blob: 9537ea0032402382e0ccdd50d27005edbd01295a [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.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"
Douglas Gregor55297ac2008-12-23 00:26:44 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000033#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000034#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000035
36using namespace clang;
37
Chris Lattner58258242008-04-10 02:22:51 +000038//===----------------------------------------------------------------------===//
39// CheckDefaultArgumentVisitor
40//===----------------------------------------------------------------------===//
41
Chris Lattnerb0d38442008-04-12 23:52:44 +000042namespace {
43 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
44 /// the default argument of a parameter to determine whether it
45 /// contains any ill-formed subexpressions. For example, this will
46 /// diagnose the use of local variables or parameters within the
47 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000048 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000049 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 Expr *DefaultArg;
51 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000052
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 public:
Mike Stump11289f42009-09-09 15:08:12 +000054 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000056
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 bool VisitExpr(Expr *Node);
58 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000059 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 };
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 /// VisitExpr - Visit all of the children of this expression.
63 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
64 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000065 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000066 E = Node->child_end(); I != E; ++I)
67 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000068 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000069 }
70
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 /// VisitDeclRefExpr - Visit a reference to a declaration, to
72 /// determine whether this declaration can be used in the default
73 /// argument expression.
74 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000076 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
77 // C++ [dcl.fct.default]p9
78 // Default arguments are evaluated each time the function is
79 // called. The order of evaluation of function arguments is
80 // unspecified. Consequently, parameters of a function shall not
81 // be used in default argument expressions, even if they are not
82 // evaluated. Parameters of a function declared before a default
83 // argument expression are in scope and can hide namespace and
84 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000085 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000087 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000088 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000089 // C++ [dcl.fct.default]p7
90 // Local variables shall not be used in default argument
91 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000092 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000093 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000095 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000096 }
Chris Lattner58258242008-04-10 02:22:51 +000097
Douglas Gregor8e12c382008-11-04 13:41:56 +000098 return false;
99 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000100
Douglas Gregor97a9c812008-11-04 14:32:21 +0000101 /// VisitCXXThisExpr - Visit a C++ "this" expression.
102 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
103 // C++ [dcl.fct.default]p8:
104 // The keyword this shall not be used in a default argument of a
105 // member function.
106 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000107 diag::err_param_default_argument_references_this)
108 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109 }
Chris Lattner58258242008-04-10 02:22:51 +0000110}
111
Anders Carlssonc80a1272009-08-25 02:29:20 +0000112bool
John McCallb268a282010-08-23 23:25:46 +0000113Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000114 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000115 if (RequireCompleteType(Param->getLocation(), Param->getType(),
116 diag::err_typecheck_decl_incomplete_type)) {
117 Param->setInvalidDecl();
118 return true;
119 }
120
Anders Carlssonc80a1272009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Douglas Gregor85dabae2009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000131 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000132 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000133 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000134 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136
Anders Carlsson6e997b22009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000142 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000143}
144
Chris Lattner58258242008-04-10 02:22:51 +0000145/// ActOnParamDefaultArgument - Check whether the default argument
146/// provided for a function parameter is well-formed. If so, attach it
147/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000148void
John McCall48871652010-08-21 09:40:31 +0000149Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000150 Expr *DefaultArg) {
151 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000152 return;
Mike Stump11289f42009-09-09 15:08:12 +0000153
John McCall48871652010-08-21 09:40:31 +0000154 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000155 UnparsedDefaultArgLocs.erase(Param);
156
Chris Lattner199abbc2008-04-08 05:04:30 +0000157 // Default arguments are only permitted in C++
158 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000159 Diag(EqualLoc, diag::err_param_default_argument)
160 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000161 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000162 return;
163 }
164
Anders Carlssonf1c26952009-08-25 01:02:06 +0000165 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000166 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
167 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000168 Param->setInvalidDecl();
169 return;
170 }
Mike Stump11289f42009-09-09 15:08:12 +0000171
John McCallb268a282010-08-23 23:25:46 +0000172 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000173}
174
Douglas Gregor58354032008-12-24 00:01:03 +0000175/// ActOnParamUnparsedDefaultArgument - We've seen a default
176/// argument for a function parameter, but we can't parse it yet
177/// because we're inside a class definition. Note that this default
178/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000179void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000180 SourceLocation EqualLoc,
181 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000182 if (!param)
183 return;
Mike Stump11289f42009-09-09 15:08:12 +0000184
John McCall48871652010-08-21 09:40:31 +0000185 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000186 if (Param)
187 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000188
Anders Carlsson84613c42009-06-12 16:51:40 +0000189 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000190}
191
Douglas Gregor4d87df52008-12-16 21:30:33 +0000192/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
193/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000194void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000195 if (!param)
196 return;
Mike Stump11289f42009-09-09 15:08:12 +0000197
John McCall48871652010-08-21 09:40:31 +0000198 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000199
Anders Carlsson84613c42009-06-12 16:51:40 +0000200 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000203}
204
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000205/// CheckExtraCXXDefaultArguments - Check for any extra default
206/// arguments in the declarator, which is not a function declaration
207/// or definition and therefore is not permitted to have default
208/// arguments. This routine should be invoked for every declarator
209/// that is not a function declaration or definition.
210void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
211 // C++ [dcl.fct.default]p3
212 // A default argument expression shall be specified only in the
213 // parameter-declaration-clause of a function declaration or in a
214 // template-parameter (14.1). It shall not be specified for a
215 // parameter pack. If it is specified in a
216 // parameter-declaration-clause, it shall not occur within a
217 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000218 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000219 DeclaratorChunk &chunk = D.getTypeObject(i);
220 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000221 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
222 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000223 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000224 if (Param->hasUnparsedDefaultArg()) {
225 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000226 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
227 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
228 delete Toks;
229 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000230 } else if (Param->getDefaultArg()) {
231 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
232 << Param->getDefaultArg()->getSourceRange();
233 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000234 }
235 }
236 }
237 }
238}
239
Chris Lattner199abbc2008-04-08 05:04:30 +0000240// MergeCXXFunctionDecl - Merge two declarations of the same C++
241// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000242// type. Subroutine of MergeFunctionDecl. Returns true if there was an
243// error, false otherwise.
244bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
245 bool Invalid = false;
246
Chris Lattner199abbc2008-04-08 05:04:30 +0000247 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000248 // For non-template functions, default arguments can be added in
249 // later declarations of a function in the same
250 // scope. Declarations in different scopes have completely
251 // distinct sets of default arguments. That is, declarations in
252 // inner scopes do not acquire default arguments from
253 // declarations in outer scopes, and vice versa. In a given
254 // function declaration, all parameters subsequent to a
255 // parameter with a default argument shall have default
256 // arguments supplied in this or previous declarations. A
257 // default argument shall not be redefined by a later
258 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000259 //
260 // C++ [dcl.fct.default]p6:
261 // Except for member functions of class templates, the default arguments
262 // in a member function definition that appears outside of the class
263 // definition are added to the set of default arguments provided by the
264 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000265 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
266 ParmVarDecl *OldParam = Old->getParamDecl(p);
267 ParmVarDecl *NewParam = New->getParamDecl(p);
268
Douglas Gregorc732aba2009-09-11 18:44:32 +0000269 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000270 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
271 // hint here. Alternatively, we could walk the type-source information
272 // for NewParam to find the last source location in the type... but it
273 // isn't worth the effort right now. This is the kind of test case that
274 // is hard to get right:
275
276 // int f(int);
277 // void g(int (*fp)(int) = f);
278 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000279 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000280 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000281 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000282
283 // Look for the function declaration where the default argument was
284 // actually written, which may be a declaration prior to Old.
285 for (FunctionDecl *Older = Old->getPreviousDeclaration();
286 Older; Older = Older->getPreviousDeclaration()) {
287 if (!Older->getParamDecl(p)->hasDefaultArg())
288 break;
289
290 OldParam = Older->getParamDecl(p);
291 }
292
293 Diag(OldParam->getLocation(), diag::note_previous_definition)
294 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000295 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000296 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000297 // Merge the old default argument into the new parameter.
298 // It's important to use getInit() here; getDefaultArg()
299 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000300 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
John McCalle61b02b2010-05-04 01:53:42 +0000305 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000356 }
357 }
358
Douglas Gregorf40863c2010-02-12 07:32:17 +0000359 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000360 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000361
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000362 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000363}
364
365/// CheckCXXDefaultArguments - Verify that the default arguments for a
366/// function declaration are well-formed according to C++
367/// [dcl.fct.default].
368void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
369 unsigned NumParams = FD->getNumParams();
370 unsigned p;
371
372 // Find first parameter with a default argument
373 for (p = 0; p < NumParams; ++p) {
374 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000375 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000376 break;
377 }
378
379 // C++ [dcl.fct.default]p4:
380 // In a given function declaration, all parameters
381 // subsequent to a parameter with a default argument shall
382 // have default arguments supplied in this or previous
383 // declarations. A default argument shall not be redefined
384 // by a later declaration (not even to the same value).
385 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000386 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000387 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000388 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 if (Param->isInvalidDecl())
390 /* We already complained about this parameter. */;
391 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000392 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000393 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000394 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000395 else
Mike Stump11289f42009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 LastMissingDefaultArg = p;
400 }
401 }
402
403 if (LastMissingDefaultArg > 0) {
404 // Some default arguments were missing. Clear out all of the
405 // default arguments up to (and including) the last missing
406 // default argument, so that we leave the function parameters
407 // in a semantically valid state.
408 for (p = 0; p <= LastMissingDefaultArg; ++p) {
409 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000410 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregor556877c2008-04-13 21:30:24 +0000416
Douglas Gregor61956c42008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000423 assert(getLangOptions().CPlusPlus && "No class names in C!");
424
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000425 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000426 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000427 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
429 } else
430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
431
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000432 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000433 return &II == CurDecl->getIdentifier();
434 else
435 return false;
436}
437
Mike Stump11289f42009-09-09 15:08:12 +0000438/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000439///
440/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
441/// and returns NULL otherwise.
442CXXBaseSpecifier *
443Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
444 SourceRange SpecifierRange,
445 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000446 TypeSourceInfo *TInfo) {
447 QualType BaseType = TInfo->getType();
448
Douglas Gregor463421d2009-03-03 04:44:36 +0000449 // C++ [class.union]p1:
450 // A union shall not have base classes.
451 if (Class->isUnion()) {
452 Diag(Class->getLocation(), diag::err_base_clause_on_union)
453 << SpecifierRange;
454 return 0;
455 }
456
457 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000458 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000459 Class->getTagKind() == TTK_Class,
460 Access, TInfo);
461
462 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000463
464 // Base specifiers must be record types.
465 if (!BaseType->isRecordType()) {
466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
467 return 0;
468 }
469
470 // C++ [class.union]p1:
471 // A union shall not be used as a base class.
472 if (BaseType->isUnionType()) {
473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
474 return 0;
475 }
476
477 // C++ [class.derived]p2:
478 // The class-name in a base-specifier shall not be an incompletely
479 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000480 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000481 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000482 << SpecifierRange)) {
483 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000484 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000485 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000486
Eli Friedmanc96d4962009-08-15 21:55:26 +0000487 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000488 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000489 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000490 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000491 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000492 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
493 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000494
Alexis Hunt96d5c762009-11-21 08:43:09 +0000495 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
496 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
497 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000498 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
499 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000500 return 0;
501 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000502
Eli Friedman89c038e2009-12-05 23:03:49 +0000503 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
John McCall3696dcb2010-08-17 07:23:57 +0000504
505 if (BaseDecl->isInvalidDecl())
506 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000507
508 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000509 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000510 Class->getTagKind() == TTK_Class,
511 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000512}
513
514void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
515 const CXXRecordDecl *BaseClass,
516 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000517 // A class with a non-empty base class is not empty.
518 // FIXME: Standard ref?
519 if (!BaseClass->isEmpty())
520 Class->setEmpty(false);
521
522 // C++ [class.virtual]p1:
523 // A class that [...] inherits a virtual function is called a polymorphic
524 // class.
525 if (BaseClass->isPolymorphic())
526 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000527
Douglas Gregor463421d2009-03-03 04:44:36 +0000528 // C++ [dcl.init.aggr]p1:
529 // An aggregate is [...] a class with [...] no base classes [...].
530 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000531
532 // C++ [class]p4:
533 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000534 Class->setPOD(false);
535
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000536 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000537 // C++ [class.ctor]p5:
538 // A constructor is trivial if its class has no virtual base classes.
539 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000540
541 // C++ [class.copy]p6:
542 // A copy constructor is trivial if its class has no virtual base classes.
543 Class->setHasTrivialCopyConstructor(false);
544
545 // C++ [class.copy]p11:
546 // A copy assignment operator is trivial if its class has no virtual
547 // base classes.
548 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000549
550 // C++0x [meta.unary.prop] is_empty:
551 // T is a class type, but not a union type, with ... no virtual base
552 // classes
553 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000554 } else {
555 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000556 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000557 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000558 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000559 Class->setHasTrivialConstructor(false);
560
561 // C++ [class.copy]p6:
562 // A copy constructor is trivial if all the direct base classes of its
563 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000564 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000565 Class->setHasTrivialCopyConstructor(false);
566
567 // C++ [class.copy]p11:
568 // A copy assignment operator is trivial if all the direct base classes
569 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000570 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000571 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000572 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000573
574 // C++ [class.ctor]p3:
575 // A destructor is trivial if all the direct base classes of its class
576 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000577 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000578 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000579}
580
Douglas Gregor556877c2008-04-13 21:30:24 +0000581/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
582/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000583/// example:
584/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000585/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000586Sema::BaseResult
John McCall48871652010-08-21 09:40:31 +0000587Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000588 bool Virtual, AccessSpecifier Access,
John McCallba7bf592010-08-24 05:47:05 +0000589 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000590 if (!classdecl)
591 return true;
592
Douglas Gregorc40290e2009-03-09 23:48:35 +0000593 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000594 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000595 if (!Class)
596 return true;
597
Nick Lewycky19b9f952010-07-26 16:56:01 +0000598 TypeSourceInfo *TInfo = 0;
599 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor463421d2009-03-03 04:44:36 +0000600 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000601 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000602 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Douglas Gregor463421d2009-03-03 04:44:36 +0000604 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000605}
Douglas Gregor556877c2008-04-13 21:30:24 +0000606
Douglas Gregor463421d2009-03-03 04:44:36 +0000607/// \brief Performs the actual work of attaching the given base class
608/// specifiers to a C++ class.
609bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
610 unsigned NumBases) {
611 if (NumBases == 0)
612 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000613
614 // Used to keep track of which base types we have already seen, so
615 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000616 // that the key is always the unqualified canonical type of the base
617 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000618 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
619
620 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000621 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000623 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000624 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000625 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000626 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000627 if (!Class->hasObjectMember()) {
628 if (const RecordType *FDTTy =
629 NewBaseType.getTypePtr()->getAs<RecordType>())
630 if (FDTTy->getDecl()->hasObjectMember())
631 Class->setHasObjectMember(true);
632 }
633
Douglas Gregor29a92472008-10-22 17:49:05 +0000634 if (KnownBaseTypes[NewBaseType]) {
635 // C++ [class.mi]p3:
636 // A class shall not be specified as a direct base class of a
637 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000639 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000640 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000642
643 // Delete the duplicate base class specifier; we're going to
644 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000645 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000646
647 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000648 } else {
649 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000650 KnownBaseTypes[NewBaseType] = Bases[idx];
651 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000652 }
653 }
654
655 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000656 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000657
658 // Delete the remaining (good) base class specifiers, since their
659 // data has been copied into the CXXRecordDecl.
660 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000661 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000662
663 return Invalid;
664}
665
666/// ActOnBaseSpecifiers - Attach the given base specifiers to the
667/// class, after checking whether there are any duplicate base
668/// classes.
John McCall48871652010-08-21 09:40:31 +0000669void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000670 unsigned NumBases) {
671 if (!ClassDecl || !Bases || !NumBases)
672 return;
673
674 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000675 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000676 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000677}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000678
John McCalle78aac42010-03-10 03:28:59 +0000679static CXXRecordDecl *GetClassForType(QualType T) {
680 if (const RecordType *RT = T->getAs<RecordType>())
681 return cast<CXXRecordDecl>(RT->getDecl());
682 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
683 return ICT->getDecl();
684 else
685 return 0;
686}
687
Douglas Gregor36d1b142009-10-06 17:59:45 +0000688/// \brief Determine whether the type \p Derived is a C++ class that is
689/// derived from the type \p Base.
690bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
691 if (!getLangOptions().CPlusPlus)
692 return false;
John McCalle78aac42010-03-10 03:28:59 +0000693
694 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
695 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000696 return false;
697
John McCalle78aac42010-03-10 03:28:59 +0000698 CXXRecordDecl *BaseRD = GetClassForType(Base);
699 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000700 return false;
701
John McCall67da35c2010-02-04 22:26:26 +0000702 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
703 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000704}
705
706/// \brief Determine whether the type \p Derived is a C++ class that is
707/// derived from the type \p Base.
708bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
709 if (!getLangOptions().CPlusPlus)
710 return false;
711
John McCalle78aac42010-03-10 03:28:59 +0000712 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
713 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000714 return false;
715
John McCalle78aac42010-03-10 03:28:59 +0000716 CXXRecordDecl *BaseRD = GetClassForType(Base);
717 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000718 return false;
719
Douglas Gregor36d1b142009-10-06 17:59:45 +0000720 return DerivedRD->isDerivedFrom(BaseRD, Paths);
721}
722
Anders Carlssona70cff62010-04-24 19:06:50 +0000723void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000724 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000725 assert(BasePathArray.empty() && "Base path array must be empty!");
726 assert(Paths.isRecordingPaths() && "Must record paths!");
727
728 const CXXBasePath &Path = Paths.front();
729
730 // We first go backward and check if we have a virtual base.
731 // FIXME: It would be better if CXXBasePath had the base specifier for
732 // the nearest virtual base.
733 unsigned Start = 0;
734 for (unsigned I = Path.size(); I != 0; --I) {
735 if (Path[I - 1].Base->isVirtual()) {
736 Start = I - 1;
737 break;
738 }
739 }
740
741 // Now add all bases.
742 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000743 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000744}
745
Douglas Gregor88d292c2010-05-13 16:44:06 +0000746/// \brief Determine whether the given base path includes a virtual
747/// base class.
John McCallcf142162010-08-07 06:22:56 +0000748bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
749 for (CXXCastPath::const_iterator B = BasePath.begin(),
750 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000751 B != BEnd; ++B)
752 if ((*B)->isVirtual())
753 return true;
754
755 return false;
756}
757
Douglas Gregor36d1b142009-10-06 17:59:45 +0000758/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
759/// conversion (where Derived and Base are class types) is
760/// well-formed, meaning that the conversion is unambiguous (and
761/// that all of the base classes are accessible). Returns true
762/// and emits a diagnostic if the code is ill-formed, returns false
763/// otherwise. Loc is the location where this routine should point to
764/// if there is an error, and Range is the source range to highlight
765/// if there is an error.
766bool
767Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000768 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000769 unsigned AmbigiousBaseConvID,
770 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000771 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000772 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000773 // First, determine whether the path from Derived to Base is
774 // ambiguous. This is slightly more expensive than checking whether
775 // the Derived to Base conversion exists, because here we need to
776 // explore multiple paths to determine if there is an ambiguity.
777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
778 /*DetectVirtual=*/false);
779 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
780 assert(DerivationOkay &&
781 "Can only be used with a derived-to-base conversion");
782 (void)DerivationOkay;
783
784 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000785 if (InaccessibleBaseID) {
786 // Check that the base class can be accessed.
787 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
788 InaccessibleBaseID)) {
789 case AR_inaccessible:
790 return true;
791 case AR_accessible:
792 case AR_dependent:
793 case AR_delayed:
794 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000795 }
John McCall5b0829a2010-02-10 09:31:12 +0000796 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000797
798 // Build a base path if necessary.
799 if (BasePath)
800 BuildBasePathArray(Paths, *BasePath);
801 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000802 }
803
804 // We know that the derived-to-base conversion is ambiguous, and
805 // we're going to produce a diagnostic. Perform the derived-to-base
806 // search just one more time to compute all of the possible paths so
807 // that we can print them out. This is more expensive than any of
808 // the previous derived-to-base checks we've done, but at this point
809 // performance isn't as much of an issue.
810 Paths.clear();
811 Paths.setRecordingPaths(true);
812 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
813 assert(StillOkay && "Can only be used with a derived-to-base conversion");
814 (void)StillOkay;
815
816 // Build up a textual representation of the ambiguous paths, e.g.,
817 // D -> B -> A, that will be used to illustrate the ambiguous
818 // conversions in the diagnostic. We only print one of the paths
819 // to each base class subobject.
820 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
821
822 Diag(Loc, AmbigiousBaseConvID)
823 << Derived << Base << PathDisplayStr << Range << Name;
824 return true;
825}
826
827bool
828Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000829 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000830 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000831 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000832 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000833 IgnoreAccess ? 0
834 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000835 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000836 Loc, Range, DeclarationName(),
837 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000838}
839
840
841/// @brief Builds a string representing ambiguous paths from a
842/// specific derived class to different subobjects of the same base
843/// class.
844///
845/// This function builds a string that can be used in error messages
846/// to show the different paths that one can take through the
847/// inheritance hierarchy to go from the derived class to different
848/// subobjects of a base class. The result looks something like this:
849/// @code
850/// struct D -> struct B -> struct A
851/// struct D -> struct C -> struct A
852/// @endcode
853std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
854 std::string PathDisplayStr;
855 std::set<unsigned> DisplayedPaths;
856 for (CXXBasePaths::paths_iterator Path = Paths.begin();
857 Path != Paths.end(); ++Path) {
858 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
859 // We haven't displayed a path to this particular base
860 // class subobject yet.
861 PathDisplayStr += "\n ";
862 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
863 for (CXXBasePath::const_iterator Element = Path->begin();
864 Element != Path->end(); ++Element)
865 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
866 }
867 }
868
869 return PathDisplayStr;
870}
871
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000872//===----------------------------------------------------------------------===//
873// C++ class member Handling
874//===----------------------------------------------------------------------===//
875
Abramo Bagnarad7340582010-06-05 05:09:32 +0000876/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000877Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
878 SourceLocation ASLoc,
879 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000880 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000881 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000882 ASLoc, ColonLoc);
883 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000884 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000885}
886
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000887/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
888/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
889/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000890/// any.
John McCall48871652010-08-21 09:40:31 +0000891Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000892Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000893 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000894 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
895 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000896 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000897 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
898 DeclarationName Name = NameInfo.getName();
899 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000900 Expr *BitWidth = static_cast<Expr*>(BW);
901 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000902
John McCallb1cd7da2010-06-04 08:34:12 +0000903 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000904 assert(!DS.isFriendSpecified());
905
John McCallb1cd7da2010-06-04 08:34:12 +0000906 bool isFunc = false;
907 if (D.isFunctionDeclarator())
908 isFunc = true;
909 else if (D.getNumTypeObjects() == 0 &&
910 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000911 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000912 isFunc = TDType->isFunctionType();
913 }
914
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915 // C++ 9.2p6: A member shall not be declared to have automatic storage
916 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000917 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
918 // data members and cannot be applied to names declared const or static,
919 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000920 switch (DS.getStorageClassSpec()) {
921 case DeclSpec::SCS_unspecified:
922 case DeclSpec::SCS_typedef:
923 case DeclSpec::SCS_static:
924 // FALL THROUGH.
925 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000926 case DeclSpec::SCS_mutable:
927 if (isFunc) {
928 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000929 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000930 else
Chris Lattner3b054132008-11-19 05:08:23 +0000931 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Sebastian Redl8071edb2008-11-17 23:24:37 +0000933 // FIXME: It would be nicer if the keyword was ignored only for this
934 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000935 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000936 }
937 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000938 default:
939 if (DS.getStorageClassSpecLoc().isValid())
940 Diag(DS.getStorageClassSpecLoc(),
941 diag::err_storageclass_invalid_for_member);
942 else
943 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
944 D.getMutableDeclSpec().ClearStorageClassSpecs();
945 }
946
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000947 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
948 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000949 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000950
951 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000952 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000953 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000954 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
955 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000956 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000957 } else {
John McCall48871652010-08-21 09:40:31 +0000958 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000959 if (!Member) {
960 if (BitWidth) DeleteExpr(BitWidth);
John McCall48871652010-08-21 09:40:31 +0000961 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000962 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000963
964 // Non-instance-fields can't have a bitfield.
965 if (BitWidth) {
966 if (Member->isInvalidDecl()) {
967 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000968 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000969 // C++ 9.6p3: A bit-field shall not be a static member.
970 // "static member 'A' cannot be a bit-field"
971 Diag(Loc, diag::err_static_not_bitfield)
972 << Name << BitWidth->getSourceRange();
973 } else if (isa<TypedefDecl>(Member)) {
974 // "typedef member 'x' cannot be a bit-field"
975 Diag(Loc, diag::err_typedef_not_bitfield)
976 << Name << BitWidth->getSourceRange();
977 } else {
978 // A function typedef ("typedef int f(); f a;").
979 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
980 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000981 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000982 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattnerd26760a2009-03-05 23:01:03 +0000985 DeleteExpr(BitWidth);
986 BitWidth = 0;
987 Member->setInvalidDecl();
988 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000989
990 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor3447e762009-08-20 22:52:58 +0000992 // If we have declared a member function template, set the access of the
993 // templated declaration as well.
994 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
995 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000996 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997
Douglas Gregor92751d42008-11-17 22:58:34 +0000998 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000999
Douglas Gregor0c880302009-03-11 23:00:04 +00001000 if (Init)
John McCallb268a282010-08-23 23:25:46 +00001001 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001002 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001003 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001004
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001005 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001006 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001007 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001008 }
John McCall48871652010-08-21 09:40:31 +00001009 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001010}
1011
Douglas Gregor15e77a22009-12-31 09:10:24 +00001012/// \brief Find the direct and/or virtual base specifiers that
1013/// correspond to the given base type, for use in base initialization
1014/// within a constructor.
1015static bool FindBaseInitializer(Sema &SemaRef,
1016 CXXRecordDecl *ClassDecl,
1017 QualType BaseType,
1018 const CXXBaseSpecifier *&DirectBaseSpec,
1019 const CXXBaseSpecifier *&VirtualBaseSpec) {
1020 // First, check for a direct base class.
1021 DirectBaseSpec = 0;
1022 for (CXXRecordDecl::base_class_const_iterator Base
1023 = ClassDecl->bases_begin();
1024 Base != ClassDecl->bases_end(); ++Base) {
1025 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1026 // We found a direct base of this type. That's what we're
1027 // initializing.
1028 DirectBaseSpec = &*Base;
1029 break;
1030 }
1031 }
1032
1033 // Check for a virtual base class.
1034 // FIXME: We might be able to short-circuit this if we know in advance that
1035 // there are no virtual bases.
1036 VirtualBaseSpec = 0;
1037 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1038 // We haven't found a base yet; search the class hierarchy for a
1039 // virtual base class.
1040 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1041 /*DetectVirtual=*/false);
1042 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1043 BaseType, Paths)) {
1044 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1045 Path != Paths.end(); ++Path) {
1046 if (Path->back().Base->isVirtual()) {
1047 VirtualBaseSpec = Path->back().Base;
1048 break;
1049 }
1050 }
1051 }
1052 }
1053
1054 return DirectBaseSpec || VirtualBaseSpec;
1055}
1056
Douglas Gregore8381c02008-11-05 04:29:56 +00001057/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001058Sema::MemInitResult
John McCall48871652010-08-21 09:40:31 +00001059Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001060 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001061 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001062 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001063 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001064 SourceLocation IdLoc,
1065 SourceLocation LParenLoc,
1066 ExprTy **Args, unsigned NumArgs,
1067 SourceLocation *CommaLocs,
1068 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001069 if (!ConstructorD)
1070 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001072 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001073
1074 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001075 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001076 if (!Constructor) {
1077 // The user wrote a constructor initializer on a function that is
1078 // not a C++ constructor. Ignore the error for now, because we may
1079 // have more member initializers coming; we'll diagnose it just
1080 // once in ActOnMemInitializers.
1081 return true;
1082 }
1083
1084 CXXRecordDecl *ClassDecl = Constructor->getParent();
1085
1086 // C++ [class.base.init]p2:
1087 // Names in a mem-initializer-id are looked up in the scope of the
1088 // constructor’s class and, if not found in that scope, are looked
1089 // up in the scope containing the constructor’s
1090 // definition. [Note: if the constructor’s class contains a member
1091 // with the same name as a direct or virtual base class of the
1092 // class, a mem-initializer-id naming the member or base class and
1093 // composed of a single identifier refers to the class member. A
1094 // mem-initializer-id for the hidden base class may be specified
1095 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001096 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001097 // Look for a member, first.
1098 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001099 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001100 = ClassDecl->lookup(MemberOrBase);
1101 if (Result.first != Result.second)
1102 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001103
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001104 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001105
Eli Friedman8e1433b2009-07-29 19:44:27 +00001106 if (Member)
1107 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001108 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001109 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001110 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001111 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001112 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001113
1114 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001115 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001116 } else {
1117 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1118 LookupParsedName(R, S, &SS);
1119
1120 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1121 if (!TyD) {
1122 if (R.isAmbiguous()) return true;
1123
John McCallda6841b2010-04-09 19:01:14 +00001124 // We don't want access-control diagnostics here.
1125 R.suppressDiagnostics();
1126
Douglas Gregora3b624a2010-01-19 06:46:48 +00001127 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1128 bool NotUnknownSpecialization = false;
1129 DeclContext *DC = computeDeclContext(SS, false);
1130 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1131 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1132
1133 if (!NotUnknownSpecialization) {
1134 // When the scope specifier can refer to a member of an unknown
1135 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001136 BaseType = CheckTypenameType(ETK_None,
1137 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001138 *MemberOrBase, SourceLocation(),
1139 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001140 if (BaseType.isNull())
1141 return true;
1142
Douglas Gregora3b624a2010-01-19 06:46:48 +00001143 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001144 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001145 }
1146 }
1147
Douglas Gregor15e77a22009-12-31 09:10:24 +00001148 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001149 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001150 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1151 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001152 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1153 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1154 // We have found a non-static data member with a similar
1155 // name to what was typed; complain and initialize that
1156 // member.
1157 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1158 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001159 << FixItHint::CreateReplacement(R.getNameLoc(),
1160 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001161 Diag(Member->getLocation(), diag::note_previous_decl)
1162 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001163
1164 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1165 LParenLoc, RParenLoc);
1166 }
1167 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1168 const CXXBaseSpecifier *DirectBaseSpec;
1169 const CXXBaseSpecifier *VirtualBaseSpec;
1170 if (FindBaseInitializer(*this, ClassDecl,
1171 Context.getTypeDeclType(Type),
1172 DirectBaseSpec, VirtualBaseSpec)) {
1173 // We have found a direct or virtual base class with a
1174 // similar name to what was typed; complain and initialize
1175 // that base class.
1176 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1177 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001178 << FixItHint::CreateReplacement(R.getNameLoc(),
1179 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001180
1181 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1182 : VirtualBaseSpec;
1183 Diag(BaseSpec->getSourceRange().getBegin(),
1184 diag::note_base_class_specified_here)
1185 << BaseSpec->getType()
1186 << BaseSpec->getSourceRange();
1187
Douglas Gregor15e77a22009-12-31 09:10:24 +00001188 TyD = Type;
1189 }
1190 }
1191 }
1192
Douglas Gregora3b624a2010-01-19 06:46:48 +00001193 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001194 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1195 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1196 return true;
1197 }
John McCallb5a0d312009-12-21 10:41:20 +00001198 }
1199
Douglas Gregora3b624a2010-01-19 06:46:48 +00001200 if (BaseType.isNull()) {
1201 BaseType = Context.getTypeDeclType(TyD);
1202 if (SS.isSet()) {
1203 NestedNameSpecifier *Qualifier =
1204 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001205
Douglas Gregora3b624a2010-01-19 06:46:48 +00001206 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001207 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001208 }
John McCallb5a0d312009-12-21 10:41:20 +00001209 }
1210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
John McCallbcd03502009-12-07 02:54:59 +00001212 if (!TInfo)
1213 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001214
John McCallbcd03502009-12-07 02:54:59 +00001215 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001216 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001217}
1218
John McCalle22a04a2009-11-04 23:02:40 +00001219/// Checks an initializer expression for use of uninitialized fields, such as
1220/// containing the field that is being initialized. Returns true if there is an
1221/// uninitialized field was used an updates the SourceLocation parameter; false
1222/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001223static bool InitExprContainsUninitializedFields(const Stmt *S,
1224 const FieldDecl *LhsField,
1225 SourceLocation *L) {
1226 if (isa<CallExpr>(S)) {
1227 // Do not descend into function calls or constructors, as the use
1228 // of an uninitialized field may be valid. One would have to inspect
1229 // the contents of the function/ctor to determine if it is safe or not.
1230 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1231 // may be safe, depending on what the function/ctor does.
1232 return false;
1233 }
1234 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1235 const NamedDecl *RhsField = ME->getMemberDecl();
John McCalle22a04a2009-11-04 23:02:40 +00001236 if (RhsField == LhsField) {
1237 // Initializing a field with itself. Throw a warning.
1238 // But wait; there are exceptions!
1239 // Exception #1: The field may not belong to this record.
1240 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001241 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001242 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1243 // Even though the field matches, it does not belong to this record.
1244 return false;
1245 }
1246 // None of the exceptions triggered; return true to indicate an
1247 // uninitialized field was used.
1248 *L = ME->getMemberLoc();
1249 return true;
1250 }
1251 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001252 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1253 it != e; ++it) {
1254 if (!*it) {
1255 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001256 continue;
1257 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001258 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1259 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001260 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001261 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001262}
1263
Eli Friedman8e1433b2009-07-29 19:44:27 +00001264Sema::MemInitResult
1265Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1266 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001267 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001268 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001269 // Diagnose value-uses of fields to initialize themselves, e.g.
1270 // foo(foo)
1271 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001272 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001273 for (unsigned i = 0; i < NumArgs; ++i) {
1274 SourceLocation L;
1275 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1276 // FIXME: Return true in the case when other fields are used before being
1277 // uninitialized. For example, let this field be the i'th field. When
1278 // initializing the i'th field, throw a warning if any of the >= i'th
1279 // fields are used, as they are not yet initialized.
1280 // Right now we are only handling the case where the i'th field uses
1281 // itself in its initializer.
1282 Diag(L, diag::warn_field_is_uninit);
1283 }
1284 }
1285
Eli Friedman8e1433b2009-07-29 19:44:27 +00001286 bool HasDependentArg = false;
1287 for (unsigned i = 0; i < NumArgs; i++)
1288 HasDependentArg |= Args[i]->isTypeDependent();
1289
Eli Friedman9255adf2010-07-24 21:19:15 +00001290 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001291 // Can't check initialization for a member of dependent type or when
1292 // any of the arguments are type-dependent expressions.
John McCallb268a282010-08-23 23:25:46 +00001293 Expr *Init
1294 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1295 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001296
1297 // Erase any temporaries within this evaluation context; we're not
1298 // going to track them in the AST, since we'll be rebuilding the
1299 // ASTs during template instantiation.
1300 ExprTemporaries.erase(
1301 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1302 ExprTemporaries.end());
1303
1304 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1305 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001306 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001307 RParenLoc);
1308
Douglas Gregore8381c02008-11-05 04:29:56 +00001309 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001310
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001311 if (Member->isInvalidDecl())
1312 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001313
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001314 // Initialize the member.
1315 InitializedEntity MemberEntity =
1316 InitializedEntity::InitializeMember(Member, 0);
1317 InitializationKind Kind =
1318 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1319
1320 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1321
John McCalldadc5752010-08-24 06:29:42 +00001322 ExprResult MemberInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001323 InitSeq.Perform(*this, MemberEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001324 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001325 if (MemberInit.isInvalid())
1326 return true;
1327
1328 // C++0x [class.base.init]p7:
1329 // The initialization of each base and member constitutes a
1330 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001331 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001332 if (MemberInit.isInvalid())
1333 return true;
1334
1335 // If we are in a dependent context, template instantiation will
1336 // perform this type-checking again. Just save the arguments that we
1337 // received in a ParenListExpr.
1338 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1339 // of the information that we have about the member
1340 // initializer. However, deconstructing the ASTs is a dicey process,
1341 // and this approach is far more likely to get the corner cases right.
1342 if (CurContext->isDependentContext()) {
1343 // Bump the reference count of all of the arguments.
1344 for (unsigned I = 0; I != NumArgs; ++I)
1345 Args[I]->Retain();
1346
John McCallb268a282010-08-23 23:25:46 +00001347 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1348 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001349 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1350 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001351 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001352 RParenLoc);
1353 }
1354
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001355 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001356 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001357 MemberInit.get(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001358 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001359}
1360
1361Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001362Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001363 Expr **Args, unsigned NumArgs,
1364 SourceLocation LParenLoc, SourceLocation RParenLoc,
1365 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001366 bool HasDependentArg = false;
1367 for (unsigned i = 0; i < NumArgs; i++)
1368 HasDependentArg |= Args[i]->isTypeDependent();
1369
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001370 SourceLocation BaseLoc
1371 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1372
1373 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1374 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1375 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1376
1377 // C++ [class.base.init]p2:
1378 // [...] Unless the mem-initializer-id names a nonstatic data
1379 // member of the constructor’s class or a direct or virtual base
1380 // of that class, the mem-initializer is ill-formed. A
1381 // mem-initializer-list can initialize a base class using any
1382 // name that denotes that base class type.
1383 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1384
1385 // Check for direct and virtual base classes.
1386 const CXXBaseSpecifier *DirectBaseSpec = 0;
1387 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1388 if (!Dependent) {
1389 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1390 VirtualBaseSpec);
1391
1392 // C++ [base.class.init]p2:
1393 // Unless the mem-initializer-id names a nonstatic data member of the
1394 // constructor's class or a direct or virtual base of that class, the
1395 // mem-initializer is ill-formed.
1396 if (!DirectBaseSpec && !VirtualBaseSpec) {
1397 // If the class has any dependent bases, then it's possible that
1398 // one of those types will resolve to the same type as
1399 // BaseType. Therefore, just treat this as a dependent base
1400 // class initialization. FIXME: Should we try to check the
1401 // initialization anyway? It seems odd.
1402 if (ClassDecl->hasAnyDependentBases())
1403 Dependent = true;
1404 else
1405 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1406 << BaseType << Context.getTypeDeclType(ClassDecl)
1407 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1408 }
1409 }
1410
1411 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001412 // Can't check initialization for a base of dependent type or when
1413 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001414 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1416 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001417
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001418 // Erase any temporaries within this evaluation context; we're not
1419 // going to track them in the AST, since we'll be rebuilding the
1420 // ASTs during template instantiation.
1421 ExprTemporaries.erase(
1422 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1423 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001424
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001425 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001426 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001427 LParenLoc,
1428 BaseInit.takeAs<Expr>(),
1429 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001430 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001431
1432 // C++ [base.class.init]p2:
1433 // If a mem-initializer-id is ambiguous because it designates both
1434 // a direct non-virtual base class and an inherited virtual base
1435 // class, the mem-initializer is ill-formed.
1436 if (DirectBaseSpec && VirtualBaseSpec)
1437 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001438 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001439
1440 CXXBaseSpecifier *BaseSpec
1441 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1442 if (!BaseSpec)
1443 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1444
1445 // Initialize the base.
1446 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001447 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001448 InitializationKind Kind =
1449 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1450
1451 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1452
John McCalldadc5752010-08-24 06:29:42 +00001453 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001454 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001455 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001456 if (BaseInit.isInvalid())
1457 return true;
1458
1459 // C++0x [class.base.init]p7:
1460 // The initialization of each base and member constitutes a
1461 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001462 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001463 if (BaseInit.isInvalid())
1464 return true;
1465
1466 // If we are in a dependent context, template instantiation will
1467 // perform this type-checking again. Just save the arguments that we
1468 // received in a ParenListExpr.
1469 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1470 // of the information that we have about the base
1471 // initializer. However, deconstructing the ASTs is a dicey process,
1472 // and this approach is far more likely to get the corner cases right.
1473 if (CurContext->isDependentContext()) {
1474 // Bump the reference count of all of the arguments.
1475 for (unsigned I = 0; I != NumArgs; ++I)
1476 Args[I]->Retain();
1477
John McCalldadc5752010-08-24 06:29:42 +00001478 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001479 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1480 RParenLoc));
1481 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001482 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001483 LParenLoc,
1484 Init.takeAs<Expr>(),
1485 RParenLoc);
1486 }
1487
1488 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001489 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001490 LParenLoc,
1491 BaseInit.takeAs<Expr>(),
1492 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001493}
1494
Anders Carlsson1b00e242010-04-23 03:10:23 +00001495/// ImplicitInitializerKind - How an implicit base or member initializer should
1496/// initialize its base or member.
1497enum ImplicitInitializerKind {
1498 IIK_Default,
1499 IIK_Copy,
1500 IIK_Move
1501};
1502
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001503static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001504BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001505 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001506 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001507 bool IsInheritedVirtualBase,
1508 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001509 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001510 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1511 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001512
John McCalldadc5752010-08-24 06:29:42 +00001513 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001514
1515 switch (ImplicitInitKind) {
1516 case IIK_Default: {
1517 InitializationKind InitKind
1518 = InitializationKind::CreateDefault(Constructor->getLocation());
1519 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1520 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1521 Sema::MultiExprArg(SemaRef, 0, 0));
1522 break;
1523 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001524
Anders Carlsson1b00e242010-04-23 03:10:23 +00001525 case IIK_Copy: {
1526 ParmVarDecl *Param = Constructor->getParamDecl(0);
1527 QualType ParamType = Param->getType().getNonReferenceType();
1528
1529 Expr *CopyCtorArg =
1530 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001531 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001532
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001533 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001534 QualType ArgTy =
1535 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1536 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001537
1538 CXXCastPath BasePath;
1539 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001540 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001541 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00001542 ImplicitCastExpr::LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001543
Anders Carlsson1b00e242010-04-23 03:10:23 +00001544 InitializationKind InitKind
1545 = InitializationKind::CreateDirect(Constructor->getLocation(),
1546 SourceLocation(), SourceLocation());
1547 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1548 &CopyCtorArg, 1);
1549 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1550 Sema::MultiExprArg(SemaRef,
John McCall37ad5512010-08-23 06:44:23 +00001551 &CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001552 break;
1553 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001554
Anders Carlsson1b00e242010-04-23 03:10:23 +00001555 case IIK_Move:
1556 assert(false && "Unhandled initializer kind!");
1557 }
John McCallb268a282010-08-23 23:25:46 +00001558
1559 if (BaseInit.isInvalid())
1560 return true;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001561
John McCallb268a282010-08-23 23:25:46 +00001562 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001563 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001564 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001565
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001566 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001567 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1568 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1569 SourceLocation()),
1570 BaseSpec->isVirtual(),
1571 SourceLocation(),
1572 BaseInit.takeAs<Expr>(),
1573 SourceLocation());
1574
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001575 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001576}
1577
Anders Carlsson3c1db572010-04-23 02:15:47 +00001578static bool
1579BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001580 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001581 FieldDecl *Field,
1582 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001583 if (Field->isInvalidDecl())
1584 return true;
1585
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001586 SourceLocation Loc = Constructor->getLocation();
1587
Anders Carlsson423f5d82010-04-23 16:04:08 +00001588 if (ImplicitInitKind == IIK_Copy) {
1589 ParmVarDecl *Param = Constructor->getParamDecl(0);
1590 QualType ParamType = Param->getType().getNonReferenceType();
1591
1592 Expr *MemberExprBase =
1593 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001594 Loc, ParamType, 0);
1595
1596 // Build a reference to this field within the parameter.
1597 CXXScopeSpec SS;
1598 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1599 Sema::LookupMemberName);
1600 MemberLookup.addDecl(Field, AS_public);
1601 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001602 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001603 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001604 ParamType, Loc,
1605 /*IsArrow=*/false,
1606 SS,
1607 /*FirstQualifierInScope=*/0,
1608 MemberLookup,
1609 /*TemplateArgs=*/0);
1610 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001611 return true;
1612
Douglas Gregor94f9a482010-05-05 05:51:00 +00001613 // When the field we are copying is an array, create index variables for
1614 // each dimension of the array. We use these index variables to subscript
1615 // the source array, and other clients (e.g., CodeGen) will perform the
1616 // necessary iteration with these index variables.
1617 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1618 QualType BaseType = Field->getType();
1619 QualType SizeType = SemaRef.Context.getSizeType();
1620 while (const ConstantArrayType *Array
1621 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1622 // Create the iteration variable for this array index.
1623 IdentifierInfo *IterationVarName = 0;
1624 {
1625 llvm::SmallString<8> Str;
1626 llvm::raw_svector_ostream OS(Str);
1627 OS << "__i" << IndexVariables.size();
1628 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1629 }
1630 VarDecl *IterationVar
1631 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1632 IterationVarName, SizeType,
1633 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1634 VarDecl::None, VarDecl::None);
1635 IndexVariables.push_back(IterationVar);
1636
1637 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001638 ExprResult IterationVarRef
Douglas Gregor94f9a482010-05-05 05:51:00 +00001639 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1640 assert(!IterationVarRef.isInvalid() &&
1641 "Reference to invented variable cannot fail!");
1642
1643 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001644 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001645 Loc,
John McCallb268a282010-08-23 23:25:46 +00001646 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001647 Loc);
1648 if (CopyCtorArg.isInvalid())
1649 return true;
1650
1651 BaseType = Array->getElementType();
1652 }
1653
1654 // Construct the entity that we will be initializing. For an array, this
1655 // will be first element in the array, which may require several levels
1656 // of array-subscript entities.
1657 llvm::SmallVector<InitializedEntity, 4> Entities;
1658 Entities.reserve(1 + IndexVariables.size());
1659 Entities.push_back(InitializedEntity::InitializeMember(Field));
1660 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1661 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1662 0,
1663 Entities.back()));
1664
1665 // Direct-initialize to use the copy constructor.
1666 InitializationKind InitKind =
1667 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1668
1669 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1670 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1671 &CopyCtorArgE, 1);
1672
John McCalldadc5752010-08-24 06:29:42 +00001673 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001674 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCall37ad5512010-08-23 06:44:23 +00001675 Sema::MultiExprArg(SemaRef, &CopyCtorArgE, 1));
John McCallb268a282010-08-23 23:25:46 +00001676 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor94f9a482010-05-05 05:51:00 +00001677 if (MemberInit.isInvalid())
1678 return true;
1679
1680 CXXMemberInit
1681 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1682 MemberInit.takeAs<Expr>(), Loc,
1683 IndexVariables.data(),
1684 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001685 return false;
1686 }
1687
Anders Carlsson423f5d82010-04-23 16:04:08 +00001688 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1689
Anders Carlsson3c1db572010-04-23 02:15:47 +00001690 QualType FieldBaseElementType =
1691 SemaRef.Context.getBaseElementType(Field->getType());
1692
Anders Carlsson3c1db572010-04-23 02:15:47 +00001693 if (FieldBaseElementType->isRecordType()) {
1694 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001695 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001696 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001697
1698 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001699 ExprResult MemberInit =
Anders Carlsson3c1db572010-04-23 02:15:47 +00001700 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1701 Sema::MultiExprArg(SemaRef, 0, 0));
John McCallb268a282010-08-23 23:25:46 +00001702 if (MemberInit.isInvalid())
1703 return true;
1704
1705 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001706 if (MemberInit.isInvalid())
1707 return true;
1708
1709 CXXMemberInit =
1710 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001711 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001712 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001713 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001714 return false;
1715 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001716
1717 if (FieldBaseElementType->isReferenceType()) {
1718 SemaRef.Diag(Constructor->getLocation(),
1719 diag::err_uninitialized_member_in_ctor)
1720 << (int)Constructor->isImplicit()
1721 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1722 << 0 << Field->getDeclName();
1723 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1724 return true;
1725 }
1726
1727 if (FieldBaseElementType.isConstQualified()) {
1728 SemaRef.Diag(Constructor->getLocation(),
1729 diag::err_uninitialized_member_in_ctor)
1730 << (int)Constructor->isImplicit()
1731 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1732 << 1 << Field->getDeclName();
1733 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1734 return true;
1735 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001736
1737 // Nothing to initialize.
1738 CXXMemberInit = 0;
1739 return false;
1740}
John McCallbc83b3f2010-05-20 23:23:51 +00001741
1742namespace {
1743struct BaseAndFieldInfo {
1744 Sema &S;
1745 CXXConstructorDecl *Ctor;
1746 bool AnyErrorsInInits;
1747 ImplicitInitializerKind IIK;
1748 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1749 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1750
1751 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1752 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1753 // FIXME: Handle implicit move constructors.
1754 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1755 IIK = IIK_Copy;
1756 else
1757 IIK = IIK_Default;
1758 }
1759};
1760}
1761
Chandler Carruth139e9622010-06-30 02:59:29 +00001762static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1763 FieldDecl *Top, FieldDecl *Field,
1764 CXXBaseOrMemberInitializer *Init) {
1765 // If the member doesn't need to be initialized, Init will still be null.
1766 if (!Init)
1767 return;
1768
1769 Info.AllToInit.push_back(Init);
1770 if (Field != Top) {
1771 Init->setMember(Top);
1772 Init->setAnonUnionMember(Field);
1773 }
1774}
1775
John McCallbc83b3f2010-05-20 23:23:51 +00001776static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1777 FieldDecl *Top, FieldDecl *Field) {
1778
Chandler Carruth139e9622010-06-30 02:59:29 +00001779 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001780 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001781 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001782 return false;
1783 }
1784
1785 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1786 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1787 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001788 CXXRecordDecl *FieldClassDecl
1789 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001790
1791 // Even though union members never have non-trivial default
1792 // constructions in C++03, we still build member initializers for aggregate
1793 // record types which can be union members, and C++0x allows non-trivial
1794 // default constructors for union members, so we ensure that only one
1795 // member is initialized for these.
1796 if (FieldClassDecl->isUnion()) {
1797 // First check for an explicit initializer for one field.
1798 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1799 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1800 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1801 RecordFieldInitializer(Info, Top, *FA, Init);
1802
1803 // Once we've initialized a field of an anonymous union, the union
1804 // field in the class is also initialized, so exit immediately.
1805 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001806 } else if ((*FA)->isAnonymousStructOrUnion()) {
1807 if (CollectFieldInitializer(Info, Top, *FA))
1808 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001809 }
1810 }
1811
1812 // Fallthrough and construct a default initializer for the union as
1813 // a whole, which can call its default constructor if such a thing exists
1814 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1815 // behavior going forward with C++0x, when anonymous unions there are
1816 // finalized, we should revisit this.
1817 } else {
1818 // For structs, we simply descend through to initialize all members where
1819 // necessary.
1820 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1821 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1822 if (CollectFieldInitializer(Info, Top, *FA))
1823 return true;
1824 }
1825 }
John McCallbc83b3f2010-05-20 23:23:51 +00001826 }
1827
1828 // Don't try to build an implicit initializer if there were semantic
1829 // errors in any of the initializers (and therefore we might be
1830 // missing some that the user actually wrote).
1831 if (Info.AnyErrorsInInits)
1832 return false;
1833
1834 CXXBaseOrMemberInitializer *Init = 0;
1835 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1836 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001837
Chandler Carruth139e9622010-06-30 02:59:29 +00001838 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001839 return false;
1840}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001841
Eli Friedman9cf6b592009-11-09 19:20:36 +00001842bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001843Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001844 CXXBaseOrMemberInitializer **Initializers,
1845 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001846 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001847 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001848 // Just store the initializers as written, they will be checked during
1849 // instantiation.
1850 if (NumInitializers > 0) {
1851 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1852 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1853 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1854 memcpy(baseOrMemberInitializers, Initializers,
1855 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1856 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1857 }
1858
1859 return false;
1860 }
1861
John McCallbc83b3f2010-05-20 23:23:51 +00001862 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001863
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001864 // We need to build the initializer AST according to order of construction
1865 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001866 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001867 if (!ClassDecl)
1868 return true;
1869
Eli Friedman9cf6b592009-11-09 19:20:36 +00001870 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001871
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001872 for (unsigned i = 0; i < NumInitializers; i++) {
1873 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001874
1875 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001876 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001877 else
John McCallbc83b3f2010-05-20 23:23:51 +00001878 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001879 }
1880
Anders Carlsson43c64af2010-04-21 19:52:01 +00001881 // Keep track of the direct virtual bases.
1882 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1883 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1884 E = ClassDecl->bases_end(); I != E; ++I) {
1885 if (I->isVirtual())
1886 DirectVBases.insert(I);
1887 }
1888
Anders Carlssondb0a9652010-04-02 06:26:44 +00001889 // Push virtual bases before others.
1890 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1891 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1892
1893 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001894 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1895 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001896 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001897 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001898 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001899 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001900 VBase, IsInheritedVirtualBase,
1901 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001902 HadError = true;
1903 continue;
1904 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001905
John McCallbc83b3f2010-05-20 23:23:51 +00001906 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001907 }
1908 }
Mike Stump11289f42009-09-09 15:08:12 +00001909
John McCallbc83b3f2010-05-20 23:23:51 +00001910 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001911 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1912 E = ClassDecl->bases_end(); Base != E; ++Base) {
1913 // Virtuals are in the virtual base list and already constructed.
1914 if (Base->isVirtual())
1915 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001916
Anders Carlssondb0a9652010-04-02 06:26:44 +00001917 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001918 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1919 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001920 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001921 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001922 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001923 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001924 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001925 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001926 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001927 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001928
John McCallbc83b3f2010-05-20 23:23:51 +00001929 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001930 }
1931 }
Mike Stump11289f42009-09-09 15:08:12 +00001932
John McCallbc83b3f2010-05-20 23:23:51 +00001933 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001934 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001935 E = ClassDecl->field_end(); Field != E; ++Field) {
1936 if ((*Field)->getType()->isIncompleteArrayType()) {
1937 assert(ClassDecl->hasFlexibleArrayMember() &&
1938 "Incomplete array type is not valid");
1939 continue;
1940 }
John McCallbc83b3f2010-05-20 23:23:51 +00001941 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001942 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001943 }
Mike Stump11289f42009-09-09 15:08:12 +00001944
John McCallbc83b3f2010-05-20 23:23:51 +00001945 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001946 if (NumInitializers > 0) {
1947 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1948 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1949 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001950 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001951 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001952 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001953
John McCalla6309952010-03-16 21:39:52 +00001954 // Constructors implicitly reference the base and member
1955 // destructors.
1956 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1957 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001958 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001959
1960 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001961}
1962
Eli Friedman952c15d2009-07-21 19:28:10 +00001963static void *GetKeyForTopLevelField(FieldDecl *Field) {
1964 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001965 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001966 if (RT->getDecl()->isAnonymousStructOrUnion())
1967 return static_cast<void *>(RT->getDecl());
1968 }
1969 return static_cast<void *>(Field);
1970}
1971
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001972static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1973 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001974}
1975
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001976static void *GetKeyForMember(ASTContext &Context,
1977 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001978 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001979 if (!Member->isMemberInitializer())
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.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001984 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001985
Anders Carlssona942dcd2010-03-30 15:39:27 +00001986 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1987 // data member of the class. Data member used in the initializer list is
1988 // in AnonUnionMember field.
1989 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1990 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001991
John McCall23eebd92010-04-10 09:28:51 +00001992 // If the field is a member of an anonymous struct or union, our key
1993 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001994 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001995 if (RD->isAnonymousStructOrUnion()) {
1996 while (true) {
1997 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1998 if (Parent->isAnonymousStructOrUnion())
1999 RD = Parent;
2000 else
2001 break;
2002 }
2003
Anders Carlsson83ac3122010-03-30 16:19:37 +00002004 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Anders Carlssona942dcd2010-03-30 15:39:27 +00002007 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002008}
2009
Anders Carlssone857b292010-04-02 03:37:03 +00002010static void
2011DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002012 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00002013 CXXBaseOrMemberInitializer **Inits,
2014 unsigned NumInits) {
2015 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002016 return;
Mike Stump11289f42009-09-09 15:08:12 +00002017
John McCallbb7b6582010-04-10 07:37:23 +00002018 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2019 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002020 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002021
John McCallbb7b6582010-04-10 07:37:23 +00002022 // Build the list of bases and members in the order that they'll
2023 // actually be initialized. The explicit initializers should be in
2024 // this same order but may be missing things.
2025 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002026
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002027 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2028
John McCallbb7b6582010-04-10 07:37:23 +00002029 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002030 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002031 ClassDecl->vbases_begin(),
2032 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002033 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCallbb7b6582010-04-10 07:37:23 +00002035 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002036 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002037 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002038 if (Base->isVirtual())
2039 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002040 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
John McCallbb7b6582010-04-10 07:37:23 +00002043 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002044 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2045 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002046 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCallbb7b6582010-04-10 07:37:23 +00002048 unsigned NumIdealInits = IdealInitKeys.size();
2049 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002050
John McCallbb7b6582010-04-10 07:37:23 +00002051 CXXBaseOrMemberInitializer *PrevInit = 0;
2052 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2053 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2054 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2055
2056 // Scan forward to try to find this initializer in the idealized
2057 // initializers list.
2058 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2059 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002060 break;
John McCallbb7b6582010-04-10 07:37:23 +00002061
2062 // If we didn't find this initializer, it must be because we
2063 // scanned past it on a previous iteration. That can only
2064 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002065 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002066 Sema::SemaDiagnosticBuilder D =
2067 SemaRef.Diag(PrevInit->getSourceLocation(),
2068 diag::warn_initializer_out_of_order);
2069
2070 if (PrevInit->isMemberInitializer())
2071 D << 0 << PrevInit->getMember()->getDeclName();
2072 else
2073 D << 1 << PrevInit->getBaseClassInfo()->getType();
2074
2075 if (Init->isMemberInitializer())
2076 D << 0 << Init->getMember()->getDeclName();
2077 else
2078 D << 1 << Init->getBaseClassInfo()->getType();
2079
2080 // Move back to the initializer's location in the ideal list.
2081 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2082 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002083 break;
John McCallbb7b6582010-04-10 07:37:23 +00002084
2085 assert(IdealIndex != NumIdealInits &&
2086 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002087 }
John McCallbb7b6582010-04-10 07:37:23 +00002088
2089 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002090 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002091}
2092
John McCall23eebd92010-04-10 09:28:51 +00002093namespace {
2094bool CheckRedundantInit(Sema &S,
2095 CXXBaseOrMemberInitializer *Init,
2096 CXXBaseOrMemberInitializer *&PrevInit) {
2097 if (!PrevInit) {
2098 PrevInit = Init;
2099 return false;
2100 }
2101
2102 if (FieldDecl *Field = Init->getMember())
2103 S.Diag(Init->getSourceLocation(),
2104 diag::err_multiple_mem_initialization)
2105 << Field->getDeclName()
2106 << Init->getSourceRange();
2107 else {
2108 Type *BaseClass = Init->getBaseClass();
2109 assert(BaseClass && "neither field nor base");
2110 S.Diag(Init->getSourceLocation(),
2111 diag::err_multiple_base_initialization)
2112 << QualType(BaseClass, 0)
2113 << Init->getSourceRange();
2114 }
2115 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2116 << 0 << PrevInit->getSourceRange();
2117
2118 return true;
2119}
2120
2121typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2122typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2123
2124bool CheckRedundantUnionInit(Sema &S,
2125 CXXBaseOrMemberInitializer *Init,
2126 RedundantUnionMap &Unions) {
2127 FieldDecl *Field = Init->getMember();
2128 RecordDecl *Parent = Field->getParent();
2129 if (!Parent->isAnonymousStructOrUnion())
2130 return false;
2131
2132 NamedDecl *Child = Field;
2133 do {
2134 if (Parent->isUnion()) {
2135 UnionEntry &En = Unions[Parent];
2136 if (En.first && En.first != Child) {
2137 S.Diag(Init->getSourceLocation(),
2138 diag::err_multiple_mem_union_initialization)
2139 << Field->getDeclName()
2140 << Init->getSourceRange();
2141 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2142 << 0 << En.second->getSourceRange();
2143 return true;
2144 } else if (!En.first) {
2145 En.first = Child;
2146 En.second = Init;
2147 }
2148 }
2149
2150 Child = Parent;
2151 Parent = cast<RecordDecl>(Parent->getDeclContext());
2152 } while (Parent->isAnonymousStructOrUnion());
2153
2154 return false;
2155}
2156}
2157
Anders Carlssone857b292010-04-02 03:37:03 +00002158/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002159void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002160 SourceLocation ColonLoc,
2161 MemInitTy **meminits, unsigned NumMemInits,
2162 bool AnyErrors) {
2163 if (!ConstructorDecl)
2164 return;
2165
2166 AdjustDeclIfTemplate(ConstructorDecl);
2167
2168 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002169 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002170
2171 if (!Constructor) {
2172 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2173 return;
2174 }
2175
2176 CXXBaseOrMemberInitializer **MemInits =
2177 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002178
2179 // Mapping for the duplicate initializers check.
2180 // For member initializers, this is keyed with a FieldDecl*.
2181 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002182 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002183
2184 // Mapping for the inconsistent anonymous-union initializers check.
2185 RedundantUnionMap MemberUnions;
2186
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002187 bool HadError = false;
2188 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002189 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002190
Abramo Bagnara341d7832010-05-26 18:09:23 +00002191 // Set the source order index.
2192 Init->setSourceOrder(i);
2193
John McCall23eebd92010-04-10 09:28:51 +00002194 if (Init->isMemberInitializer()) {
2195 FieldDecl *Field = Init->getMember();
2196 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2197 CheckRedundantUnionInit(*this, Init, MemberUnions))
2198 HadError = true;
2199 } else {
2200 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2201 if (CheckRedundantInit(*this, Init, Members[Key]))
2202 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002203 }
Anders Carlssone857b292010-04-02 03:37:03 +00002204 }
2205
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002206 if (HadError)
2207 return;
2208
Anders Carlssone857b292010-04-02 03:37:03 +00002209 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002210
2211 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002212}
2213
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002214void
John McCalla6309952010-03-16 21:39:52 +00002215Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2216 CXXRecordDecl *ClassDecl) {
2217 // Ignore dependent contexts.
2218 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002219 return;
John McCall1064d7e2010-03-16 05:22:47 +00002220
2221 // FIXME: all the access-control diagnostics are positioned on the
2222 // field/base declaration. That's probably good; that said, the
2223 // user might reasonably want to know why the destructor is being
2224 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002225
Anders Carlssondee9a302009-11-17 04:44:12 +00002226 // Non-static data members.
2227 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2228 E = ClassDecl->field_end(); I != E; ++I) {
2229 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002230 if (Field->isInvalidDecl())
2231 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002232 QualType FieldType = Context.getBaseElementType(Field->getType());
2233
2234 const RecordType* RT = FieldType->getAs<RecordType>();
2235 if (!RT)
2236 continue;
2237
2238 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2239 if (FieldClassDecl->hasTrivialDestructor())
2240 continue;
2241
Douglas Gregore71edda2010-07-01 22:47:18 +00002242 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002243 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002244 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002245 << Field->getDeclName()
2246 << FieldType);
2247
John McCalla6309952010-03-16 21:39:52 +00002248 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002249 }
2250
John McCall1064d7e2010-03-16 05:22:47 +00002251 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2252
Anders Carlssondee9a302009-11-17 04:44:12 +00002253 // Bases.
2254 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2255 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002256 // Bases are always records in a well-formed non-dependent class.
2257 const RecordType *RT = Base->getType()->getAs<RecordType>();
2258
2259 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002260 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002261 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002262
2263 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002264 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002265 if (BaseClassDecl->hasTrivialDestructor())
2266 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002267
Douglas Gregore71edda2010-07-01 22:47:18 +00002268 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002269
2270 // FIXME: caret should be on the start of the class name
2271 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002272 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002273 << Base->getType()
2274 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002275
John McCalla6309952010-03-16 21:39:52 +00002276 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002277 }
2278
2279 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002280 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2281 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002282
2283 // Bases are always records in a well-formed non-dependent class.
2284 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2285
2286 // Ignore direct virtual bases.
2287 if (DirectVirtualBases.count(RT))
2288 continue;
2289
Anders Carlssondee9a302009-11-17 04:44:12 +00002290 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002291 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002292 if (BaseClassDecl->hasTrivialDestructor())
2293 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002294
Douglas Gregore71edda2010-07-01 22:47:18 +00002295 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002296 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002297 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002298 << VBase->getType());
2299
John McCalla6309952010-03-16 21:39:52 +00002300 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002301 }
2302}
2303
John McCall48871652010-08-21 09:40:31 +00002304void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002305 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002306 return;
Mike Stump11289f42009-09-09 15:08:12 +00002307
Mike Stump11289f42009-09-09 15:08:12 +00002308 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002309 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002310 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002311}
2312
Mike Stump11289f42009-09-09 15:08:12 +00002313bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002314 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002315 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002316 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002317 else
John McCall02db245d2010-08-18 09:41:07 +00002318 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002319}
2320
Anders Carlssoneabf7702009-08-27 00:13:57 +00002321bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002322 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002323 if (!getLangOptions().CPlusPlus)
2324 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002325
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002326 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002327 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002328
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002329 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002330 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002331 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002332 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002333
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002334 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002335 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002336 }
Mike Stump11289f42009-09-09 15:08:12 +00002337
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002338 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002339 if (!RT)
2340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002341
John McCall67da35c2010-02-04 22:26:26 +00002342 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002343
John McCall02db245d2010-08-18 09:41:07 +00002344 // We can't answer whether something is abstract until it has a
2345 // definition. If it's currently being defined, we'll walk back
2346 // over all the declarations when we have a full definition.
2347 const CXXRecordDecl *Def = RD->getDefinition();
2348 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002349 return false;
2350
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002351 if (!RD->isAbstract())
2352 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002353
Anders Carlssoneabf7702009-08-27 00:13:57 +00002354 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002355 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002356
John McCall02db245d2010-08-18 09:41:07 +00002357 return true;
2358}
2359
2360void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2361 // Check if we've already emitted the list of pure virtual functions
2362 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002363 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002364 return;
Mike Stump11289f42009-09-09 15:08:12 +00002365
Douglas Gregor4165bd62010-03-23 23:47:56 +00002366 CXXFinalOverriderMap FinalOverriders;
2367 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002368
Anders Carlssona2f74f32010-06-03 01:00:02 +00002369 // Keep a set of seen pure methods so we won't diagnose the same method
2370 // more than once.
2371 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2372
Douglas Gregor4165bd62010-03-23 23:47:56 +00002373 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2374 MEnd = FinalOverriders.end();
2375 M != MEnd;
2376 ++M) {
2377 for (OverridingMethods::iterator SO = M->second.begin(),
2378 SOEnd = M->second.end();
2379 SO != SOEnd; ++SO) {
2380 // C++ [class.abstract]p4:
2381 // A class is abstract if it contains or inherits at least one
2382 // pure virtual function for which the final overrider is pure
2383 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002384
Douglas Gregor4165bd62010-03-23 23:47:56 +00002385 //
2386 if (SO->second.size() != 1)
2387 continue;
2388
2389 if (!SO->second.front().Method->isPure())
2390 continue;
2391
Anders Carlssona2f74f32010-06-03 01:00:02 +00002392 if (!SeenPureMethods.insert(SO->second.front().Method))
2393 continue;
2394
Douglas Gregor4165bd62010-03-23 23:47:56 +00002395 Diag(SO->second.front().Method->getLocation(),
2396 diag::note_pure_virtual_function)
2397 << SO->second.front().Method->getDeclName();
2398 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002399 }
2400
2401 if (!PureVirtualClassDiagSet)
2402 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2403 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002404}
2405
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002406namespace {
John McCall02db245d2010-08-18 09:41:07 +00002407struct AbstractUsageInfo {
2408 Sema &S;
2409 CXXRecordDecl *Record;
2410 CanQualType AbstractType;
2411 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002412
John McCall02db245d2010-08-18 09:41:07 +00002413 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2414 : S(S), Record(Record),
2415 AbstractType(S.Context.getCanonicalType(
2416 S.Context.getTypeDeclType(Record))),
2417 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002418
John McCall02db245d2010-08-18 09:41:07 +00002419 void DiagnoseAbstractType() {
2420 if (Invalid) return;
2421 S.DiagnoseAbstractType(Record);
2422 Invalid = true;
2423 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002424
John McCall02db245d2010-08-18 09:41:07 +00002425 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2426};
2427
2428struct CheckAbstractUsage {
2429 AbstractUsageInfo &Info;
2430 const NamedDecl *Ctx;
2431
2432 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2433 : Info(Info), Ctx(Ctx) {}
2434
2435 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2436 switch (TL.getTypeLocClass()) {
2437#define ABSTRACT_TYPELOC(CLASS, PARENT)
2438#define TYPELOC(CLASS, PARENT) \
2439 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2440#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002441 }
John McCall02db245d2010-08-18 09:41:07 +00002442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
John McCall02db245d2010-08-18 09:41:07 +00002444 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2445 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2446 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2447 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2448 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002449 }
John McCall02db245d2010-08-18 09:41:07 +00002450 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002451
John McCall02db245d2010-08-18 09:41:07 +00002452 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2453 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455
John McCall02db245d2010-08-18 09:41:07 +00002456 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2457 // Visit the type parameters from a permissive context.
2458 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2459 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2460 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2461 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2462 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2463 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002464 }
John McCall02db245d2010-08-18 09:41:07 +00002465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
John McCall02db245d2010-08-18 09:41:07 +00002467 // Visit pointee types from a permissive context.
2468#define CheckPolymorphic(Type) \
2469 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2470 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2471 }
2472 CheckPolymorphic(PointerTypeLoc)
2473 CheckPolymorphic(ReferenceTypeLoc)
2474 CheckPolymorphic(MemberPointerTypeLoc)
2475 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002476
John McCall02db245d2010-08-18 09:41:07 +00002477 /// Handle all the types we haven't given a more specific
2478 /// implementation for above.
2479 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2480 // Every other kind of type that we haven't called out already
2481 // that has an inner type is either (1) sugar or (2) contains that
2482 // inner type in some way as a subobject.
2483 if (TypeLoc Next = TL.getNextTypeLoc())
2484 return Visit(Next, Sel);
2485
2486 // If there's no inner type and we're in a permissive context,
2487 // don't diagnose.
2488 if (Sel == Sema::AbstractNone) return;
2489
2490 // Check whether the type matches the abstract type.
2491 QualType T = TL.getType();
2492 if (T->isArrayType()) {
2493 Sel = Sema::AbstractArrayType;
2494 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002495 }
John McCall02db245d2010-08-18 09:41:07 +00002496 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2497 if (CT != Info.AbstractType) return;
2498
2499 // It matched; do some magic.
2500 if (Sel == Sema::AbstractArrayType) {
2501 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2502 << T << TL.getSourceRange();
2503 } else {
2504 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2505 << Sel << T << TL.getSourceRange();
2506 }
2507 Info.DiagnoseAbstractType();
2508 }
2509};
2510
2511void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2512 Sema::AbstractDiagSelID Sel) {
2513 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2514}
2515
2516}
2517
2518/// Check for invalid uses of an abstract type in a method declaration.
2519static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2520 CXXMethodDecl *MD) {
2521 // No need to do the check on definitions, which require that
2522 // the return/param types be complete.
2523 if (MD->isThisDeclarationADefinition())
2524 return;
2525
2526 // For safety's sake, just ignore it if we don't have type source
2527 // information. This should never happen for non-implicit methods,
2528 // but...
2529 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2530 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2531}
2532
2533/// Check for invalid uses of an abstract type within a class definition.
2534static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2535 CXXRecordDecl *RD) {
2536 for (CXXRecordDecl::decl_iterator
2537 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2538 Decl *D = *I;
2539 if (D->isImplicit()) continue;
2540
2541 // Methods and method templates.
2542 if (isa<CXXMethodDecl>(D)) {
2543 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2544 } else if (isa<FunctionTemplateDecl>(D)) {
2545 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2546 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2547
2548 // Fields and static variables.
2549 } else if (isa<FieldDecl>(D)) {
2550 FieldDecl *FD = cast<FieldDecl>(D);
2551 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2552 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2553 } else if (isa<VarDecl>(D)) {
2554 VarDecl *VD = cast<VarDecl>(D);
2555 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2556 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2557
2558 // Nested classes and class templates.
2559 } else if (isa<CXXRecordDecl>(D)) {
2560 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2561 } else if (isa<ClassTemplateDecl>(D)) {
2562 CheckAbstractClassUsage(Info,
2563 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2564 }
2565 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002566}
2567
Douglas Gregorc99f1552009-12-03 18:33:45 +00002568/// \brief Perform semantic checks on a class definition that has been
2569/// completing, introducing implicitly-declared members, checking for
2570/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002571void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002572 if (!Record || Record->isInvalidDecl())
2573 return;
2574
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002575 if (!Record->isDependentType())
Douglas Gregor0be31a22010-07-02 17:43:08 +00002576 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002577
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002578 if (Record->isInvalidDecl())
2579 return;
2580
John McCall2cb94162010-01-28 07:38:46 +00002581 // Set access bits correctly on the directly-declared conversions.
2582 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2583 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2584 Convs->setAccess(I, (*I)->getAccess());
2585
Douglas Gregor4165bd62010-03-23 23:47:56 +00002586 // Determine whether we need to check for final overriders. We do
2587 // this either when there are virtual base classes (in which case we
2588 // may end up finding multiple final overriders for a given virtual
2589 // function) or any of the base classes is abstract (in which case
2590 // we might detect that this class is abstract).
2591 bool CheckFinalOverriders = false;
2592 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2593 !Record->isDependentType()) {
2594 if (Record->getNumVBases())
2595 CheckFinalOverriders = true;
2596 else if (!Record->isAbstract()) {
2597 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2598 BEnd = Record->bases_end();
2599 B != BEnd; ++B) {
2600 CXXRecordDecl *BaseDecl
2601 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2602 if (BaseDecl->isAbstract()) {
2603 CheckFinalOverriders = true;
2604 break;
2605 }
2606 }
2607 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002608 }
2609
Douglas Gregor4165bd62010-03-23 23:47:56 +00002610 if (CheckFinalOverriders) {
2611 CXXFinalOverriderMap FinalOverriders;
2612 Record->getFinalOverriders(FinalOverriders);
2613
2614 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2615 MEnd = FinalOverriders.end();
2616 M != MEnd; ++M) {
2617 for (OverridingMethods::iterator SO = M->second.begin(),
2618 SOEnd = M->second.end();
2619 SO != SOEnd; ++SO) {
2620 assert(SO->second.size() > 0 &&
2621 "All virtual functions have overridding virtual functions");
2622 if (SO->second.size() == 1) {
2623 // C++ [class.abstract]p4:
2624 // A class is abstract if it contains or inherits at least one
2625 // pure virtual function for which the final overrider is pure
2626 // virtual.
2627 if (SO->second.front().Method->isPure())
2628 Record->setAbstract(true);
2629 continue;
2630 }
2631
2632 // C++ [class.virtual]p2:
2633 // In a derived class, if a virtual member function of a base
2634 // class subobject has more than one final overrider the
2635 // program is ill-formed.
2636 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2637 << (NamedDecl *)M->first << Record;
2638 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2639 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2640 OMEnd = SO->second.end();
2641 OM != OMEnd; ++OM)
2642 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2643 << (NamedDecl *)M->first << OM->Method->getParent();
2644
2645 Record->setInvalidDecl();
2646 }
2647 }
2648 }
2649
John McCall02db245d2010-08-18 09:41:07 +00002650 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2651 AbstractUsageInfo Info(*this, Record);
2652 CheckAbstractClassUsage(Info, Record);
2653 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002654
2655 // If this is not an aggregate type and has no user-declared constructor,
2656 // complain about any non-static data members of reference or const scalar
2657 // type, since they will never get initializers.
2658 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2659 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2660 bool Complained = false;
2661 for (RecordDecl::field_iterator F = Record->field_begin(),
2662 FEnd = Record->field_end();
2663 F != FEnd; ++F) {
2664 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002665 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002666 if (!Complained) {
2667 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2668 << Record->getTagKind() << Record;
2669 Complained = true;
2670 }
2671
2672 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2673 << F->getType()->isReferenceType()
2674 << F->getDeclName();
2675 }
2676 }
2677 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002678
2679 if (Record->isDynamicClass())
2680 DynamicClasses.push_back(Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002681}
2682
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002683void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002684 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002685 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002686 SourceLocation RBrac,
2687 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002688 if (!TagDecl)
2689 return;
Mike Stump11289f42009-09-09 15:08:12 +00002690
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002691 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002692
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002693 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002694 // strict aliasing violation!
2695 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002696 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002697
Douglas Gregor0be31a22010-07-02 17:43:08 +00002698 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002699 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002700}
2701
Douglas Gregor95755162010-07-01 05:10:53 +00002702namespace {
2703 /// \brief Helper class that collects exception specifications for
2704 /// implicitly-declared special member functions.
2705 class ImplicitExceptionSpecification {
2706 ASTContext &Context;
2707 bool AllowsAllExceptions;
2708 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2709 llvm::SmallVector<QualType, 4> Exceptions;
2710
2711 public:
2712 explicit ImplicitExceptionSpecification(ASTContext &Context)
2713 : Context(Context), AllowsAllExceptions(false) { }
2714
2715 /// \brief Whether the special member function should have any
2716 /// exception specification at all.
2717 bool hasExceptionSpecification() const {
2718 return !AllowsAllExceptions;
2719 }
2720
2721 /// \brief Whether the special member function should have a
2722 /// throw(...) exception specification (a Microsoft extension).
2723 bool hasAnyExceptionSpecification() const {
2724 return false;
2725 }
2726
2727 /// \brief The number of exceptions in the exception specification.
2728 unsigned size() const { return Exceptions.size(); }
2729
2730 /// \brief The set of exceptions in the exception specification.
2731 const QualType *data() const { return Exceptions.data(); }
2732
2733 /// \brief Note that
2734 void CalledDecl(CXXMethodDecl *Method) {
2735 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002736 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002737 return;
2738
2739 const FunctionProtoType *Proto
2740 = Method->getType()->getAs<FunctionProtoType>();
2741
2742 // If this function can throw any exceptions, make a note of that.
2743 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2744 AllowsAllExceptions = true;
2745 ExceptionsSeen.clear();
2746 Exceptions.clear();
2747 return;
2748 }
2749
2750 // Record the exceptions in this function's exception specification.
2751 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2752 EEnd = Proto->exception_end();
2753 E != EEnd; ++E)
2754 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2755 Exceptions.push_back(*E);
2756 }
2757 };
2758}
2759
2760
Douglas Gregor05379422008-11-03 17:51:48 +00002761/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2762/// special functions, such as the default constructor, copy
2763/// constructor, or destructor, to the given C++ class (C++
2764/// [special]p1). This routine can only be executed just before the
2765/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002766void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002767 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002768 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002769
Douglas Gregor54be3392010-07-01 17:57:27 +00002770 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002771 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002772
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002773 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2774 ++ASTContext::NumImplicitCopyAssignmentOperators;
2775
2776 // If we have a dynamic class, then the copy assignment operator may be
2777 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2778 // it shows up in the right place in the vtable and that we diagnose
2779 // problems with the implicit exception specification.
2780 if (ClassDecl->isDynamicClass())
2781 DeclareImplicitCopyAssignment(ClassDecl);
2782 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002783
Douglas Gregor7454c562010-07-02 20:37:36 +00002784 if (!ClassDecl->hasUserDeclaredDestructor()) {
2785 ++ASTContext::NumImplicitDestructors;
2786
2787 // If we have a dynamic class, then the destructor may be virtual, so we
2788 // have to declare the destructor immediately. This ensures that, e.g., it
2789 // shows up in the right place in the vtable and that we diagnose problems
2790 // with the implicit exception specification.
2791 if (ClassDecl->isDynamicClass())
2792 DeclareImplicitDestructor(ClassDecl);
2793 }
Douglas Gregor05379422008-11-03 17:51:48 +00002794}
2795
John McCall48871652010-08-21 09:40:31 +00002796void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002797 if (!D)
2798 return;
2799
2800 TemplateParameterList *Params = 0;
2801 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2802 Params = Template->getTemplateParameters();
2803 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2804 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2805 Params = PartialSpec->getTemplateParameters();
2806 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002807 return;
2808
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002809 for (TemplateParameterList::iterator Param = Params->begin(),
2810 ParamEnd = Params->end();
2811 Param != ParamEnd; ++Param) {
2812 NamedDecl *Named = cast<NamedDecl>(*Param);
2813 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002814 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002815 IdResolver.AddDecl(Named);
2816 }
2817 }
2818}
2819
John McCall48871652010-08-21 09:40:31 +00002820void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002821 if (!RecordD) return;
2822 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002823 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002824 PushDeclContext(S, Record);
2825}
2826
John McCall48871652010-08-21 09:40:31 +00002827void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002828 if (!RecordD) return;
2829 PopDeclContext();
2830}
2831
Douglas Gregor4d87df52008-12-16 21:30:33 +00002832/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2833/// parsing a top-level (non-nested) C++ class, and we are now
2834/// parsing those parts of the given Method declaration that could
2835/// not be parsed earlier (C++ [class.mem]p2), such as default
2836/// arguments. This action should enter the scope of the given
2837/// Method declaration as if we had just parsed the qualified method
2838/// name. However, it should not bring the parameters into scope;
2839/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002840void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002841}
2842
2843/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2844/// C++ method declaration. We're (re-)introducing the given
2845/// function parameter into scope for use in parsing later parts of
2846/// the method declaration. For example, we could see an
2847/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002848void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002849 if (!ParamD)
2850 return;
Mike Stump11289f42009-09-09 15:08:12 +00002851
John McCall48871652010-08-21 09:40:31 +00002852 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002853
2854 // If this parameter has an unparsed default argument, clear it out
2855 // to make way for the parsed default argument.
2856 if (Param->hasUnparsedDefaultArg())
2857 Param->setDefaultArg(0);
2858
John McCall48871652010-08-21 09:40:31 +00002859 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002860 if (Param->getDeclName())
2861 IdResolver.AddDecl(Param);
2862}
2863
2864/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2865/// processing the delayed method declaration for Method. The method
2866/// declaration is now considered finished. There may be a separate
2867/// ActOnStartOfFunctionDef action later (not necessarily
2868/// immediately!) for this method, if it was also defined inside the
2869/// class body.
John McCall48871652010-08-21 09:40:31 +00002870void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002871 if (!MethodD)
2872 return;
Mike Stump11289f42009-09-09 15:08:12 +00002873
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002874 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002875
John McCall48871652010-08-21 09:40:31 +00002876 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002877
2878 // Now that we have our default arguments, check the constructor
2879 // again. It could produce additional diagnostics or affect whether
2880 // the class has implicitly-declared destructors, among other
2881 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002882 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2883 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002884
2885 // Check the default arguments, which we may have added.
2886 if (!Method->isInvalidDecl())
2887 CheckCXXDefaultArguments(Method);
2888}
2889
Douglas Gregor831c93f2008-11-05 20:51:48 +00002890/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002891/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002892/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002893/// emit diagnostics and set the invalid bit to true. In any case, the type
2894/// will be updated to reflect a well-formed type for the constructor and
2895/// returned.
2896QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2897 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002898 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002899
2900 // C++ [class.ctor]p3:
2901 // A constructor shall not be virtual (10.3) or static (9.4). A
2902 // constructor can be invoked for a const, volatile or const
2903 // volatile object. A constructor shall not be declared const,
2904 // volatile, or const volatile (9.3.2).
2905 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002906 if (!D.isInvalidType())
2907 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2908 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2909 << SourceRange(D.getIdentifierLoc());
2910 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002911 }
2912 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002913 if (!D.isInvalidType())
2914 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2915 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2916 << SourceRange(D.getIdentifierLoc());
2917 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002918 SC = FunctionDecl::None;
2919 }
Mike Stump11289f42009-09-09 15:08:12 +00002920
Chris Lattner38378bf2009-04-25 08:28:21 +00002921 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2922 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002923 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002924 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2925 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002926 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002927 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2928 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002929 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002930 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2931 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002932 }
Mike Stump11289f42009-09-09 15:08:12 +00002933
Douglas Gregor831c93f2008-11-05 20:51:48 +00002934 // Rebuild the function type "R" without any type qualifiers (in
2935 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002936 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002937 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002938 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2939 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002940 Proto->isVariadic(), 0,
2941 Proto->hasExceptionSpec(),
2942 Proto->hasAnyExceptionSpec(),
2943 Proto->getNumExceptions(),
2944 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002945 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002946}
2947
Douglas Gregor4d87df52008-12-16 21:30:33 +00002948/// CheckConstructor - Checks a fully-formed constructor for
2949/// well-formedness, issuing any diagnostics required. Returns true if
2950/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002951void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002952 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002953 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2954 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002955 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002956
2957 // C++ [class.copy]p3:
2958 // A declaration of a constructor for a class X is ill-formed if
2959 // its first parameter is of type (optionally cv-qualified) X and
2960 // either there are no other parameters or else all other
2961 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002962 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002963 ((Constructor->getNumParams() == 1) ||
2964 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002965 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2966 Constructor->getTemplateSpecializationKind()
2967 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002968 QualType ParamType = Constructor->getParamDecl(0)->getType();
2969 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2970 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002971 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002972 const char *ConstRef
2973 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2974 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002975 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002976 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002977
2978 // FIXME: Rather that making the constructor invalid, we should endeavor
2979 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002980 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002981 }
2982 }
Mike Stump11289f42009-09-09 15:08:12 +00002983
John McCall43314ab2010-04-13 07:45:41 +00002984 // Notify the class that we've added a constructor. In principle we
2985 // don't need to do this for out-of-line declarations; in practice
2986 // we only instantiate the most recent declaration of a method, so
2987 // we have to call this for everything but friends.
2988 if (!Constructor->getFriendObjectKind())
2989 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002990}
2991
John McCalldeb646e2010-08-04 01:04:25 +00002992/// CheckDestructor - Checks a fully-formed destructor definition for
2993/// well-formedness, issuing any diagnostics required. Returns true
2994/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002995bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002996 CXXRecordDecl *RD = Destructor->getParent();
2997
2998 if (Destructor->isVirtual()) {
2999 SourceLocation Loc;
3000
3001 if (!Destructor->isImplicit())
3002 Loc = Destructor->getLocation();
3003 else
3004 Loc = RD->getLocation();
3005
3006 // If we have a virtual destructor, look up the deallocation function
3007 FunctionDecl *OperatorDelete = 0;
3008 DeclarationName Name =
3009 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003010 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003011 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003012
3013 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003014
3015 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003016 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003017
3018 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003019}
3020
Mike Stump11289f42009-09-09 15:08:12 +00003021static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003022FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3023 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3024 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003025 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003026}
3027
Douglas Gregor831c93f2008-11-05 20:51:48 +00003028/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3029/// the well-formednes of the destructor declarator @p D with type @p
3030/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003031/// emit diagnostics and set the declarator to invalid. Even if this happens,
3032/// will be updated to reflect a well-formed type for the destructor and
3033/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003034QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
Chris Lattner38378bf2009-04-25 08:28:21 +00003035 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003036 // C++ [class.dtor]p1:
3037 // [...] A typedef-name that names a class is a class-name
3038 // (7.1.3); however, a typedef-name that names a class shall not
3039 // be used as the identifier in the declarator for a destructor
3040 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003041 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003042 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003043 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003044 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003045
3046 // C++ [class.dtor]p2:
3047 // A destructor is used to destroy objects of its class type. A
3048 // destructor takes no parameters, and no return type can be
3049 // specified for it (not even void). The address of a destructor
3050 // shall not be taken. A destructor shall not be static. A
3051 // destructor can be invoked for a const, volatile or const
3052 // volatile object. A destructor shall not be declared const,
3053 // volatile or const volatile (9.3.2).
3054 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003055 if (!D.isInvalidType())
3056 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3057 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003058 << SourceRange(D.getIdentifierLoc())
3059 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3060
Douglas Gregor831c93f2008-11-05 20:51:48 +00003061 SC = FunctionDecl::None;
3062 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003063 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003064 // Destructors don't have return types, but the parser will
3065 // happily parse something like:
3066 //
3067 // class X {
3068 // float ~X();
3069 // };
3070 //
3071 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003072 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3073 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3074 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003075 }
Mike Stump11289f42009-09-09 15:08:12 +00003076
Chris Lattner38378bf2009-04-25 08:28:21 +00003077 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3078 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003079 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003080 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3081 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003082 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3084 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003085 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3087 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003088 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003089 }
3090
3091 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003092 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003093 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3094
3095 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003096 FTI.freeArgs();
3097 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003098 }
3099
Mike Stump11289f42009-09-09 15:08:12 +00003100 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003101 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003102 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003103 D.setInvalidType();
3104 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003105
3106 // Rebuild the function type "R" without any type qualifiers or
3107 // parameters (in case any of the errors above fired) and with
3108 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003109 // types.
3110 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3111 if (!Proto)
3112 return QualType();
3113
Douglas Gregor36c569f2010-02-21 22:15:06 +00003114 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00003115 Proto->hasExceptionSpec(),
3116 Proto->hasAnyExceptionSpec(),
3117 Proto->getNumExceptions(),
3118 Proto->exception_begin(),
3119 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003120}
3121
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003122/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3123/// well-formednes of the conversion function declarator @p D with
3124/// type @p R. If there are any errors in the declarator, this routine
3125/// will emit diagnostics and return true. Otherwise, it will return
3126/// false. Either way, the type @p R will be updated to reflect a
3127/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003128void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003129 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003130 // C++ [class.conv.fct]p1:
3131 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003132 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003133 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003134 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003135 if (!D.isInvalidType())
3136 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3137 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3138 << SourceRange(D.getIdentifierLoc());
3139 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003140 SC = FunctionDecl::None;
3141 }
John McCall212fa2e2010-04-13 00:04:31 +00003142
3143 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3144
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003145 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003146 // Conversion functions don't have return types, but the parser will
3147 // happily parse something like:
3148 //
3149 // class X {
3150 // float operator bool();
3151 // };
3152 //
3153 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003154 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3155 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3156 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003157 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003158 }
3159
John McCall212fa2e2010-04-13 00:04:31 +00003160 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3161
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003162 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003163 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003164 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3165
3166 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003167 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003168 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003169 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003170 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003171 D.setInvalidType();
3172 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173
John McCall212fa2e2010-04-13 00:04:31 +00003174 // Diagnose "&operator bool()" and other such nonsense. This
3175 // is actually a gcc extension which we don't support.
3176 if (Proto->getResultType() != ConvType) {
3177 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3178 << Proto->getResultType();
3179 D.setInvalidType();
3180 ConvType = Proto->getResultType();
3181 }
3182
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003183 // C++ [class.conv.fct]p4:
3184 // The conversion-type-id shall not represent a function type nor
3185 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003186 if (ConvType->isArrayType()) {
3187 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3188 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003189 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003190 } else if (ConvType->isFunctionType()) {
3191 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3192 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003193 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003194 }
3195
3196 // Rebuild the function type "R" without any parameters (in case any
3197 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003198 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003199 if (D.isInvalidType()) {
3200 R = Context.getFunctionType(ConvType, 0, 0, false,
3201 Proto->getTypeQuals(),
3202 Proto->hasExceptionSpec(),
3203 Proto->hasAnyExceptionSpec(),
3204 Proto->getNumExceptions(),
3205 Proto->exception_begin(),
3206 Proto->getExtInfo());
3207 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003208
Douglas Gregor5fb53972009-01-14 15:45:31 +00003209 // C++0x explicit conversion operators.
3210 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003211 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003212 diag::warn_explicit_conversion_functions)
3213 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003214}
3215
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003216/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3217/// the declaration of the given C++ conversion function. This routine
3218/// is responsible for recording the conversion function in the C++
3219/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003220Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003221 assert(Conversion && "Expected to receive a conversion function declaration");
3222
Douglas Gregor4287b372008-12-12 08:25:50 +00003223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003224
3225 // Make sure we aren't redeclaring the conversion function.
3226 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003227
3228 // C++ [class.conv.fct]p1:
3229 // [...] A conversion function is never used to convert a
3230 // (possibly cv-qualified) object to the (possibly cv-qualified)
3231 // same object type (or a reference to it), to a (possibly
3232 // cv-qualified) base class of that type (or a reference to it),
3233 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003234 // FIXME: Suppress this warning if the conversion function ends up being a
3235 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003236 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003237 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003238 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003239 ConvType = ConvTypeRef->getPointeeType();
3240 if (ConvType->isRecordType()) {
3241 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3242 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003243 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003244 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003245 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003246 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003247 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003248 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003249 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003250 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003251 }
3252
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003253 if (Conversion->getPrimaryTemplate()) {
3254 // ignore specializations
3255 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003256 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003257 = Conversion->getDescribedFunctionTemplate()) {
3258 if (ClassDecl->replaceConversion(
3259 ConversionTemplate->getPreviousDeclaration(),
3260 ConversionTemplate))
John McCall48871652010-08-21 09:40:31 +00003261 return ConversionTemplate;
Douglas Gregor133bc742010-01-11 18:53:25 +00003262 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3263 Conversion))
John McCall48871652010-08-21 09:40:31 +00003264 return Conversion;
Douglas Gregor1dc98262008-12-26 15:00:45 +00003265 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003266 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003267 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003268 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003269 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003270 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003271
John McCall48871652010-08-21 09:40:31 +00003272 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003273}
3274
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003275//===----------------------------------------------------------------------===//
3276// Namespace Handling
3277//===----------------------------------------------------------------------===//
3278
3279/// ActOnStartNamespaceDef - This is called at the start of a namespace
3280/// definition.
John McCall48871652010-08-21 09:40:31 +00003281Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Chris Lattner83f095c2009-03-28 19:18:32 +00003282 SourceLocation IdentLoc,
3283 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003284 SourceLocation LBrace,
3285 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003286 // anonymous namespace starts at its left brace
3287 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3288 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003289 Namespc->setLBracLoc(LBrace);
3290
3291 Scope *DeclRegionScope = NamespcScope->getParent();
3292
Anders Carlssona7bcade2010-02-07 01:09:23 +00003293 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3294
Eli Friedman570024a2010-08-05 06:57:20 +00003295 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003296 PushPragmaVisibility(attr->getVisibility(), attr->getLocation());
Eli Friedman570024a2010-08-05 06:57:20 +00003297
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003298 if (II) {
3299 // C++ [namespace.def]p2:
3300 // The identifier in an original-namespace-definition shall not have been
3301 // previously defined in the declarative region in which the
3302 // original-namespace-definition appears. The identifier in an
3303 // original-namespace-definition is the name of the namespace. Subsequently
3304 // in that declarative region, it is treated as an original-namespace-name.
3305
John McCall9f3059a2009-10-09 21:13:30 +00003306 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003307 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003308 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003309
Douglas Gregor91f84212008-12-11 16:49:14 +00003310 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3311 // This is an extended namespace definition.
3312 // Attach this namespace decl to the chain of extended namespace
3313 // definitions.
3314 OrigNS->setNextNamespace(Namespc);
3315 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003316
Mike Stump11289f42009-09-09 15:08:12 +00003317 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003318 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003319 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003320 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003321 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003322 } else if (PrevDecl) {
3323 // This is an invalid name redefinition.
3324 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3325 << Namespc->getDeclName();
3326 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3327 Namespc->setInvalidDecl();
3328 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003329 } else if (II->isStr("std") &&
3330 CurContext->getLookupContext()->isTranslationUnit()) {
3331 // This is the first "real" definition of the namespace "std", so update
3332 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003333 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003334 // We had already defined a dummy namespace "std". Link this new
3335 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003336 StdNS->setNextNamespace(Namespc);
3337 StdNS->setLocation(IdentLoc);
3338 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003339 }
3340
3341 // Make our StdNamespace cache point at the first real definition of the
3342 // "std" namespace.
3343 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003344 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003345
3346 PushOnScopeChains(Namespc, DeclRegionScope);
3347 } else {
John McCall4fa53422009-10-01 00:25:31 +00003348 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003349 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003350
3351 // Link the anonymous namespace into its parent.
3352 NamespaceDecl *PrevDecl;
3353 DeclContext *Parent = CurContext->getLookupContext();
3354 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3355 PrevDecl = TU->getAnonymousNamespace();
3356 TU->setAnonymousNamespace(Namespc);
3357 } else {
3358 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3359 PrevDecl = ND->getAnonymousNamespace();
3360 ND->setAnonymousNamespace(Namespc);
3361 }
3362
3363 // Link the anonymous namespace with its previous declaration.
3364 if (PrevDecl) {
3365 assert(PrevDecl->isAnonymousNamespace());
3366 assert(!PrevDecl->getNextNamespace());
3367 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3368 PrevDecl->setNextNamespace(Namespc);
3369 }
John McCall4fa53422009-10-01 00:25:31 +00003370
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003371 CurContext->addDecl(Namespc);
3372
John McCall4fa53422009-10-01 00:25:31 +00003373 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3374 // behaves as if it were replaced by
3375 // namespace unique { /* empty body */ }
3376 // using namespace unique;
3377 // namespace unique { namespace-body }
3378 // where all occurrences of 'unique' in a translation unit are
3379 // replaced by the same identifier and this identifier differs
3380 // from all other identifiers in the entire program.
3381
3382 // We just create the namespace with an empty name and then add an
3383 // implicit using declaration, just like the standard suggests.
3384 //
3385 // CodeGen enforces the "universally unique" aspect by giving all
3386 // declarations semantically contained within an anonymous
3387 // namespace internal linkage.
3388
John McCall0db42252009-12-16 02:06:49 +00003389 if (!PrevDecl) {
3390 UsingDirectiveDecl* UD
3391 = UsingDirectiveDecl::Create(Context, CurContext,
3392 /* 'using' */ LBrace,
3393 /* 'namespace' */ SourceLocation(),
3394 /* qualifier */ SourceRange(),
3395 /* NNS */ NULL,
3396 /* identifier */ SourceLocation(),
3397 Namespc,
3398 /* Ancestor */ CurContext);
3399 UD->setImplicit();
3400 CurContext->addDecl(UD);
3401 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003402 }
3403
3404 // Although we could have an invalid decl (i.e. the namespace name is a
3405 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003406 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3407 // for the namespace has the declarations that showed up in that particular
3408 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003409 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003410 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003411}
3412
Sebastian Redla6602e92009-11-23 15:34:23 +00003413/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3414/// is a namespace alias, returns the namespace it points to.
3415static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3416 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3417 return AD->getNamespace();
3418 return dyn_cast_or_null<NamespaceDecl>(D);
3419}
3420
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003421/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3422/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003423void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003424 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3425 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3426 Namespc->setRBracLoc(RBrace);
3427 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003428 if (Namespc->hasAttr<VisibilityAttr>())
3429 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003430}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003431
Douglas Gregorcdf87022010-06-29 17:53:46 +00003432/// \brief Retrieve the special "std" namespace, which may require us to
3433/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003434NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003435 if (!StdNamespace) {
3436 // The "std" namespace has not yet been defined, so build one implicitly.
3437 StdNamespace = NamespaceDecl::Create(Context,
3438 Context.getTranslationUnitDecl(),
3439 SourceLocation(),
3440 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003441 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003442 }
3443
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003444 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003445}
3446
John McCall48871652010-08-21 09:40:31 +00003447Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003448 SourceLocation UsingLoc,
3449 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003450 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003451 SourceLocation IdentLoc,
3452 IdentifierInfo *NamespcName,
3453 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003454 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3455 assert(NamespcName && "Invalid NamespcName.");
3456 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003457 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003458
Douglas Gregor889ceb72009-02-03 19:21:40 +00003459 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003460 NestedNameSpecifier *Qualifier = 0;
3461 if (SS.isSet())
3462 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3463
Douglas Gregor34074322009-01-14 22:20:51 +00003464 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003465 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3466 LookupParsedName(R, S, &SS);
3467 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003468 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003469
Douglas Gregorcdf87022010-06-29 17:53:46 +00003470 if (R.empty()) {
3471 // Allow "using namespace std;" or "using namespace ::std;" even if
3472 // "std" hasn't been defined yet, for GCC compatibility.
3473 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3474 NamespcName->isStr("std")) {
3475 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003476 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003477 R.resolveKind();
3478 }
3479 // Otherwise, attempt typo correction.
3480 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3481 CTC_NoKeywords, 0)) {
3482 if (R.getAsSingle<NamespaceDecl>() ||
3483 R.getAsSingle<NamespaceAliasDecl>()) {
3484 if (DeclContext *DC = computeDeclContext(SS, false))
3485 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3486 << NamespcName << DC << Corrected << SS.getRange()
3487 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3488 else
3489 Diag(IdentLoc, diag::err_using_directive_suggest)
3490 << NamespcName << Corrected
3491 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3492 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3493 << Corrected;
3494
3495 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003496 } else {
3497 R.clear();
3498 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003499 }
3500 }
3501 }
3502
John McCall9f3059a2009-10-09 21:13:30 +00003503 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003504 NamedDecl *Named = R.getFoundDecl();
3505 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3506 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003507 // C++ [namespace.udir]p1:
3508 // A using-directive specifies that the names in the nominated
3509 // namespace can be used in the scope in which the
3510 // using-directive appears after the using-directive. During
3511 // unqualified name lookup (3.4.1), the names appear as if they
3512 // were declared in the nearest enclosing namespace which
3513 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003514 // namespace. [Note: in this context, "contains" means "contains
3515 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003516
3517 // Find enclosing context containing both using-directive and
3518 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003519 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003520 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3521 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3522 CommonAncestor = CommonAncestor->getParent();
3523
Sebastian Redla6602e92009-11-23 15:34:23 +00003524 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003525 SS.getRange(),
3526 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003527 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003528 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003529 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003530 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003531 }
3532
Douglas Gregor889ceb72009-02-03 19:21:40 +00003533 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003534 delete AttrList;
John McCall48871652010-08-21 09:40:31 +00003535 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003536}
3537
3538void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3539 // If scope has associated entity, then using directive is at namespace
3540 // or translation unit scope. We add UsingDirectiveDecls, into
3541 // it's lookup structure.
3542 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003543 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003544 else
3545 // Otherwise it is block-sope. using-directives will affect lookup
3546 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003547 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003548}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003549
Douglas Gregorfec52632009-06-20 00:51:54 +00003550
John McCall48871652010-08-21 09:40:31 +00003551Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003552 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003553 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003554 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003555 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003556 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003557 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003558 bool IsTypeName,
3559 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003560 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003561
Douglas Gregor220f4272009-11-04 16:30:06 +00003562 switch (Name.getKind()) {
3563 case UnqualifiedId::IK_Identifier:
3564 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003565 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003566 case UnqualifiedId::IK_ConversionFunctionId:
3567 break;
3568
3569 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003570 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003571 // C++0x inherited constructors.
3572 if (getLangOptions().CPlusPlus0x) break;
3573
Douglas Gregor220f4272009-11-04 16:30:06 +00003574 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3575 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003576 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003577
3578 case UnqualifiedId::IK_DestructorName:
3579 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3580 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003581 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003582
3583 case UnqualifiedId::IK_TemplateId:
3584 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3585 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003586 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003587 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003588
3589 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3590 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003591 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003592 return 0;
John McCall3969e302009-12-08 07:46:18 +00003593
John McCalla0097262009-12-11 02:10:03 +00003594 // Warn about using declarations.
3595 // TODO: store that the declaration was written without 'using' and
3596 // talk about access decls instead of using decls in the
3597 // diagnostics.
3598 if (!HasUsingKeyword) {
3599 UsingLoc = Name.getSourceRange().getBegin();
3600
3601 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003602 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003603 }
3604
John McCall3f746822009-11-17 05:59:44 +00003605 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003606 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003607 /* IsInstantiation */ false,
3608 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003609 if (UD)
3610 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003611
John McCall48871652010-08-21 09:40:31 +00003612 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003613}
3614
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003615/// \brief Determine whether a using declaration considers the given
3616/// declarations as "equivalent", e.g., if they are redeclarations of
3617/// the same entity or are both typedefs of the same type.
3618static bool
3619IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3620 bool &SuppressRedeclaration) {
3621 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3622 SuppressRedeclaration = false;
3623 return true;
3624 }
3625
3626 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3627 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3628 SuppressRedeclaration = true;
3629 return Context.hasSameType(TD1->getUnderlyingType(),
3630 TD2->getUnderlyingType());
3631 }
3632
3633 return false;
3634}
3635
3636
John McCall84d87672009-12-10 09:41:52 +00003637/// Determines whether to create a using shadow decl for a particular
3638/// decl, given the set of decls existing prior to this using lookup.
3639bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3640 const LookupResult &Previous) {
3641 // Diagnose finding a decl which is not from a base class of the
3642 // current class. We do this now because there are cases where this
3643 // function will silently decide not to build a shadow decl, which
3644 // will pre-empt further diagnostics.
3645 //
3646 // We don't need to do this in C++0x because we do the check once on
3647 // the qualifier.
3648 //
3649 // FIXME: diagnose the following if we care enough:
3650 // struct A { int foo; };
3651 // struct B : A { using A::foo; };
3652 // template <class T> struct C : A {};
3653 // template <class T> struct D : C<T> { using B::foo; } // <---
3654 // This is invalid (during instantiation) in C++03 because B::foo
3655 // resolves to the using decl in B, which is not a base class of D<T>.
3656 // We can't diagnose it immediately because C<T> is an unknown
3657 // specialization. The UsingShadowDecl in D<T> then points directly
3658 // to A::foo, which will look well-formed when we instantiate.
3659 // The right solution is to not collapse the shadow-decl chain.
3660 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3661 DeclContext *OrigDC = Orig->getDeclContext();
3662
3663 // Handle enums and anonymous structs.
3664 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3665 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3666 while (OrigRec->isAnonymousStructOrUnion())
3667 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3668
3669 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3670 if (OrigDC == CurContext) {
3671 Diag(Using->getLocation(),
3672 diag::err_using_decl_nested_name_specifier_is_current_class)
3673 << Using->getNestedNameRange();
3674 Diag(Orig->getLocation(), diag::note_using_decl_target);
3675 return true;
3676 }
3677
3678 Diag(Using->getNestedNameRange().getBegin(),
3679 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3680 << Using->getTargetNestedNameDecl()
3681 << cast<CXXRecordDecl>(CurContext)
3682 << Using->getNestedNameRange();
3683 Diag(Orig->getLocation(), diag::note_using_decl_target);
3684 return true;
3685 }
3686 }
3687
3688 if (Previous.empty()) return false;
3689
3690 NamedDecl *Target = Orig;
3691 if (isa<UsingShadowDecl>(Target))
3692 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3693
John McCalla17e83e2009-12-11 02:33:26 +00003694 // If the target happens to be one of the previous declarations, we
3695 // don't have a conflict.
3696 //
3697 // FIXME: but we might be increasing its access, in which case we
3698 // should redeclare it.
3699 NamedDecl *NonTag = 0, *Tag = 0;
3700 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3701 I != E; ++I) {
3702 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003703 bool Result;
3704 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3705 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003706
3707 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3708 }
3709
John McCall84d87672009-12-10 09:41:52 +00003710 if (Target->isFunctionOrFunctionTemplate()) {
3711 FunctionDecl *FD;
3712 if (isa<FunctionTemplateDecl>(Target))
3713 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3714 else
3715 FD = cast<FunctionDecl>(Target);
3716
3717 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003718 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003719 case Ovl_Overload:
3720 return false;
3721
3722 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003723 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003724 break;
3725
3726 // We found a decl with the exact signature.
3727 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003728 // If we're in a record, we want to hide the target, so we
3729 // return true (without a diagnostic) to tell the caller not to
3730 // build a shadow decl.
3731 if (CurContext->isRecord())
3732 return true;
3733
3734 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003735 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003736 break;
3737 }
3738
3739 Diag(Target->getLocation(), diag::note_using_decl_target);
3740 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3741 return true;
3742 }
3743
3744 // Target is not a function.
3745
John McCall84d87672009-12-10 09:41:52 +00003746 if (isa<TagDecl>(Target)) {
3747 // No conflict between a tag and a non-tag.
3748 if (!Tag) return false;
3749
John McCalle29c5cd2009-12-10 19:51:03 +00003750 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003751 Diag(Target->getLocation(), diag::note_using_decl_target);
3752 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3753 return true;
3754 }
3755
3756 // No conflict between a tag and a non-tag.
3757 if (!NonTag) return false;
3758
John McCalle29c5cd2009-12-10 19:51:03 +00003759 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003760 Diag(Target->getLocation(), diag::note_using_decl_target);
3761 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3762 return true;
3763}
3764
John McCall3f746822009-11-17 05:59:44 +00003765/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003766UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003767 UsingDecl *UD,
3768 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003769
3770 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003771 NamedDecl *Target = Orig;
3772 if (isa<UsingShadowDecl>(Target)) {
3773 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3774 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003775 }
3776
3777 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003778 = UsingShadowDecl::Create(Context, CurContext,
3779 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003780 UD->addShadowDecl(Shadow);
3781
3782 if (S)
John McCall3969e302009-12-08 07:46:18 +00003783 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003784 else
John McCall3969e302009-12-08 07:46:18 +00003785 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003786 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003787
John McCallda4458e2010-03-31 01:36:47 +00003788 // Register it as a conversion if appropriate.
3789 if (Shadow->getDeclName().getNameKind()
3790 == DeclarationName::CXXConversionFunctionName)
3791 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3792
John McCall3969e302009-12-08 07:46:18 +00003793 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3794 Shadow->setInvalidDecl();
3795
John McCall84d87672009-12-10 09:41:52 +00003796 return Shadow;
3797}
John McCall3969e302009-12-08 07:46:18 +00003798
John McCall84d87672009-12-10 09:41:52 +00003799/// Hides a using shadow declaration. This is required by the current
3800/// using-decl implementation when a resolvable using declaration in a
3801/// class is followed by a declaration which would hide or override
3802/// one or more of the using decl's targets; for example:
3803///
3804/// struct Base { void foo(int); };
3805/// struct Derived : Base {
3806/// using Base::foo;
3807/// void foo(int);
3808/// };
3809///
3810/// The governing language is C++03 [namespace.udecl]p12:
3811///
3812/// When a using-declaration brings names from a base class into a
3813/// derived class scope, member functions in the derived class
3814/// override and/or hide member functions with the same name and
3815/// parameter types in a base class (rather than conflicting).
3816///
3817/// There are two ways to implement this:
3818/// (1) optimistically create shadow decls when they're not hidden
3819/// by existing declarations, or
3820/// (2) don't create any shadow decls (or at least don't make them
3821/// visible) until we've fully parsed/instantiated the class.
3822/// The problem with (1) is that we might have to retroactively remove
3823/// a shadow decl, which requires several O(n) operations because the
3824/// decl structures are (very reasonably) not designed for removal.
3825/// (2) avoids this but is very fiddly and phase-dependent.
3826void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003827 if (Shadow->getDeclName().getNameKind() ==
3828 DeclarationName::CXXConversionFunctionName)
3829 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3830
John McCall84d87672009-12-10 09:41:52 +00003831 // Remove it from the DeclContext...
3832 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003833
John McCall84d87672009-12-10 09:41:52 +00003834 // ...and the scope, if applicable...
3835 if (S) {
John McCall48871652010-08-21 09:40:31 +00003836 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003837 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003838 }
3839
John McCall84d87672009-12-10 09:41:52 +00003840 // ...and the using decl.
3841 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3842
3843 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003844 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003845}
3846
John McCalle61f2ba2009-11-18 02:36:19 +00003847/// Builds a using declaration.
3848///
3849/// \param IsInstantiation - Whether this call arises from an
3850/// instantiation of an unresolved using declaration. We treat
3851/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003852NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3853 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003854 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003855 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003856 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003857 bool IsInstantiation,
3858 bool IsTypeName,
3859 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003860 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003861 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003862 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003863
Anders Carlssonf038fc22009-08-28 05:49:21 +00003864 // FIXME: We ignore attributes for now.
3865 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003866
Anders Carlsson59140b32009-08-28 03:16:11 +00003867 if (SS.isEmpty()) {
3868 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003869 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003870 }
Mike Stump11289f42009-09-09 15:08:12 +00003871
John McCall84d87672009-12-10 09:41:52 +00003872 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003873 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003874 ForRedeclaration);
3875 Previous.setHideTags(false);
3876 if (S) {
3877 LookupName(Previous, S);
3878
3879 // It is really dumb that we have to do this.
3880 LookupResult::Filter F = Previous.makeFilter();
3881 while (F.hasNext()) {
3882 NamedDecl *D = F.next();
3883 if (!isDeclInScope(D, CurContext, S))
3884 F.erase();
3885 }
3886 F.done();
3887 } else {
3888 assert(IsInstantiation && "no scope in non-instantiation");
3889 assert(CurContext->isRecord() && "scope not record in instantiation");
3890 LookupQualifiedName(Previous, CurContext);
3891 }
3892
Mike Stump11289f42009-09-09 15:08:12 +00003893 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003894 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3895
John McCall84d87672009-12-10 09:41:52 +00003896 // Check for invalid redeclarations.
3897 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3898 return 0;
3899
3900 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003901 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3902 return 0;
3903
John McCall84c16cf2009-11-12 03:15:40 +00003904 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003905 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003906 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003907 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003908 // FIXME: not all declaration name kinds are legal here
3909 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3910 UsingLoc, TypenameLoc,
3911 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003912 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003913 } else {
3914 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003915 UsingLoc, SS.getRange(),
3916 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003917 }
John McCallb96ec562009-12-04 22:46:56 +00003918 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003919 D = UsingDecl::Create(Context, CurContext,
3920 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003921 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003922 }
John McCallb96ec562009-12-04 22:46:56 +00003923 D->setAccess(AS);
3924 CurContext->addDecl(D);
3925
3926 if (!LookupContext) return D;
3927 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003928
John McCall0b66eb32010-05-01 00:40:08 +00003929 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003930 UD->setInvalidDecl();
3931 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003932 }
3933
John McCall3969e302009-12-08 07:46:18 +00003934 // Look up the target name.
3935
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003936 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003937
John McCall3969e302009-12-08 07:46:18 +00003938 // Unlike most lookups, we don't always want to hide tag
3939 // declarations: tag names are visible through the using declaration
3940 // even if hidden by ordinary names, *except* in a dependent context
3941 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003942 if (!IsInstantiation)
3943 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003944
John McCall27b18f82009-11-17 02:14:36 +00003945 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003946
John McCall9f3059a2009-10-09 21:13:30 +00003947 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003948 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003949 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003950 UD->setInvalidDecl();
3951 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003952 }
3953
John McCallb96ec562009-12-04 22:46:56 +00003954 if (R.isAmbiguous()) {
3955 UD->setInvalidDecl();
3956 return UD;
3957 }
Mike Stump11289f42009-09-09 15:08:12 +00003958
John McCalle61f2ba2009-11-18 02:36:19 +00003959 if (IsTypeName) {
3960 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003961 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003962 Diag(IdentLoc, diag::err_using_typename_non_type);
3963 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3964 Diag((*I)->getUnderlyingDecl()->getLocation(),
3965 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003966 UD->setInvalidDecl();
3967 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003968 }
3969 } else {
3970 // If we asked for a non-typename and we got a type, error out,
3971 // but only if this is an instantiation of an unresolved using
3972 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003973 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003974 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3975 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003976 UD->setInvalidDecl();
3977 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003978 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003979 }
3980
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003981 // C++0x N2914 [namespace.udecl]p6:
3982 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003983 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003984 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3985 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003986 UD->setInvalidDecl();
3987 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003988 }
Mike Stump11289f42009-09-09 15:08:12 +00003989
John McCall84d87672009-12-10 09:41:52 +00003990 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3991 if (!CheckUsingShadowDecl(UD, *I, Previous))
3992 BuildUsingShadowDecl(S, UD, *I);
3993 }
John McCall3f746822009-11-17 05:59:44 +00003994
3995 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003996}
3997
John McCall84d87672009-12-10 09:41:52 +00003998/// Checks that the given using declaration is not an invalid
3999/// redeclaration. Note that this is checking only for the using decl
4000/// itself, not for any ill-formedness among the UsingShadowDecls.
4001bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4002 bool isTypeName,
4003 const CXXScopeSpec &SS,
4004 SourceLocation NameLoc,
4005 const LookupResult &Prev) {
4006 // C++03 [namespace.udecl]p8:
4007 // C++0x [namespace.udecl]p10:
4008 // A using-declaration is a declaration and can therefore be used
4009 // repeatedly where (and only where) multiple declarations are
4010 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004011 //
4012 // That's in non-member contexts.
4013 if (!CurContext->getLookupContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004014 return false;
4015
4016 NestedNameSpecifier *Qual
4017 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4018
4019 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4020 NamedDecl *D = *I;
4021
4022 bool DTypename;
4023 NestedNameSpecifier *DQual;
4024 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4025 DTypename = UD->isTypeName();
4026 DQual = UD->getTargetNestedNameDecl();
4027 } else if (UnresolvedUsingValueDecl *UD
4028 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4029 DTypename = false;
4030 DQual = UD->getTargetNestedNameSpecifier();
4031 } else if (UnresolvedUsingTypenameDecl *UD
4032 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4033 DTypename = true;
4034 DQual = UD->getTargetNestedNameSpecifier();
4035 } else continue;
4036
4037 // using decls differ if one says 'typename' and the other doesn't.
4038 // FIXME: non-dependent using decls?
4039 if (isTypeName != DTypename) continue;
4040
4041 // using decls differ if they name different scopes (but note that
4042 // template instantiation can cause this check to trigger when it
4043 // didn't before instantiation).
4044 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4045 Context.getCanonicalNestedNameSpecifier(DQual))
4046 continue;
4047
4048 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004049 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004050 return true;
4051 }
4052
4053 return false;
4054}
4055
John McCall3969e302009-12-08 07:46:18 +00004056
John McCallb96ec562009-12-04 22:46:56 +00004057/// Checks that the given nested-name qualifier used in a using decl
4058/// in the current context is appropriately related to the current
4059/// scope. If an error is found, diagnoses it and returns true.
4060bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4061 const CXXScopeSpec &SS,
4062 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004063 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004064
John McCall3969e302009-12-08 07:46:18 +00004065 if (!CurContext->isRecord()) {
4066 // C++03 [namespace.udecl]p3:
4067 // C++0x [namespace.udecl]p8:
4068 // A using-declaration for a class member shall be a member-declaration.
4069
4070 // If we weren't able to compute a valid scope, it must be a
4071 // dependent class scope.
4072 if (!NamedContext || NamedContext->isRecord()) {
4073 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4074 << SS.getRange();
4075 return true;
4076 }
4077
4078 // Otherwise, everything is known to be fine.
4079 return false;
4080 }
4081
4082 // The current scope is a record.
4083
4084 // If the named context is dependent, we can't decide much.
4085 if (!NamedContext) {
4086 // FIXME: in C++0x, we can diagnose if we can prove that the
4087 // nested-name-specifier does not refer to a base class, which is
4088 // still possible in some cases.
4089
4090 // Otherwise we have to conservatively report that things might be
4091 // okay.
4092 return false;
4093 }
4094
4095 if (!NamedContext->isRecord()) {
4096 // Ideally this would point at the last name in the specifier,
4097 // but we don't have that level of source info.
4098 Diag(SS.getRange().getBegin(),
4099 diag::err_using_decl_nested_name_specifier_is_not_class)
4100 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4101 return true;
4102 }
4103
4104 if (getLangOptions().CPlusPlus0x) {
4105 // C++0x [namespace.udecl]p3:
4106 // In a using-declaration used as a member-declaration, the
4107 // nested-name-specifier shall name a base class of the class
4108 // being defined.
4109
4110 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4111 cast<CXXRecordDecl>(NamedContext))) {
4112 if (CurContext == NamedContext) {
4113 Diag(NameLoc,
4114 diag::err_using_decl_nested_name_specifier_is_current_class)
4115 << SS.getRange();
4116 return true;
4117 }
4118
4119 Diag(SS.getRange().getBegin(),
4120 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4121 << (NestedNameSpecifier*) SS.getScopeRep()
4122 << cast<CXXRecordDecl>(CurContext)
4123 << SS.getRange();
4124 return true;
4125 }
4126
4127 return false;
4128 }
4129
4130 // C++03 [namespace.udecl]p4:
4131 // A using-declaration used as a member-declaration shall refer
4132 // to a member of a base class of the class being defined [etc.].
4133
4134 // Salient point: SS doesn't have to name a base class as long as
4135 // lookup only finds members from base classes. Therefore we can
4136 // diagnose here only if we can prove that that can't happen,
4137 // i.e. if the class hierarchies provably don't intersect.
4138
4139 // TODO: it would be nice if "definitely valid" results were cached
4140 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4141 // need to be repeated.
4142
4143 struct UserData {
4144 llvm::DenseSet<const CXXRecordDecl*> Bases;
4145
4146 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4147 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4148 Data->Bases.insert(Base);
4149 return true;
4150 }
4151
4152 bool hasDependentBases(const CXXRecordDecl *Class) {
4153 return !Class->forallBases(collect, this);
4154 }
4155
4156 /// Returns true if the base is dependent or is one of the
4157 /// accumulated base classes.
4158 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4159 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4160 return !Data->Bases.count(Base);
4161 }
4162
4163 bool mightShareBases(const CXXRecordDecl *Class) {
4164 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4165 }
4166 };
4167
4168 UserData Data;
4169
4170 // Returns false if we find a dependent base.
4171 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4172 return false;
4173
4174 // Returns false if the class has a dependent base or if it or one
4175 // of its bases is present in the base set of the current context.
4176 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4177 return false;
4178
4179 Diag(SS.getRange().getBegin(),
4180 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4181 << (NestedNameSpecifier*) SS.getScopeRep()
4182 << cast<CXXRecordDecl>(CurContext)
4183 << SS.getRange();
4184
4185 return true;
John McCallb96ec562009-12-04 22:46:56 +00004186}
4187
John McCall48871652010-08-21 09:40:31 +00004188Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004189 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004190 SourceLocation AliasLoc,
4191 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004192 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004193 SourceLocation IdentLoc,
4194 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004195
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004196 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004197 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4198 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004199
Anders Carlssondca83c42009-03-28 06:23:46 +00004200 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004201 NamedDecl *PrevDecl
4202 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4203 ForRedeclaration);
4204 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4205 PrevDecl = 0;
4206
4207 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004208 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004209 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004210 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004211 // FIXME: At some point, we'll want to create the (redundant)
4212 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004213 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004214 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004215 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004216 }
Mike Stump11289f42009-09-09 15:08:12 +00004217
Anders Carlssondca83c42009-03-28 06:23:46 +00004218 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4219 diag::err_redefinition_different_kind;
4220 Diag(AliasLoc, DiagID) << Alias;
4221 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004222 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004223 }
4224
John McCall27b18f82009-11-17 02:14:36 +00004225 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004226 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004227
John McCall9f3059a2009-10-09 21:13:30 +00004228 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004229 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4230 CTC_NoKeywords, 0)) {
4231 if (R.getAsSingle<NamespaceDecl>() ||
4232 R.getAsSingle<NamespaceAliasDecl>()) {
4233 if (DeclContext *DC = computeDeclContext(SS, false))
4234 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4235 << Ident << DC << Corrected << SS.getRange()
4236 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4237 else
4238 Diag(IdentLoc, diag::err_using_directive_suggest)
4239 << Ident << Corrected
4240 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4241
4242 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4243 << Corrected;
4244
4245 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004246 } else {
4247 R.clear();
4248 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004249 }
4250 }
4251
4252 if (R.empty()) {
4253 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004254 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004255 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004258 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004259 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4260 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004261 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004262 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCalld8d0d432010-02-16 06:53:13 +00004264 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004265 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004266}
4267
Douglas Gregora57478e2010-05-01 15:04:51 +00004268namespace {
4269 /// \brief Scoped object used to handle the state changes required in Sema
4270 /// to implicitly define the body of a C++ member function;
4271 class ImplicitlyDefinedFunctionScope {
4272 Sema &S;
4273 DeclContext *PreviousContext;
4274
4275 public:
4276 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4277 : S(S), PreviousContext(S.CurContext)
4278 {
4279 S.CurContext = Method;
4280 S.PushFunctionScope();
4281 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4282 }
4283
4284 ~ImplicitlyDefinedFunctionScope() {
4285 S.PopExpressionEvaluationContext();
4286 S.PopFunctionOrBlockScope();
4287 S.CurContext = PreviousContext;
4288 }
4289 };
4290}
4291
Douglas Gregor0be31a22010-07-02 17:43:08 +00004292CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4293 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004294 // C++ [class.ctor]p5:
4295 // A default constructor for a class X is a constructor of class X
4296 // that can be called without an argument. If there is no
4297 // user-declared constructor for class X, a default constructor is
4298 // implicitly declared. An implicitly-declared default constructor
4299 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004300 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4301 "Should not build implicit default constructor!");
4302
Douglas Gregor6d880b12010-07-01 22:31:05 +00004303 // C++ [except.spec]p14:
4304 // An implicitly declared special member function (Clause 12) shall have an
4305 // exception-specification. [...]
4306 ImplicitExceptionSpecification ExceptSpec(Context);
4307
4308 // Direct base-class destructors.
4309 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4310 BEnd = ClassDecl->bases_end();
4311 B != BEnd; ++B) {
4312 if (B->isVirtual()) // Handled below.
4313 continue;
4314
Douglas Gregor9672f922010-07-03 00:47:00 +00004315 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4316 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4317 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4318 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4319 else if (CXXConstructorDecl *Constructor
4320 = BaseClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004321 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004322 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004323 }
4324
4325 // Virtual base-class destructors.
4326 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4327 BEnd = ClassDecl->vbases_end();
4328 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004329 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4330 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4331 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4332 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4333 else if (CXXConstructorDecl *Constructor
4334 = BaseClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004335 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004336 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004337 }
4338
4339 // Field destructors.
4340 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4341 FEnd = ClassDecl->field_end();
4342 F != FEnd; ++F) {
4343 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004344 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4345 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4346 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4347 ExceptSpec.CalledDecl(
4348 DeclareImplicitDefaultConstructor(FieldClassDecl));
4349 else if (CXXConstructorDecl *Constructor
4350 = FieldClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004351 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004352 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004353 }
4354
4355
4356 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004357 CanQualType ClassType
4358 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4359 DeclarationName Name
4360 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004361 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004362 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004363 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004364 Context.getFunctionType(Context.VoidTy,
4365 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004366 ExceptSpec.hasExceptionSpecification(),
4367 ExceptSpec.hasAnyExceptionSpecification(),
4368 ExceptSpec.size(),
4369 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004370 FunctionType::ExtInfo()),
4371 /*TInfo=*/0,
4372 /*isExplicit=*/false,
4373 /*isInline=*/true,
4374 /*isImplicitlyDeclared=*/true);
4375 DefaultCon->setAccess(AS_public);
4376 DefaultCon->setImplicit();
4377 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004378
4379 // Note that we have declared this constructor.
4380 ClassDecl->setDeclaredDefaultConstructor(true);
4381 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4382
Douglas Gregor0be31a22010-07-02 17:43:08 +00004383 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004384 PushOnScopeChains(DefaultCon, S, false);
4385 ClassDecl->addDecl(DefaultCon);
4386
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004387 return DefaultCon;
4388}
4389
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004390void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4391 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004392 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004393 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004394 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004395
Anders Carlsson423f5d82010-04-23 16:04:08 +00004396 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004397 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004398
Douglas Gregora57478e2010-05-01 15:04:51 +00004399 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004400 ErrorTrap Trap(*this);
4401 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4402 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004403 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004404 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004405 Constructor->setInvalidDecl();
4406 } else {
4407 Constructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004408 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004409 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004410}
4411
Douglas Gregor0be31a22010-07-02 17:43:08 +00004412CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004413 // C++ [class.dtor]p2:
4414 // If a class has no user-declared destructor, a destructor is
4415 // declared implicitly. An implicitly-declared destructor is an
4416 // inline public member of its class.
4417
4418 // C++ [except.spec]p14:
4419 // An implicitly declared special member function (Clause 12) shall have
4420 // an exception-specification.
4421 ImplicitExceptionSpecification ExceptSpec(Context);
4422
4423 // Direct base-class destructors.
4424 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4425 BEnd = ClassDecl->bases_end();
4426 B != BEnd; ++B) {
4427 if (B->isVirtual()) // Handled below.
4428 continue;
4429
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 // Virtual base-class destructors.
4436 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4437 BEnd = ClassDecl->vbases_end();
4438 B != BEnd; ++B) {
4439 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4440 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004441 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004442 }
4443
4444 // Field destructors.
4445 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4446 FEnd = ClassDecl->field_end();
4447 F != FEnd; ++F) {
4448 if (const RecordType *RecordTy
4449 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4450 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004451 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004452 }
4453
Douglas Gregor7454c562010-07-02 20:37:36 +00004454 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004455 QualType Ty = Context.getFunctionType(Context.VoidTy,
4456 0, 0, false, 0,
4457 ExceptSpec.hasExceptionSpecification(),
4458 ExceptSpec.hasAnyExceptionSpecification(),
4459 ExceptSpec.size(),
4460 ExceptSpec.data(),
4461 FunctionType::ExtInfo());
4462
4463 CanQualType ClassType
4464 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4465 DeclarationName Name
4466 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004467 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004468 CXXDestructorDecl *Destructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004469 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorf1203042010-07-01 19:09:28 +00004470 /*isInline=*/true,
4471 /*isImplicitlyDeclared=*/true);
4472 Destructor->setAccess(AS_public);
4473 Destructor->setImplicit();
4474 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004475
4476 // Note that we have declared this destructor.
4477 ClassDecl->setDeclaredDestructor(true);
4478 ++ASTContext::NumImplicitDestructorsDeclared;
4479
4480 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004481 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004482 PushOnScopeChains(Destructor, S, false);
4483 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004484
4485 // This could be uniqued if it ever proves significant.
4486 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4487
4488 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004489
Douglas Gregorf1203042010-07-01 19:09:28 +00004490 return Destructor;
4491}
4492
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004493void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004494 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004495 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004496 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004497 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004498 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004499
Douglas Gregor54818f02010-05-12 16:39:35 +00004500 if (Destructor->isInvalidDecl())
4501 return;
4502
Douglas Gregora57478e2010-05-01 15:04:51 +00004503 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004504
Douglas Gregor54818f02010-05-12 16:39:35 +00004505 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004506 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4507 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004508
Douglas Gregor54818f02010-05-12 16:39:35 +00004509 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004510 Diag(CurrentLocation, diag::note_member_synthesized_at)
4511 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4512
4513 Destructor->setInvalidDecl();
4514 return;
4515 }
4516
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004517 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004518 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004519}
4520
Douglas Gregorb139cd52010-05-01 20:49:11 +00004521/// \brief Builds a statement that copies the given entity from \p From to
4522/// \c To.
4523///
4524/// This routine is used to copy the members of a class with an
4525/// implicitly-declared copy assignment operator. When the entities being
4526/// copied are arrays, this routine builds for loops to copy them.
4527///
4528/// \param S The Sema object used for type-checking.
4529///
4530/// \param Loc The location where the implicit copy is being generated.
4531///
4532/// \param T The type of the expressions being copied. Both expressions must
4533/// have this type.
4534///
4535/// \param To The expression we are copying to.
4536///
4537/// \param From The expression we are copying from.
4538///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004539/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4540/// Otherwise, it's a non-static member subobject.
4541///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004542/// \param Depth Internal parameter recording the depth of the recursion.
4543///
4544/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004545static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004546BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004547 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004548 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004549 // C++0x [class.copy]p30:
4550 // Each subobject is assigned in the manner appropriate to its type:
4551 //
4552 // - if the subobject is of class type, the copy assignment operator
4553 // for the class is used (as if by explicit qualification; that is,
4554 // ignoring any possible virtual overriding functions in more derived
4555 // classes);
4556 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4557 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4558
4559 // Look for operator=.
4560 DeclarationName Name
4561 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4562 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4563 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4564
4565 // Filter out any result that isn't a copy-assignment operator.
4566 LookupResult::Filter F = OpLookup.makeFilter();
4567 while (F.hasNext()) {
4568 NamedDecl *D = F.next();
4569 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4570 if (Method->isCopyAssignmentOperator())
4571 continue;
4572
4573 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004574 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004575 F.done();
4576
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004577 // Suppress the protected check (C++ [class.protected]) for each of the
4578 // assignment operators we found. This strange dance is required when
4579 // we're assigning via a base classes's copy-assignment operator. To
4580 // ensure that we're getting the right base class subobject (without
4581 // ambiguities), we need to cast "this" to that subobject type; to
4582 // ensure that we don't go through the virtual call mechanism, we need
4583 // to qualify the operator= name with the base class (see below). However,
4584 // this means that if the base class has a protected copy assignment
4585 // operator, the protected member access check will fail. So, we
4586 // rewrite "protected" access to "public" access in this case, since we
4587 // know by construction that we're calling from a derived class.
4588 if (CopyingBaseSubobject) {
4589 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4590 L != LEnd; ++L) {
4591 if (L.getAccess() == AS_protected)
4592 L.setAccess(AS_public);
4593 }
4594 }
4595
Douglas Gregorb139cd52010-05-01 20:49:11 +00004596 // Create the nested-name-specifier that will be used to qualify the
4597 // reference to operator=; this is required to suppress the virtual
4598 // call mechanism.
4599 CXXScopeSpec SS;
4600 SS.setRange(Loc);
4601 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4602 T.getTypePtr()));
4603
4604 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004605 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004606 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004607 /*FirstQualifierInScope=*/0, OpLookup,
4608 /*TemplateArgs=*/0,
4609 /*SuppressQualifierCheck=*/true);
4610 if (OpEqualRef.isInvalid())
4611 return S.StmtError();
4612
4613 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004614
John McCalldadc5752010-08-24 06:29:42 +00004615 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004616 OpEqualRef.takeAs<Expr>(),
John McCallb268a282010-08-23 23:25:46 +00004617 Loc, &From, 1, 0, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004618 if (Call.isInvalid())
4619 return S.StmtError();
4620
4621 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004622 }
John McCallab8c2732010-03-16 06:11:48 +00004623
Douglas Gregorb139cd52010-05-01 20:49:11 +00004624 // - if the subobject is of scalar type, the built-in assignment
4625 // operator is used.
4626 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4627 if (!ArrayTy) {
John McCalldadc5752010-08-24 06:29:42 +00004628 ExprResult Assignment = S.CreateBuiltinBinOp(Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004629 BinaryOperator::Assign,
John McCallb268a282010-08-23 23:25:46 +00004630 To,
4631 From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004632 if (Assignment.isInvalid())
4633 return S.StmtError();
4634
4635 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004636 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004637
4638 // - if the subobject is an array, each element is assigned, in the
4639 // manner appropriate to the element type;
4640
4641 // Construct a loop over the array bounds, e.g.,
4642 //
4643 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4644 //
4645 // that will copy each of the array elements.
4646 QualType SizeType = S.Context.getSizeType();
4647
4648 // Create the iteration variable.
4649 IdentifierInfo *IterationVarName = 0;
4650 {
4651 llvm::SmallString<8> Str;
4652 llvm::raw_svector_ostream OS(Str);
4653 OS << "__i" << Depth;
4654 IterationVarName = &S.Context.Idents.get(OS.str());
4655 }
4656 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4657 IterationVarName, SizeType,
4658 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4659 VarDecl::None, VarDecl::None);
4660
4661 // Initialize the iteration variable to zero.
4662 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4663 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4664
4665 // Create a reference to the iteration variable; we'll use this several
4666 // times throughout.
4667 Expr *IterationVarRef
4668 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4669 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4670
4671 // Create the DeclStmt that holds the iteration variable.
4672 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4673
4674 // Create the comparison against the array bound.
4675 llvm::APInt Upper = ArrayTy->getSize();
4676 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004677 Expr *Comparison
4678 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00004679 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
John McCallb268a282010-08-23 23:25:46 +00004680 BinaryOperator::NE, S.Context.BoolTy, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004681
4682 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004683 Expr *Increment
4684 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4685 UnaryOperator::PreInc,
4686 SizeType, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004687
4688 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004689 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4690 IterationVarRef, Loc));
4691 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4692 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004693
4694 // Build the copy for an individual element of the array.
John McCalldadc5752010-08-24 06:29:42 +00004695 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004696 ArrayTy->getElementType(),
John McCallb268a282010-08-23 23:25:46 +00004697 To, From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004698 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004699 if (Copy.isInvalid())
Douglas Gregorb139cd52010-05-01 20:49:11 +00004700 return S.StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004701
4702 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004703 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004704 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004705 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004706 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004707}
4708
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004709/// \brief Determine whether the given class has a copy assignment operator
4710/// that accepts a const-qualified argument.
4711static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4712 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4713
4714 if (!Class->hasDeclaredCopyAssignment())
4715 S.DeclareImplicitCopyAssignment(Class);
4716
4717 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4718 DeclarationName OpName
4719 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4720
4721 DeclContext::lookup_const_iterator Op, OpEnd;
4722 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4723 // C++ [class.copy]p9:
4724 // A user-declared copy assignment operator is a non-static non-template
4725 // member function of class X with exactly one parameter of type X, X&,
4726 // const X&, volatile X& or const volatile X&.
4727 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4728 if (!Method)
4729 continue;
4730
4731 if (Method->isStatic())
4732 continue;
4733 if (Method->getPrimaryTemplate())
4734 continue;
4735 const FunctionProtoType *FnType =
4736 Method->getType()->getAs<FunctionProtoType>();
4737 assert(FnType && "Overloaded operator has no prototype.");
4738 // Don't assert on this; an invalid decl might have been left in the AST.
4739 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4740 continue;
4741 bool AcceptsConst = true;
4742 QualType ArgType = FnType->getArgType(0);
4743 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4744 ArgType = Ref->getPointeeType();
4745 // Is it a non-const lvalue reference?
4746 if (!ArgType.isConstQualified())
4747 AcceptsConst = false;
4748 }
4749 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4750 continue;
4751
4752 // We have a single argument of type cv X or cv X&, i.e. we've found the
4753 // copy assignment operator. Return whether it accepts const arguments.
4754 return AcceptsConst;
4755 }
4756 assert(Class->isInvalidDecl() &&
4757 "No copy assignment operator declared in valid code.");
4758 return false;
4759}
4760
Douglas Gregor0be31a22010-07-02 17:43:08 +00004761CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004762 // Note: The following rules are largely analoguous to the copy
4763 // constructor rules. Note that virtual bases are not taken into account
4764 // for determining the argument type of the operator. Note also that
4765 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004766
4767
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004768 // C++ [class.copy]p10:
4769 // If the class definition does not explicitly declare a copy
4770 // assignment operator, one is declared implicitly.
4771 // The implicitly-defined copy assignment operator for a class X
4772 // will have the form
4773 //
4774 // X& X::operator=(const X&)
4775 //
4776 // if
4777 bool HasConstCopyAssignment = true;
4778
4779 // -- each direct base class B of X has a copy assignment operator
4780 // whose parameter is of type const B&, const volatile B& or B,
4781 // and
4782 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4783 BaseEnd = ClassDecl->bases_end();
4784 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4785 assert(!Base->getType()->isDependentType() &&
4786 "Cannot generate implicit members for class with dependent bases.");
4787 const CXXRecordDecl *BaseClassDecl
4788 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004789 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004790 }
4791
4792 // -- for all the nonstatic data members of X that are of a class
4793 // type M (or array thereof), each such class type has a copy
4794 // assignment operator whose parameter is of type const M&,
4795 // const volatile M& or M.
4796 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4797 FieldEnd = ClassDecl->field_end();
4798 HasConstCopyAssignment && Field != FieldEnd;
4799 ++Field) {
4800 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4801 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4802 const CXXRecordDecl *FieldClassDecl
4803 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004804 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004805 }
4806 }
4807
4808 // Otherwise, the implicitly declared copy assignment operator will
4809 // have the form
4810 //
4811 // X& X::operator=(X&)
4812 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4813 QualType RetType = Context.getLValueReferenceType(ArgType);
4814 if (HasConstCopyAssignment)
4815 ArgType = ArgType.withConst();
4816 ArgType = Context.getLValueReferenceType(ArgType);
4817
Douglas Gregor68e11362010-07-01 17:48:08 +00004818 // C++ [except.spec]p14:
4819 // An implicitly declared special member function (Clause 12) shall have an
4820 // exception-specification. [...]
4821 ImplicitExceptionSpecification ExceptSpec(Context);
4822 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4823 BaseEnd = ClassDecl->bases_end();
4824 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004825 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004826 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004827
4828 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4829 DeclareImplicitCopyAssignment(BaseClassDecl);
4830
Douglas Gregor68e11362010-07-01 17:48:08 +00004831 if (CXXMethodDecl *CopyAssign
4832 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4833 ExceptSpec.CalledDecl(CopyAssign);
4834 }
4835 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4836 FieldEnd = ClassDecl->field_end();
4837 Field != FieldEnd;
4838 ++Field) {
4839 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4840 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004841 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004842 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004843
4844 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4845 DeclareImplicitCopyAssignment(FieldClassDecl);
4846
Douglas Gregor68e11362010-07-01 17:48:08 +00004847 if (CXXMethodDecl *CopyAssign
4848 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4849 ExceptSpec.CalledDecl(CopyAssign);
4850 }
4851 }
4852
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004853 // An implicitly-declared copy assignment operator is an inline public
4854 // member of its class.
4855 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004856 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004857 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004858 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004859 Context.getFunctionType(RetType, &ArgType, 1,
4860 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004861 ExceptSpec.hasExceptionSpecification(),
4862 ExceptSpec.hasAnyExceptionSpecification(),
4863 ExceptSpec.size(),
4864 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004865 FunctionType::ExtInfo()),
4866 /*TInfo=*/0, /*isStatic=*/false,
4867 /*StorageClassAsWritten=*/FunctionDecl::None,
4868 /*isInline=*/true);
4869 CopyAssignment->setAccess(AS_public);
4870 CopyAssignment->setImplicit();
4871 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4872 CopyAssignment->setCopyAssignment(true);
4873
4874 // Add the parameter to the operator.
4875 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4876 ClassDecl->getLocation(),
4877 /*Id=*/0,
4878 ArgType, /*TInfo=*/0,
4879 VarDecl::None,
4880 VarDecl::None, 0);
4881 CopyAssignment->setParams(&FromParam, 1);
4882
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004883 // Note that we have added this copy-assignment operator.
4884 ClassDecl->setDeclaredCopyAssignment(true);
4885 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4886
Douglas Gregor0be31a22010-07-02 17:43:08 +00004887 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004888 PushOnScopeChains(CopyAssignment, S, false);
4889 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004890
4891 AddOverriddenMethods(ClassDecl, CopyAssignment);
4892 return CopyAssignment;
4893}
4894
Douglas Gregorb139cd52010-05-01 20:49:11 +00004895void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4896 CXXMethodDecl *CopyAssignOperator) {
4897 assert((CopyAssignOperator->isImplicit() &&
4898 CopyAssignOperator->isOverloadedOperator() &&
4899 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004900 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004901 "DefineImplicitCopyAssignment called for wrong function");
4902
4903 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4904
4905 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4906 CopyAssignOperator->setInvalidDecl();
4907 return;
4908 }
4909
4910 CopyAssignOperator->setUsed();
4911
4912 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004913 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004914
4915 // C++0x [class.copy]p30:
4916 // The implicitly-defined or explicitly-defaulted copy assignment operator
4917 // for a non-union class X performs memberwise copy assignment of its
4918 // subobjects. The direct base classes of X are assigned first, in the
4919 // order of their declaration in the base-specifier-list, and then the
4920 // immediate non-static data members of X are assigned, in the order in
4921 // which they were declared in the class definition.
4922
4923 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004924 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004925
4926 // The parameter for the "other" object, which we are copying from.
4927 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4928 Qualifiers OtherQuals = Other->getType().getQualifiers();
4929 QualType OtherRefType = Other->getType();
4930 if (const LValueReferenceType *OtherRef
4931 = OtherRefType->getAs<LValueReferenceType>()) {
4932 OtherRefType = OtherRef->getPointeeType();
4933 OtherQuals = OtherRefType.getQualifiers();
4934 }
4935
4936 // Our location for everything implicitly-generated.
4937 SourceLocation Loc = CopyAssignOperator->getLocation();
4938
4939 // Construct a reference to the "other" object. We'll be using this
4940 // throughout the generated ASTs.
4941 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4942 assert(OtherRef && "Reference to parameter cannot fail!");
4943
4944 // Construct the "this" pointer. We'll be using this throughout the generated
4945 // ASTs.
4946 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4947 assert(This && "Reference to this cannot fail!");
4948
4949 // Assign base classes.
4950 bool Invalid = false;
4951 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4952 E = ClassDecl->bases_end(); Base != E; ++Base) {
4953 // Form the assignment:
4954 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4955 QualType BaseType = Base->getType().getUnqualifiedType();
4956 CXXRecordDecl *BaseClassDecl = 0;
4957 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4958 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4959 else {
4960 Invalid = true;
4961 continue;
4962 }
4963
John McCallcf142162010-08-07 06:22:56 +00004964 CXXCastPath BasePath;
4965 BasePath.push_back(Base);
4966
Douglas Gregorb139cd52010-05-01 20:49:11 +00004967 // Construct the "from" expression, which is an implicit cast to the
4968 // appropriately-qualified base type.
4969 Expr *From = OtherRef->Retain();
4970 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004971 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00004972 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004973
4974 // Dereference "this".
John McCalldadc5752010-08-24 06:29:42 +00004975 ExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004976
4977 // Implicitly cast "this" to the appropriately-qualified base type.
4978 Expr *ToE = To.takeAs<Expr>();
4979 ImpCastExprToType(ToE,
4980 Context.getCVRQualifiedType(BaseType,
4981 CopyAssignOperator->getTypeQualifiers()),
4982 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00004983 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004984 To = Owned(ToE);
4985
4986 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004987 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCallb268a282010-08-23 23:25:46 +00004988 To.get(), From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004989 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004990 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004991 Diag(CurrentLocation, diag::note_member_synthesized_at)
4992 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4993 CopyAssignOperator->setInvalidDecl();
4994 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004995 }
4996
4997 // Success! Record the copy.
4998 Statements.push_back(Copy.takeAs<Expr>());
4999 }
5000
5001 // \brief Reference to the __builtin_memcpy function.
5002 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005003 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005004 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005005
5006 // Assign non-static members.
5007 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5008 FieldEnd = ClassDecl->field_end();
5009 Field != FieldEnd; ++Field) {
5010 // Check for members of reference type; we can't copy those.
5011 if (Field->getType()->isReferenceType()) {
5012 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5013 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5014 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005015 Diag(CurrentLocation, diag::note_member_synthesized_at)
5016 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005017 Invalid = true;
5018 continue;
5019 }
5020
5021 // Check for members of const-qualified, non-class type.
5022 QualType BaseType = Context.getBaseElementType(Field->getType());
5023 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5024 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5025 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5026 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005027 Diag(CurrentLocation, diag::note_member_synthesized_at)
5028 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005029 Invalid = true;
5030 continue;
5031 }
5032
5033 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005034 if (FieldType->isIncompleteArrayType()) {
5035 assert(ClassDecl->hasFlexibleArrayMember() &&
5036 "Incomplete array type is not valid");
5037 continue;
5038 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005039
5040 // Build references to the field in the object we're copying from and to.
5041 CXXScopeSpec SS; // Intentionally empty
5042 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5043 LookupMemberName);
5044 MemberLookup.addDecl(*Field);
5045 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005046 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005047 Loc, /*IsArrow=*/false,
5048 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005049 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005050 Loc, /*IsArrow=*/true,
5051 SS, 0, MemberLookup, 0);
5052 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5053 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5054
5055 // If the field should be copied with __builtin_memcpy rather than via
5056 // explicit assignments, do so. This optimization only applies for arrays
5057 // of scalars and arrays of class type with trivial copy-assignment
5058 // operators.
5059 if (FieldType->isArrayType() &&
5060 (!BaseType->isRecordType() ||
5061 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5062 ->hasTrivialCopyAssignment())) {
5063 // Compute the size of the memory buffer to be copied.
5064 QualType SizeType = Context.getSizeType();
5065 llvm::APInt Size(Context.getTypeSize(SizeType),
5066 Context.getTypeSizeInChars(BaseType).getQuantity());
5067 for (const ConstantArrayType *Array
5068 = Context.getAsConstantArrayType(FieldType);
5069 Array;
5070 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5071 llvm::APInt ArraySize = Array->getSize();
5072 ArraySize.zextOrTrunc(Size.getBitWidth());
5073 Size *= ArraySize;
5074 }
5075
5076 // Take the address of the field references for "from" and "to".
John McCallb268a282010-08-23 23:25:46 +00005077 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, From.get());
5078 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005079
5080 bool NeedsCollectableMemCpy =
5081 (BaseType->isRecordType() &&
5082 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5083
5084 if (NeedsCollectableMemCpy) {
5085 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005086 // Create a reference to the __builtin_objc_memmove_collectable function.
5087 LookupResult R(*this,
5088 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005089 Loc, LookupOrdinaryName);
5090 LookupName(R, TUScope, true);
5091
5092 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5093 if (!CollectableMemCpy) {
5094 // Something went horribly wrong earlier, and we will have
5095 // complained about it.
5096 Invalid = true;
5097 continue;
5098 }
5099
5100 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5101 CollectableMemCpy->getType(),
5102 Loc, 0).takeAs<Expr>();
5103 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5104 }
5105 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005106 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005107 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005108 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5109 LookupOrdinaryName);
5110 LookupName(R, TUScope, true);
5111
5112 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5113 if (!BuiltinMemCpy) {
5114 // Something went horribly wrong earlier, and we will have complained
5115 // about it.
5116 Invalid = true;
5117 continue;
5118 }
5119
5120 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5121 BuiltinMemCpy->getType(),
5122 Loc, 0).takeAs<Expr>();
5123 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5124 }
5125
John McCall37ad5512010-08-23 06:44:23 +00005126 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005127 CallArgs.push_back(To.takeAs<Expr>());
5128 CallArgs.push_back(From.takeAs<Expr>());
5129 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
5130 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5131 Commas.push_back(Loc);
5132 Commas.push_back(Loc);
John McCalldadc5752010-08-24 06:29:42 +00005133 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005134 if (NeedsCollectableMemCpy)
5135 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005136 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005137 Loc, move_arg(CallArgs),
5138 Commas.data(), Loc);
5139 else
5140 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005141 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005142 Loc, move_arg(CallArgs),
5143 Commas.data(), Loc);
5144
Douglas Gregorb139cd52010-05-01 20:49:11 +00005145 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5146 Statements.push_back(Call.takeAs<Expr>());
5147 continue;
5148 }
5149
5150 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005151 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005152 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005153 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005154 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005155 Diag(CurrentLocation, diag::note_member_synthesized_at)
5156 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5157 CopyAssignOperator->setInvalidDecl();
5158 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005159 }
5160
5161 // Success! Record the copy.
5162 Statements.push_back(Copy.takeAs<Stmt>());
5163 }
5164
5165 if (!Invalid) {
5166 // Add a "return *this;"
John McCalldadc5752010-08-24 06:29:42 +00005167 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
John McCallb268a282010-08-23 23:25:46 +00005168 This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005169
John McCalldadc5752010-08-24 06:29:42 +00005170 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005171 if (Return.isInvalid())
5172 Invalid = true;
5173 else {
5174 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005175
5176 if (Trap.hasErrorOccurred()) {
5177 Diag(CurrentLocation, diag::note_member_synthesized_at)
5178 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5179 Invalid = true;
5180 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005181 }
5182 }
5183
5184 if (Invalid) {
5185 CopyAssignOperator->setInvalidDecl();
5186 return;
5187 }
5188
John McCalldadc5752010-08-24 06:29:42 +00005189 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005190 /*isStmtExpr=*/false);
5191 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5192 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005193}
5194
Douglas Gregor0be31a22010-07-02 17:43:08 +00005195CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5196 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005197 // C++ [class.copy]p4:
5198 // If the class definition does not explicitly declare a copy
5199 // constructor, one is declared implicitly.
5200
Douglas Gregor54be3392010-07-01 17:57:27 +00005201 // C++ [class.copy]p5:
5202 // The implicitly-declared copy constructor for a class X will
5203 // have the form
5204 //
5205 // X::X(const X&)
5206 //
5207 // if
5208 bool HasConstCopyConstructor = true;
5209
5210 // -- each direct or virtual base class B of X has a copy
5211 // constructor whose first parameter is of type const B& or
5212 // const volatile B&, and
5213 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5214 BaseEnd = ClassDecl->bases_end();
5215 HasConstCopyConstructor && Base != BaseEnd;
5216 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005217 // Virtual bases are handled below.
5218 if (Base->isVirtual())
5219 continue;
5220
Douglas Gregora6d69502010-07-02 23:41:54 +00005221 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005223 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5224 DeclareImplicitCopyConstructor(BaseClassDecl);
5225
Douglas Gregorcfe68222010-07-01 18:27:03 +00005226 HasConstCopyConstructor
5227 = BaseClassDecl->hasConstCopyConstructor(Context);
5228 }
5229
5230 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5231 BaseEnd = ClassDecl->vbases_end();
5232 HasConstCopyConstructor && Base != BaseEnd;
5233 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005234 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005235 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005236 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5237 DeclareImplicitCopyConstructor(BaseClassDecl);
5238
Douglas Gregor54be3392010-07-01 17:57:27 +00005239 HasConstCopyConstructor
5240 = BaseClassDecl->hasConstCopyConstructor(Context);
5241 }
5242
5243 // -- for all the nonstatic data members of X that are of a
5244 // class type M (or array thereof), each such class type
5245 // has a copy constructor whose first parameter is of type
5246 // const M& or const volatile M&.
5247 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5248 FieldEnd = ClassDecl->field_end();
5249 HasConstCopyConstructor && Field != FieldEnd;
5250 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005251 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005252 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005253 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005254 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005255 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5256 DeclareImplicitCopyConstructor(FieldClassDecl);
5257
Douglas Gregor54be3392010-07-01 17:57:27 +00005258 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005259 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005260 }
5261 }
5262
5263 // Otherwise, the implicitly declared copy constructor will have
5264 // the form
5265 //
5266 // X::X(X&)
5267 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5268 QualType ArgType = ClassType;
5269 if (HasConstCopyConstructor)
5270 ArgType = ArgType.withConst();
5271 ArgType = Context.getLValueReferenceType(ArgType);
5272
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005273 // C++ [except.spec]p14:
5274 // An implicitly declared special member function (Clause 12) shall have an
5275 // exception-specification. [...]
5276 ImplicitExceptionSpecification ExceptSpec(Context);
5277 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5278 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5279 BaseEnd = ClassDecl->bases_end();
5280 Base != BaseEnd;
5281 ++Base) {
5282 // Virtual bases are handled below.
5283 if (Base->isVirtual())
5284 continue;
5285
Douglas Gregora6d69502010-07-02 23:41:54 +00005286 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005287 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005288 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5289 DeclareImplicitCopyConstructor(BaseClassDecl);
5290
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005291 if (CXXConstructorDecl *CopyConstructor
5292 = BaseClassDecl->getCopyConstructor(Context, Quals))
5293 ExceptSpec.CalledDecl(CopyConstructor);
5294 }
5295 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5296 BaseEnd = ClassDecl->vbases_end();
5297 Base != BaseEnd;
5298 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005299 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005300 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005301 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5302 DeclareImplicitCopyConstructor(BaseClassDecl);
5303
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005304 if (CXXConstructorDecl *CopyConstructor
5305 = BaseClassDecl->getCopyConstructor(Context, Quals))
5306 ExceptSpec.CalledDecl(CopyConstructor);
5307 }
5308 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5309 FieldEnd = ClassDecl->field_end();
5310 Field != FieldEnd;
5311 ++Field) {
5312 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5313 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005314 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005315 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005316 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5317 DeclareImplicitCopyConstructor(FieldClassDecl);
5318
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005319 if (CXXConstructorDecl *CopyConstructor
5320 = FieldClassDecl->getCopyConstructor(Context, Quals))
5321 ExceptSpec.CalledDecl(CopyConstructor);
5322 }
5323 }
5324
Douglas Gregor54be3392010-07-01 17:57:27 +00005325 // An implicitly-declared copy constructor is an inline public
5326 // member of its class.
5327 DeclarationName Name
5328 = Context.DeclarationNames.getCXXConstructorName(
5329 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005330 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005331 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005332 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005333 Context.getFunctionType(Context.VoidTy,
5334 &ArgType, 1,
5335 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005336 ExceptSpec.hasExceptionSpecification(),
5337 ExceptSpec.hasAnyExceptionSpecification(),
5338 ExceptSpec.size(),
5339 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005340 FunctionType::ExtInfo()),
5341 /*TInfo=*/0,
5342 /*isExplicit=*/false,
5343 /*isInline=*/true,
5344 /*isImplicitlyDeclared=*/true);
5345 CopyConstructor->setAccess(AS_public);
5346 CopyConstructor->setImplicit();
5347 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5348
Douglas Gregora6d69502010-07-02 23:41:54 +00005349 // Note that we have declared this constructor.
5350 ClassDecl->setDeclaredCopyConstructor(true);
5351 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5352
Douglas Gregor54be3392010-07-01 17:57:27 +00005353 // Add the parameter to the constructor.
5354 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5355 ClassDecl->getLocation(),
5356 /*IdentifierInfo=*/0,
5357 ArgType, /*TInfo=*/0,
5358 VarDecl::None,
5359 VarDecl::None, 0);
5360 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005361 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005362 PushOnScopeChains(CopyConstructor, S, false);
5363 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005364
5365 return CopyConstructor;
5366}
5367
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005368void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5369 CXXConstructorDecl *CopyConstructor,
5370 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005371 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005372 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005373 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005374 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005375
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005376 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005377 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005378
Douglas Gregora57478e2010-05-01 15:04:51 +00005379 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005380 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005381
Douglas Gregor54818f02010-05-12 16:39:35 +00005382 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5383 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005384 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005385 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005386 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005387 } else {
5388 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5389 CopyConstructor->getLocation(),
5390 MultiStmtArg(*this, 0, 0),
5391 /*isStmtExpr=*/false)
5392 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005393 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005394
5395 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005396}
5397
John McCalldadc5752010-08-24 06:29:42 +00005398ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005399Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005400 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005401 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005402 bool RequiresZeroInit,
John McCallbfd822c2010-08-24 07:32:53 +00005403 unsigned ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005404 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005405
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005406 // C++0x [class.copy]p34:
5407 // When certain criteria are met, an implementation is allowed to
5408 // omit the copy/move construction of a class object, even if the
5409 // copy/move constructor and/or destructor for the object have
5410 // side effects. [...]
5411 // - when a temporary class object that has not been bound to a
5412 // reference (12.2) would be copied/moved to a class object
5413 // with the same cv-unqualified type, the copy/move operation
5414 // can be omitted by constructing the temporary object
5415 // directly into the target of the omitted copy/move
5416 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5417 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5418 Elidable = SubExpr->isTemporaryObject() &&
Douglas Gregorec3a3f52010-08-22 18:27:02 +00005419 ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005420 Context.hasSameUnqualifiedType(SubExpr->getType(),
5421 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00005422 }
Mike Stump11289f42009-09-09 15:08:12 +00005423
5424 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005425 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005426 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00005427}
5428
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005429/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5430/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005431ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005432Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5433 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005434 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005435 bool RequiresZeroInit,
John McCallbfd822c2010-08-24 07:32:53 +00005436 unsigned ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005437 unsigned NumExprs = ExprArgs.size();
5438 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005439
Douglas Gregor27381f32009-11-23 12:27:39 +00005440 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005441 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005442 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005443 RequiresZeroInit,
5444 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005445}
5446
Mike Stump11289f42009-09-09 15:08:12 +00005447bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005448 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005449 MultiExprArg Exprs) {
John McCalldadc5752010-08-24 06:29:42 +00005450 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005451 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00005452 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005453 if (TempResult.isInvalid())
5454 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005455
Anders Carlsson6eb55572009-08-25 05:12:04 +00005456 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00005457 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005458 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005459 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005460
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005461 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005462}
5463
John McCall03c48482010-02-02 09:10:11 +00005464void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5465 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005466 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005467 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005468 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005469 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005470 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005471 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005472 << VD->getDeclName()
5473 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005474
5475 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5476 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005477 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005478}
5479
Mike Stump11289f42009-09-09 15:08:12 +00005480/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005481/// ActOnDeclarator, when a C++ direct initializer is present.
5482/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005483void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005484 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005485 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005486 SourceLocation *CommaLocs,
5487 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005488 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005489
5490 // If there is no declaration, there was an error parsing it. Just ignore
5491 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005492 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005493 return;
Mike Stump11289f42009-09-09 15:08:12 +00005494
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005495 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5496 if (!VDecl) {
5497 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5498 RealDecl->setInvalidDecl();
5499 return;
5500 }
5501
Douglas Gregor402250f2009-08-26 21:14:46 +00005502 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005503 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005504 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5505 //
5506 // Clients that want to distinguish between the two forms, can check for
5507 // direct initializer using VarDecl::hasCXXDirectInitializer().
5508 // A major benefit is that clients that don't particularly care about which
5509 // exactly form was it (like the CodeGen) can handle both cases without
5510 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005511
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005512 // C++ 8.5p11:
5513 // The form of initialization (using parentheses or '=') is generally
5514 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005515 // class type.
5516
Douglas Gregor50dc2192010-02-11 22:55:30 +00005517 if (!VDecl->getType()->isDependentType() &&
5518 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005519 diag::err_typecheck_decl_incomplete_type)) {
5520 VDecl->setInvalidDecl();
5521 return;
5522 }
5523
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005524 // The variable can not have an abstract class type.
5525 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5526 diag::err_abstract_type_in_decl,
5527 AbstractVariableType))
5528 VDecl->setInvalidDecl();
5529
Sebastian Redl5ca79842010-02-01 20:16:42 +00005530 const VarDecl *Def;
5531 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005532 Diag(VDecl->getLocation(), diag::err_redefinition)
5533 << VDecl->getDeclName();
5534 Diag(Def->getLocation(), diag::note_previous_definition);
5535 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005536 return;
5537 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005538
Douglas Gregorf0f83692010-08-24 05:27:49 +00005539 // C++ [class.static.data]p4
5540 // If a static data member is of const integral or const
5541 // enumeration type, its declaration in the class definition can
5542 // specify a constant-initializer which shall be an integral
5543 // constant expression (5.19). In that case, the member can appear
5544 // in integral constant expressions. The member shall still be
5545 // defined in a namespace scope if it is used in the program and the
5546 // namespace scope definition shall not contain an initializer.
5547 //
5548 // We already performed a redefinition check above, but for static
5549 // data members we also need to check whether there was an in-class
5550 // declaration with an initializer.
5551 const VarDecl* PrevInit = 0;
5552 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5553 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5554 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5555 return;
5556 }
5557
Douglas Gregor50dc2192010-02-11 22:55:30 +00005558 // If either the declaration has a dependent type or if any of the
5559 // expressions is type-dependent, we represent the initialization
5560 // via a ParenListExpr for later use during template instantiation.
5561 if (VDecl->getType()->isDependentType() ||
5562 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5563 // Let clients know that initialization was done with a direct initializer.
5564 VDecl->setCXXDirectInitializer(true);
5565
5566 // Store the initialization expressions as a ParenListExpr.
5567 unsigned NumExprs = Exprs.size();
5568 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5569 (Expr **)Exprs.release(),
5570 NumExprs, RParenLoc));
5571 return;
5572 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005573
5574 // Capture the variable that is being initialized and the style of
5575 // initialization.
5576 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5577
5578 // FIXME: Poor source location information.
5579 InitializationKind Kind
5580 = InitializationKind::CreateDirect(VDecl->getLocation(),
5581 LParenLoc, RParenLoc);
5582
5583 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005584 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005585 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005586 if (Result.isInvalid()) {
5587 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005588 return;
5589 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005590
John McCallb268a282010-08-23 23:25:46 +00005591 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregord5058122010-02-11 01:19:42 +00005592 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005593 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005594
John McCall8b0f4ff2010-08-02 21:13:48 +00005595 if (!VDecl->isInvalidDecl() &&
5596 !VDecl->getDeclContext()->isDependentContext() &&
5597 VDecl->hasGlobalStorage() &&
5598 !VDecl->getInit()->isConstantInitializer(Context,
5599 VDecl->getType()->isReferenceType()))
5600 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5601 << VDecl->getInit()->getSourceRange();
5602
John McCall03c48482010-02-02 09:10:11 +00005603 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5604 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005605}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005606
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005607/// \brief Given a constructor and the set of arguments provided for the
5608/// constructor, convert the arguments and add any required default arguments
5609/// to form a proper call to this constructor.
5610///
5611/// \returns true if an error occurred, false otherwise.
5612bool
5613Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5614 MultiExprArg ArgsPtr,
5615 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005616 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005617 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5618 unsigned NumArgs = ArgsPtr.size();
5619 Expr **Args = (Expr **)ArgsPtr.get();
5620
5621 const FunctionProtoType *Proto
5622 = Constructor->getType()->getAs<FunctionProtoType>();
5623 assert(Proto && "Constructor without a prototype?");
5624 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005625
5626 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005627 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005628 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005629 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005630 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005631
5632 VariadicCallType CallType =
5633 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5634 llvm::SmallVector<Expr *, 8> AllArgs;
5635 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5636 Proto, 0, Args, NumArgs, AllArgs,
5637 CallType);
5638 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5639 ConvertedArgs.push_back(AllArgs[i]);
5640 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005641}
5642
Anders Carlssone363c8e2009-12-12 00:32:00 +00005643static inline bool
5644CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5645 const FunctionDecl *FnDecl) {
5646 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
5647 if (isa<NamespaceDecl>(DC)) {
5648 return SemaRef.Diag(FnDecl->getLocation(),
5649 diag::err_operator_new_delete_declared_in_namespace)
5650 << FnDecl->getDeclName();
5651 }
5652
5653 if (isa<TranslationUnitDecl>(DC) &&
5654 FnDecl->getStorageClass() == FunctionDecl::Static) {
5655 return SemaRef.Diag(FnDecl->getLocation(),
5656 diag::err_operator_new_delete_declared_static)
5657 << FnDecl->getDeclName();
5658 }
5659
Anders Carlsson60659a82009-12-12 02:43:16 +00005660 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005661}
5662
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005663static inline bool
5664CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5665 CanQualType ExpectedResultType,
5666 CanQualType ExpectedFirstParamType,
5667 unsigned DependentParamTypeDiag,
5668 unsigned InvalidParamTypeDiag) {
5669 QualType ResultType =
5670 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5671
5672 // Check that the result type is not dependent.
5673 if (ResultType->isDependentType())
5674 return SemaRef.Diag(FnDecl->getLocation(),
5675 diag::err_operator_new_delete_dependent_result_type)
5676 << FnDecl->getDeclName() << ExpectedResultType;
5677
5678 // Check that the result type is what we expect.
5679 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5680 return SemaRef.Diag(FnDecl->getLocation(),
5681 diag::err_operator_new_delete_invalid_result_type)
5682 << FnDecl->getDeclName() << ExpectedResultType;
5683
5684 // A function template must have at least 2 parameters.
5685 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5686 return SemaRef.Diag(FnDecl->getLocation(),
5687 diag::err_operator_new_delete_template_too_few_parameters)
5688 << FnDecl->getDeclName();
5689
5690 // The function decl must have at least 1 parameter.
5691 if (FnDecl->getNumParams() == 0)
5692 return SemaRef.Diag(FnDecl->getLocation(),
5693 diag::err_operator_new_delete_too_few_parameters)
5694 << FnDecl->getDeclName();
5695
5696 // Check the the first parameter type is not dependent.
5697 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5698 if (FirstParamType->isDependentType())
5699 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5700 << FnDecl->getDeclName() << ExpectedFirstParamType;
5701
5702 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005703 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005704 ExpectedFirstParamType)
5705 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5706 << FnDecl->getDeclName() << ExpectedFirstParamType;
5707
5708 return false;
5709}
5710
Anders Carlsson12308f42009-12-11 23:23:22 +00005711static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005712CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005713 // C++ [basic.stc.dynamic.allocation]p1:
5714 // A program is ill-formed if an allocation function is declared in a
5715 // namespace scope other than global scope or declared static in global
5716 // scope.
5717 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5718 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005719
5720 CanQualType SizeTy =
5721 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5722
5723 // C++ [basic.stc.dynamic.allocation]p1:
5724 // The return type shall be void*. The first parameter shall have type
5725 // std::size_t.
5726 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5727 SizeTy,
5728 diag::err_operator_new_dependent_param_type,
5729 diag::err_operator_new_param_type))
5730 return true;
5731
5732 // C++ [basic.stc.dynamic.allocation]p1:
5733 // The first parameter shall not have an associated default argument.
5734 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005735 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005736 diag::err_operator_new_default_arg)
5737 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5738
5739 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005740}
5741
5742static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005743CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5744 // C++ [basic.stc.dynamic.deallocation]p1:
5745 // A program is ill-formed if deallocation functions are declared in a
5746 // namespace scope other than global scope or declared static in global
5747 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005748 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5749 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005750
5751 // C++ [basic.stc.dynamic.deallocation]p2:
5752 // Each deallocation function shall return void and its first parameter
5753 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005754 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5755 SemaRef.Context.VoidPtrTy,
5756 diag::err_operator_delete_dependent_param_type,
5757 diag::err_operator_delete_param_type))
5758 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005759
Anders Carlsson12308f42009-12-11 23:23:22 +00005760 return false;
5761}
5762
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005763/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5764/// of this overloaded operator is well-formed. If so, returns false;
5765/// otherwise, emits appropriate diagnostics and returns true.
5766bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005767 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005768 "Expected an overloaded operator declaration");
5769
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005770 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5771
Mike Stump11289f42009-09-09 15:08:12 +00005772 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005773 // The allocation and deallocation functions, operator new,
5774 // operator new[], operator delete and operator delete[], are
5775 // described completely in 3.7.3. The attributes and restrictions
5776 // found in the rest of this subclause do not apply to them unless
5777 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005778 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005779 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005780
Anders Carlsson22f443f2009-12-12 00:26:23 +00005781 if (Op == OO_New || Op == OO_Array_New)
5782 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005783
5784 // C++ [over.oper]p6:
5785 // An operator function shall either be a non-static member
5786 // function or be a non-member function and have at least one
5787 // parameter whose type is a class, a reference to a class, an
5788 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005789 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5790 if (MethodDecl->isStatic())
5791 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005792 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005793 } else {
5794 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005795 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5796 ParamEnd = FnDecl->param_end();
5797 Param != ParamEnd; ++Param) {
5798 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005799 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5800 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005801 ClassOrEnumParam = true;
5802 break;
5803 }
5804 }
5805
Douglas Gregord69246b2008-11-17 16:14:12 +00005806 if (!ClassOrEnumParam)
5807 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005808 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005809 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005810 }
5811
5812 // C++ [over.oper]p8:
5813 // An operator function cannot have default arguments (8.3.6),
5814 // except where explicitly stated below.
5815 //
Mike Stump11289f42009-09-09 15:08:12 +00005816 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005817 // (C++ [over.call]p1).
5818 if (Op != OO_Call) {
5819 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5820 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005821 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005822 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005823 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005824 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005825 }
5826 }
5827
Douglas Gregor6cf08062008-11-10 13:38:07 +00005828 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5829 { false, false, false }
5830#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5831 , { Unary, Binary, MemberOnly }
5832#include "clang/Basic/OperatorKinds.def"
5833 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005834
Douglas Gregor6cf08062008-11-10 13:38:07 +00005835 bool CanBeUnaryOperator = OperatorUses[Op][0];
5836 bool CanBeBinaryOperator = OperatorUses[Op][1];
5837 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005838
5839 // C++ [over.oper]p8:
5840 // [...] Operator functions cannot have more or fewer parameters
5841 // than the number required for the corresponding operator, as
5842 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005843 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005844 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005845 if (Op != OO_Call &&
5846 ((NumParams == 1 && !CanBeUnaryOperator) ||
5847 (NumParams == 2 && !CanBeBinaryOperator) ||
5848 (NumParams < 1) || (NumParams > 2))) {
5849 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005850 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005851 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005852 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005853 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005854 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005855 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005856 assert(CanBeBinaryOperator &&
5857 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005858 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005859 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005860
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005861 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005862 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005863 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005864
Douglas Gregord69246b2008-11-17 16:14:12 +00005865 // Overloaded operators other than operator() cannot be variadic.
5866 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005867 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005868 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005869 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005870 }
5871
5872 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005873 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5874 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005875 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005876 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005877 }
5878
5879 // C++ [over.inc]p1:
5880 // The user-defined function called operator++ implements the
5881 // prefix and postfix ++ operator. If this function is a member
5882 // function with no parameters, or a non-member function with one
5883 // parameter of class or enumeration type, it defines the prefix
5884 // increment operator ++ for objects of that type. If the function
5885 // is a member function with one parameter (which shall be of type
5886 // int) or a non-member function with two parameters (the second
5887 // of which shall be of type int), it defines the postfix
5888 // increment operator ++ for objects of that type.
5889 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5890 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5891 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005892 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005893 ParamIsInt = BT->getKind() == BuiltinType::Int;
5894
Chris Lattner2b786902008-11-21 07:50:02 +00005895 if (!ParamIsInt)
5896 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005897 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005898 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005899 }
5900
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005901 // Notify the class if it got an assignment operator.
5902 if (Op == OO_Equal) {
5903 // Would have returned earlier otherwise.
5904 assert(isa<CXXMethodDecl>(FnDecl) &&
5905 "Overloaded = not member, but not filtered.");
5906 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5907 Method->getParent()->addedAssignmentOperator(Context, Method);
5908 }
5909
Douglas Gregord69246b2008-11-17 16:14:12 +00005910 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005911}
Chris Lattner3b024a32008-12-17 07:09:26 +00005912
Alexis Huntc88db062010-01-13 09:01:02 +00005913/// CheckLiteralOperatorDeclaration - Check whether the declaration
5914/// of this literal operator function is well-formed. If so, returns
5915/// false; otherwise, emits appropriate diagnostics and returns true.
5916bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5917 DeclContext *DC = FnDecl->getDeclContext();
5918 Decl::Kind Kind = DC->getDeclKind();
5919 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5920 Kind != Decl::LinkageSpec) {
5921 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5922 << FnDecl->getDeclName();
5923 return true;
5924 }
5925
5926 bool Valid = false;
5927
Alexis Hunt7dd26172010-04-07 23:11:06 +00005928 // template <char...> type operator "" name() is the only valid template
5929 // signature, and the only valid signature with no parameters.
5930 if (FnDecl->param_size() == 0) {
5931 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5932 // Must have only one template parameter
5933 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5934 if (Params->size() == 1) {
5935 NonTypeTemplateParmDecl *PmDecl =
5936 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005937
Alexis Hunt7dd26172010-04-07 23:11:06 +00005938 // The template parameter must be a char parameter pack.
5939 // FIXME: This test will always fail because non-type parameter packs
5940 // have not been implemented.
5941 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5942 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5943 Valid = true;
5944 }
5945 }
5946 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005947 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005948 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5949
Alexis Huntc88db062010-01-13 09:01:02 +00005950 QualType T = (*Param)->getType();
5951
Alexis Hunt079a6f72010-04-07 22:57:35 +00005952 // unsigned long long int, long double, and any character type are allowed
5953 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005954 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5955 Context.hasSameType(T, Context.LongDoubleTy) ||
5956 Context.hasSameType(T, Context.CharTy) ||
5957 Context.hasSameType(T, Context.WCharTy) ||
5958 Context.hasSameType(T, Context.Char16Ty) ||
5959 Context.hasSameType(T, Context.Char32Ty)) {
5960 if (++Param == FnDecl->param_end())
5961 Valid = true;
5962 goto FinishedParams;
5963 }
5964
Alexis Hunt079a6f72010-04-07 22:57:35 +00005965 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005966 const PointerType *PT = T->getAs<PointerType>();
5967 if (!PT)
5968 goto FinishedParams;
5969 T = PT->getPointeeType();
5970 if (!T.isConstQualified())
5971 goto FinishedParams;
5972 T = T.getUnqualifiedType();
5973
5974 // Move on to the second parameter;
5975 ++Param;
5976
5977 // If there is no second parameter, the first must be a const char *
5978 if (Param == FnDecl->param_end()) {
5979 if (Context.hasSameType(T, Context.CharTy))
5980 Valid = true;
5981 goto FinishedParams;
5982 }
5983
5984 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5985 // are allowed as the first parameter to a two-parameter function
5986 if (!(Context.hasSameType(T, Context.CharTy) ||
5987 Context.hasSameType(T, Context.WCharTy) ||
5988 Context.hasSameType(T, Context.Char16Ty) ||
5989 Context.hasSameType(T, Context.Char32Ty)))
5990 goto FinishedParams;
5991
5992 // The second and final parameter must be an std::size_t
5993 T = (*Param)->getType().getUnqualifiedType();
5994 if (Context.hasSameType(T, Context.getSizeType()) &&
5995 ++Param == FnDecl->param_end())
5996 Valid = true;
5997 }
5998
5999 // FIXME: This diagnostic is absolutely terrible.
6000FinishedParams:
6001 if (!Valid) {
6002 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6003 << FnDecl->getDeclName();
6004 return true;
6005 }
6006
6007 return false;
6008}
6009
Douglas Gregor07665a62009-01-05 19:45:36 +00006010/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6011/// linkage specification, including the language and (if present)
6012/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6013/// the location of the language string literal, which is provided
6014/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6015/// the '{' brace. Otherwise, this linkage specification does not
6016/// have any braces.
John McCall48871652010-08-21 09:40:31 +00006017Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006018 SourceLocation ExternLoc,
6019 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00006020 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00006021 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006022 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006023 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006024 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006025 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006026 Language = LinkageSpecDecl::lang_cxx;
6027 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006028 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006029 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006030 }
Mike Stump11289f42009-09-09 15:08:12 +00006031
Chris Lattner438e5012008-12-17 07:13:27 +00006032 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006033
Douglas Gregor07665a62009-01-05 19:45:36 +00006034 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006035 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006036 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006037 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006038 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006039 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006040}
6041
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006042/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006043/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6044/// valid, it's the position of the closing '}' brace in a linkage
6045/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006046Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6047 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006048 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006049 if (LinkageSpec)
6050 PopDeclContext();
6051 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006052}
6053
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006054/// \brief Perform semantic analysis for the variable declaration that
6055/// occurs within a C++ catch clause, returning the newly-created
6056/// variable.
6057VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00006058 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006059 IdentifierInfo *Name,
6060 SourceLocation Loc,
6061 SourceRange Range) {
6062 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006063
6064 // Arrays and functions decay.
6065 if (ExDeclType->isArrayType())
6066 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6067 else if (ExDeclType->isFunctionType())
6068 ExDeclType = Context.getPointerType(ExDeclType);
6069
6070 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6071 // The exception-declaration shall not denote a pointer or reference to an
6072 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006073 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006074 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006075 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00006076 Invalid = true;
6077 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006078
Douglas Gregor104ee002010-03-08 01:47:36 +00006079 // GCC allows catching pointers and references to incomplete types
6080 // as an extension; so do we, but we warn by default.
6081
Sebastian Redl54c04d42008-12-22 19:15:10 +00006082 QualType BaseType = ExDeclType;
6083 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006084 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006085 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006086 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006087 BaseType = Ptr->getPointeeType();
6088 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006089 DK = diag::ext_catch_incomplete_ptr;
6090 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006091 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006092 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006093 BaseType = Ref->getPointeeType();
6094 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006095 DK = diag::ext_catch_incomplete_ref;
6096 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006097 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006098 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006099 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6100 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006101 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006102
Mike Stump11289f42009-09-09 15:08:12 +00006103 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006104 RequireNonAbstractType(Loc, ExDeclType,
6105 diag::err_abstract_type_in_decl,
6106 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006107 Invalid = true;
6108
John McCall2ca705e2010-07-24 00:37:23 +00006109 // Only the non-fragile NeXT runtime currently supports C++ catches
6110 // of ObjC types, and no runtime supports catching ObjC types by value.
6111 if (!Invalid && getLangOptions().ObjC1) {
6112 QualType T = ExDeclType;
6113 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6114 T = RT->getPointeeType();
6115
6116 if (T->isObjCObjectType()) {
6117 Diag(Loc, diag::err_objc_object_catch);
6118 Invalid = true;
6119 } else if (T->isObjCObjectPointerType()) {
6120 if (!getLangOptions().NeXTRuntime) {
6121 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6122 Invalid = true;
6123 } else if (!getLangOptions().ObjCNonFragileABI) {
6124 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6125 Invalid = true;
6126 }
6127 }
6128 }
6129
Mike Stump11289f42009-09-09 15:08:12 +00006130 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006131 Name, ExDeclType, TInfo, VarDecl::None,
6132 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006133 ExDecl->setExceptionVariable(true);
6134
Douglas Gregor6de584c2010-03-05 23:38:39 +00006135 if (!Invalid) {
6136 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6137 // C++ [except.handle]p16:
6138 // The object declared in an exception-declaration or, if the
6139 // exception-declaration does not specify a name, a temporary (12.2) is
6140 // copy-initialized (8.5) from the exception object. [...]
6141 // The object is destroyed when the handler exits, after the destruction
6142 // of any automatic objects initialized within the handler.
6143 //
6144 // We just pretend to initialize the object with itself, then make sure
6145 // it can be destroyed later.
6146 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6147 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6148 Loc, ExDeclType, 0);
6149 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6150 SourceLocation());
6151 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006152 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006153 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006154 if (Result.isInvalid())
6155 Invalid = true;
6156 else
6157 FinalizeVarWithDestructor(ExDecl, RecordTy);
6158 }
6159 }
6160
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006161 if (Invalid)
6162 ExDecl->setInvalidDecl();
6163
6164 return ExDecl;
6165}
6166
6167/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6168/// handler.
John McCall48871652010-08-21 09:40:31 +00006169Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006170 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6171 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006172
6173 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006174 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006175 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006176 LookupOrdinaryName,
6177 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006178 // The scope should be freshly made just for us. There is just no way
6179 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006180 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006181 if (PrevDecl->isTemplateParameter()) {
6182 // Maybe we will complain about the shadowed template parameter.
6183 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006184 }
6185 }
6186
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006187 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006188 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6189 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006190 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006191 }
6192
John McCallbcd03502009-12-07 02:54:59 +00006193 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006194 D.getIdentifier(),
6195 D.getIdentifierLoc(),
6196 D.getDeclSpec().getSourceRange());
6197
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006198 if (Invalid)
6199 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006200
Sebastian Redl54c04d42008-12-22 19:15:10 +00006201 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006202 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006203 PushOnScopeChains(ExDecl, S);
6204 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006205 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006206
Douglas Gregor758a8692009-06-17 21:51:59 +00006207 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006208 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006209}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006210
John McCall48871652010-08-21 09:40:31 +00006211Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006212 Expr *AssertExpr,
6213 Expr *AssertMessageExpr_) {
6214 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006215
Anders Carlsson54b26982009-03-14 00:33:21 +00006216 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6217 llvm::APSInt Value(32);
6218 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6219 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6220 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006221 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006222 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006223
Anders Carlsson54b26982009-03-14 00:33:21 +00006224 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006225 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006226 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006227 }
6228 }
Mike Stump11289f42009-09-09 15:08:12 +00006229
Mike Stump11289f42009-09-09 15:08:12 +00006230 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006231 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006232
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006233 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006234 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006235}
Sebastian Redlf769df52009-03-24 22:27:57 +00006236
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006237/// \brief Perform semantic analysis of the given friend type declaration.
6238///
6239/// \returns A friend declaration that.
6240FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6241 TypeSourceInfo *TSInfo) {
6242 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6243
6244 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006245 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006246
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006247 if (!getLangOptions().CPlusPlus0x) {
6248 // C++03 [class.friend]p2:
6249 // An elaborated-type-specifier shall be used in a friend declaration
6250 // for a class.*
6251 //
6252 // * The class-key of the elaborated-type-specifier is required.
6253 if (!ActiveTemplateInstantiations.empty()) {
6254 // Do not complain about the form of friend template types during
6255 // template instantiation; we will already have complained when the
6256 // template was declared.
6257 } else if (!T->isElaboratedTypeSpecifier()) {
6258 // If we evaluated the type to a record type, suggest putting
6259 // a tag in front.
6260 if (const RecordType *RT = T->getAs<RecordType>()) {
6261 RecordDecl *RD = RT->getDecl();
6262
6263 std::string InsertionText = std::string(" ") + RD->getKindName();
6264
6265 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6266 << (unsigned) RD->getTagKind()
6267 << T
6268 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6269 InsertionText);
6270 } else {
6271 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6272 << T
6273 << SourceRange(FriendLoc, TypeRange.getEnd());
6274 }
6275 } else if (T->getAs<EnumType>()) {
6276 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006277 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006278 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006279 }
6280 }
6281
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006282 // C++0x [class.friend]p3:
6283 // If the type specifier in a friend declaration designates a (possibly
6284 // cv-qualified) class type, that class is declared as a friend; otherwise,
6285 // the friend declaration is ignored.
6286
6287 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6288 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006289
6290 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6291}
6292
John McCall11083da2009-09-16 22:47:08 +00006293/// Handle a friend type declaration. This works in tandem with
6294/// ActOnTag.
6295///
6296/// Notes on friend class templates:
6297///
6298/// We generally treat friend class declarations as if they were
6299/// declaring a class. So, for example, the elaborated type specifier
6300/// in a friend declaration is required to obey the restrictions of a
6301/// class-head (i.e. no typedefs in the scope chain), template
6302/// parameters are required to match up with simple template-ids, &c.
6303/// However, unlike when declaring a template specialization, it's
6304/// okay to refer to a template specialization without an empty
6305/// template parameter declaration, e.g.
6306/// friend class A<T>::B<unsigned>;
6307/// We permit this as a special case; if there are any template
6308/// parameters present at all, require proper matching, i.e.
6309/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006310Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00006311 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006312 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006313
6314 assert(DS.isFriendSpecified());
6315 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6316
John McCall11083da2009-09-16 22:47:08 +00006317 // Try to convert the decl specifier to a type. This works for
6318 // friend templates because ActOnTag never produces a ClassTemplateDecl
6319 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006320 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006321 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6322 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006323 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006324 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006325
John McCall11083da2009-09-16 22:47:08 +00006326 // This is definitely an error in C++98. It's probably meant to
6327 // be forbidden in C++0x, too, but the specification is just
6328 // poorly written.
6329 //
6330 // The problem is with declarations like the following:
6331 // template <T> friend A<T>::foo;
6332 // where deciding whether a class C is a friend or not now hinges
6333 // on whether there exists an instantiation of A that causes
6334 // 'foo' to equal C. There are restrictions on class-heads
6335 // (which we declare (by fiat) elaborated friend declarations to
6336 // be) that makes this tractable.
6337 //
6338 // FIXME: handle "template <> friend class A<T>;", which
6339 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006340 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006341 Diag(Loc, diag::err_tagless_friend_type_template)
6342 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006343 return 0;
John McCall11083da2009-09-16 22:47:08 +00006344 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006345
John McCallaa74a0c2009-08-28 07:59:38 +00006346 // C++98 [class.friend]p1: A friend of a class is a function
6347 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006348 // This is fixed in DR77, which just barely didn't make the C++03
6349 // deadline. It's also a very silly restriction that seriously
6350 // affects inner classes and which nobody else seems to implement;
6351 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006352 //
6353 // But note that we could warn about it: it's always useless to
6354 // friend one of your own members (it's not, however, worthless to
6355 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006356
John McCall11083da2009-09-16 22:47:08 +00006357 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006358 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006359 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006360 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00006361 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006362 TSI,
John McCall11083da2009-09-16 22:47:08 +00006363 DS.getFriendSpecLoc());
6364 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006365 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6366
6367 if (!D)
John McCall48871652010-08-21 09:40:31 +00006368 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006369
John McCall11083da2009-09-16 22:47:08 +00006370 D->setAccess(AS_public);
6371 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006372
John McCall48871652010-08-21 09:40:31 +00006373 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006374}
6375
John McCall48871652010-08-21 09:40:31 +00006376Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6377 Declarator &D,
6378 bool IsDefinition,
John McCall2f212b32009-09-11 21:02:39 +00006379 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006380 const DeclSpec &DS = D.getDeclSpec();
6381
6382 assert(DS.isFriendSpecified());
6383 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6384
6385 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006386 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6387 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006388
6389 // C++ [class.friend]p1
6390 // A friend of a class is a function or class....
6391 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006392 // It *doesn't* see through dependent types, which is correct
6393 // according to [temp.arg.type]p3:
6394 // If a declaration acquires a function type through a
6395 // type dependent on a template-parameter and this causes
6396 // a declaration that does not use the syntactic form of a
6397 // function declarator to have a function type, the program
6398 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006399 if (!T->isFunctionType()) {
6400 Diag(Loc, diag::err_unexpected_friend);
6401
6402 // It might be worthwhile to try to recover by creating an
6403 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006404 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006405 }
6406
6407 // C++ [namespace.memdef]p3
6408 // - If a friend declaration in a non-local class first declares a
6409 // class or function, the friend class or function is a member
6410 // of the innermost enclosing namespace.
6411 // - The name of the friend is not found by simple name lookup
6412 // until a matching declaration is provided in that namespace
6413 // scope (either before or after the class declaration granting
6414 // friendship).
6415 // - If a friend function is called, its name may be found by the
6416 // name lookup that considers functions from namespaces and
6417 // classes associated with the types of the function arguments.
6418 // - When looking for a prior declaration of a class or a function
6419 // declared as a friend, scopes outside the innermost enclosing
6420 // namespace scope are not considered.
6421
John McCallaa74a0c2009-08-28 07:59:38 +00006422 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006423 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6424 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006425 assert(Name);
6426
John McCall07e91c02009-08-06 02:15:43 +00006427 // The context we found the declaration in, or in which we should
6428 // create the declaration.
6429 DeclContext *DC;
6430
6431 // FIXME: handle local classes
6432
6433 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006434 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006435 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006436 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6437 DC = computeDeclContext(ScopeQual);
6438
6439 // FIXME: handle dependent contexts
John McCall48871652010-08-21 09:40:31 +00006440 if (!DC) return 0;
6441 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall07e91c02009-08-06 02:15:43 +00006442
John McCall1f82f242009-11-18 22:49:29 +00006443 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006444
John McCall45831862010-05-28 01:41:47 +00006445 // Ignore things found implicitly in the wrong scope.
John McCall07e91c02009-08-06 02:15:43 +00006446 // TODO: better diagnostics for this case. Suggesting the right
6447 // qualified scope would be nice...
John McCall45831862010-05-28 01:41:47 +00006448 LookupResult::Filter F = Previous.makeFilter();
6449 while (F.hasNext()) {
6450 NamedDecl *D = F.next();
6451 if (!D->getDeclContext()->getLookupContext()->Equals(DC))
6452 F.erase();
6453 }
6454 F.done();
6455
6456 if (Previous.empty()) {
John McCallaa74a0c2009-08-28 07:59:38 +00006457 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00006458 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCall48871652010-08-21 09:40:31 +00006459 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006460 }
6461
6462 // C++ [class.friend]p1: A friend of a class is a function or
6463 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006464 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00006465 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6466
John McCall07e91c02009-08-06 02:15:43 +00006467 // Otherwise walk out to the nearest namespace scope looking for matches.
6468 } else {
6469 // TODO: handle local class contexts.
6470
6471 DC = CurContext;
6472 while (true) {
6473 // Skip class contexts. If someone can cite chapter and verse
6474 // for this behavior, that would be nice --- it's what GCC and
6475 // EDG do, and it seems like a reasonable intent, but the spec
6476 // really only says that checks for unqualified existing
6477 // declarations should stop at the nearest enclosing namespace,
6478 // not that they should only consider the nearest enclosing
6479 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006480 while (DC->isRecord())
6481 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006482
John McCall1f82f242009-11-18 22:49:29 +00006483 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006484
6485 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00006486 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006487 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006488
John McCall07e91c02009-08-06 02:15:43 +00006489 if (DC->isFileContext()) break;
6490 DC = DC->getParent();
6491 }
6492
6493 // C++ [class.friend]p1: A friend of a class is a function or
6494 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006495 // C++0x changes this for both friend types and functions.
6496 // Most C++ 98 compilers do seem to give an error here, so
6497 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006498 if (!Previous.empty() && DC->Equals(CurContext)
6499 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006500 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6501 }
6502
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006503 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00006504 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006505 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6506 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6507 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006508 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006509 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6510 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006511 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006512 }
John McCall07e91c02009-08-06 02:15:43 +00006513 }
6514
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006515 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00006516 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006517 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006518 IsDefinition,
6519 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006520 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006521
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006522 assert(ND->getDeclContext() == DC);
6523 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006524
John McCall759e32b2009-08-31 22:39:49 +00006525 // Add the function declaration to the appropriate lookup tables,
6526 // adjusting the redeclarations list as necessary. We don't
6527 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006528 //
John McCall759e32b2009-08-31 22:39:49 +00006529 // Also update the scope-based lookup if the target context's
6530 // lookup context is in lexical scope.
6531 if (!CurContext->isDependentContext()) {
6532 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006533 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006534 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006535 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006536 }
John McCallaa74a0c2009-08-28 07:59:38 +00006537
6538 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006539 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006540 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006541 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006542 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006543
John McCall48871652010-08-21 09:40:31 +00006544 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006545}
6546
John McCall48871652010-08-21 09:40:31 +00006547void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6548 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006549
Sebastian Redlf769df52009-03-24 22:27:57 +00006550 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6551 if (!Fn) {
6552 Diag(DelLoc, diag::err_deleted_non_function);
6553 return;
6554 }
6555 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6556 Diag(DelLoc, diag::err_deleted_decl_not_first);
6557 Diag(Prev->getLocation(), diag::note_previous_declaration);
6558 // If the declaration wasn't the first, we delete the function anyway for
6559 // recovery.
6560 }
6561 Fn->setDeleted();
6562}
Sebastian Redl4c018662009-04-27 21:33:24 +00006563
6564static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6565 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6566 ++CI) {
6567 Stmt *SubStmt = *CI;
6568 if (!SubStmt)
6569 continue;
6570 if (isa<ReturnStmt>(SubStmt))
6571 Self.Diag(SubStmt->getSourceRange().getBegin(),
6572 diag::err_return_in_constructor_handler);
6573 if (!isa<Expr>(SubStmt))
6574 SearchForReturnInStmt(Self, SubStmt);
6575 }
6576}
6577
6578void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6579 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6580 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6581 SearchForReturnInStmt(*this, Handler);
6582 }
6583}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006584
Mike Stump11289f42009-09-09 15:08:12 +00006585bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006586 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006587 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6588 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006589
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006590 if (Context.hasSameType(NewTy, OldTy) ||
6591 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006592 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006593
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006594 // Check if the return types are covariant
6595 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006596
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006597 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006598 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6599 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006600 NewClassTy = NewPT->getPointeeType();
6601 OldClassTy = OldPT->getPointeeType();
6602 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006603 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6604 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6605 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6606 NewClassTy = NewRT->getPointeeType();
6607 OldClassTy = OldRT->getPointeeType();
6608 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006609 }
6610 }
Mike Stump11289f42009-09-09 15:08:12 +00006611
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006612 // The return types aren't either both pointers or references to a class type.
6613 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006614 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006615 diag::err_different_return_type_for_overriding_virtual_function)
6616 << New->getDeclName() << NewTy << OldTy;
6617 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006618
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006619 return true;
6620 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006621
Anders Carlssone60365b2009-12-31 18:34:24 +00006622 // C++ [class.virtual]p6:
6623 // If the return type of D::f differs from the return type of B::f, the
6624 // class type in the return type of D::f shall be complete at the point of
6625 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006626 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6627 if (!RT->isBeingDefined() &&
6628 RequireCompleteType(New->getLocation(), NewClassTy,
6629 PDiag(diag::err_covariant_return_incomplete)
6630 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006631 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006632 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006633
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006634 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006635 // Check if the new class derives from the old class.
6636 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6637 Diag(New->getLocation(),
6638 diag::err_covariant_return_not_derived)
6639 << New->getDeclName() << NewTy << OldTy;
6640 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6641 return true;
6642 }
Mike Stump11289f42009-09-09 15:08:12 +00006643
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006644 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006645 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006646 diag::err_covariant_return_inaccessible_base,
6647 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6648 // FIXME: Should this point to the return type?
6649 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006650 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6651 return true;
6652 }
6653 }
Mike Stump11289f42009-09-09 15:08:12 +00006654
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006655 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006656 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006657 Diag(New->getLocation(),
6658 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006659 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006660 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6661 return true;
6662 };
Mike Stump11289f42009-09-09 15:08:12 +00006663
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006664
6665 // The new class type must have the same or less qualifiers as the old type.
6666 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6667 Diag(New->getLocation(),
6668 diag::err_covariant_return_type_class_type_more_qualified)
6669 << New->getDeclName() << NewTy << OldTy;
6670 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6671 return true;
6672 };
Mike Stump11289f42009-09-09 15:08:12 +00006673
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006674 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006675}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006676
Alexis Hunt96d5c762009-11-21 08:43:09 +00006677bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6678 const CXXMethodDecl *Old)
6679{
6680 if (Old->hasAttr<FinalAttr>()) {
6681 Diag(New->getLocation(), diag::err_final_function_overridden)
6682 << New->getDeclName();
6683 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6684 return true;
6685 }
6686
6687 return false;
6688}
6689
Douglas Gregor21920e372009-12-01 17:24:26 +00006690/// \brief Mark the given method pure.
6691///
6692/// \param Method the method to be marked pure.
6693///
6694/// \param InitRange the source range that covers the "0" initializer.
6695bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6696 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6697 Method->setPure();
6698
6699 // A class is abstract if at least one function is pure virtual.
6700 Method->getParent()->setAbstract(true);
6701 return false;
6702 }
6703
6704 if (!Method->isInvalidDecl())
6705 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6706 << Method->getDeclName() << InitRange;
6707 return true;
6708}
6709
John McCall1f4ee7b2009-12-19 09:28:58 +00006710/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6711/// an initializer for the out-of-line declaration 'Dcl'. The scope
6712/// is a fresh scope pushed for just this purpose.
6713///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006714/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6715/// static data member of class X, names should be looked up in the scope of
6716/// class X.
John McCall48871652010-08-21 09:40:31 +00006717void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006718 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006719 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006720
John McCall1f4ee7b2009-12-19 09:28:58 +00006721 // We should only get called for declarations with scope specifiers, like:
6722 // int foo::bar;
6723 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006724 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006725}
6726
6727/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006728/// initializer for the out-of-line declaration 'D'.
6729void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006730 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006731 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006732
John McCall1f4ee7b2009-12-19 09:28:58 +00006733 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006734 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006735}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006736
6737/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6738/// C++ if/switch/while/for statement.
6739/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006740DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006741 // C++ 6.4p2:
6742 // The declarator shall not specify a function or an array.
6743 // The type-specifier-seq shall not contain typedef and shall not declare a
6744 // new class or enumeration.
6745 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6746 "Parser allowed 'typedef' as storage class of condition decl.");
6747
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006748 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006749 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6750 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006751
6752 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6753 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6754 // would be created and CXXConditionDeclExpr wants a VarDecl.
6755 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6756 << D.getSourceRange();
6757 return DeclResult();
6758 } else if (OwnedTag && OwnedTag->isDefinition()) {
6759 // The type-specifier-seq shall not declare a new class or enumeration.
6760 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6761 }
6762
John McCall48871652010-08-21 09:40:31 +00006763 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006764 if (!Dcl)
6765 return DeclResult();
6766
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006767 return Dcl;
6768}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006769
Douglas Gregor88d292c2010-05-13 16:44:06 +00006770void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6771 bool DefinitionRequired) {
6772 // Ignore any vtable uses in unevaluated operands or for classes that do
6773 // not have a vtable.
6774 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6775 CurContext->isDependentContext() ||
6776 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006777 return;
6778
Douglas Gregor88d292c2010-05-13 16:44:06 +00006779 // Try to insert this class into the map.
6780 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6781 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6782 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6783 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006784 // If we already had an entry, check to see if we are promoting this vtable
6785 // to required a definition. If so, we need to reappend to the VTableUses
6786 // list, since we may have already processed the first entry.
6787 if (DefinitionRequired && !Pos.first->second) {
6788 Pos.first->second = true;
6789 } else {
6790 // Otherwise, we can early exit.
6791 return;
6792 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006793 }
6794
6795 // Local classes need to have their virtual members marked
6796 // immediately. For all other classes, we mark their virtual members
6797 // at the end of the translation unit.
6798 if (Class->isLocalClass())
6799 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006800 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006801 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006802}
6803
Douglas Gregor88d292c2010-05-13 16:44:06 +00006804bool Sema::DefineUsedVTables() {
6805 // If any dynamic classes have their key function defined within
6806 // this translation unit, then those vtables are considered "used" and must
6807 // be emitted.
6808 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6809 if (const CXXMethodDecl *KeyFunction
6810 = Context.getKeyFunction(DynamicClasses[I])) {
6811 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006812 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006813 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6814 }
6815 }
6816
6817 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006818 return false;
6819
Douglas Gregor88d292c2010-05-13 16:44:06 +00006820 // Note: The VTableUses vector could grow as a result of marking
6821 // the members of a class as "used", so we check the size each
6822 // time through the loop and prefer indices (with are stable) to
6823 // iterators (which are not).
6824 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006825 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006826 if (!Class)
6827 continue;
6828
6829 SourceLocation Loc = VTableUses[I].second;
6830
6831 // If this class has a key function, but that key function is
6832 // defined in another translation unit, we don't need to emit the
6833 // vtable even though we're using it.
6834 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006835 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006836 switch (KeyFunction->getTemplateSpecializationKind()) {
6837 case TSK_Undeclared:
6838 case TSK_ExplicitSpecialization:
6839 case TSK_ExplicitInstantiationDeclaration:
6840 // The key function is in another translation unit.
6841 continue;
6842
6843 case TSK_ExplicitInstantiationDefinition:
6844 case TSK_ImplicitInstantiation:
6845 // We will be instantiating the key function.
6846 break;
6847 }
6848 } else if (!KeyFunction) {
6849 // If we have a class with no key function that is the subject
6850 // of an explicit instantiation declaration, suppress the
6851 // vtable; it will live with the explicit instantiation
6852 // definition.
6853 bool IsExplicitInstantiationDeclaration
6854 = Class->getTemplateSpecializationKind()
6855 == TSK_ExplicitInstantiationDeclaration;
6856 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6857 REnd = Class->redecls_end();
6858 R != REnd; ++R) {
6859 TemplateSpecializationKind TSK
6860 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6861 if (TSK == TSK_ExplicitInstantiationDeclaration)
6862 IsExplicitInstantiationDeclaration = true;
6863 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6864 IsExplicitInstantiationDeclaration = false;
6865 break;
6866 }
6867 }
6868
6869 if (IsExplicitInstantiationDeclaration)
6870 continue;
6871 }
6872
6873 // Mark all of the virtual members of this class as referenced, so
6874 // that we can build a vtable. Then, tell the AST consumer that a
6875 // vtable for this class is required.
6876 MarkVirtualMembersReferenced(Loc, Class);
6877 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6878 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6879
6880 // Optionally warn if we're emitting a weak vtable.
6881 if (Class->getLinkage() == ExternalLinkage &&
6882 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006883 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006884 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6885 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006886 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006887 VTableUses.clear();
6888
Anders Carlsson82fccd02009-12-07 08:24:59 +00006889 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006890}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006891
Rafael Espindola5b334082010-03-26 00:36:59 +00006892void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6893 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006894 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6895 e = RD->method_end(); i != e; ++i) {
6896 CXXMethodDecl *MD = *i;
6897
6898 // C++ [basic.def.odr]p2:
6899 // [...] A virtual member function is used if it is not pure. [...]
6900 if (MD->isVirtual() && !MD->isPure())
6901 MarkDeclarationReferenced(Loc, MD);
6902 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006903
6904 // Only classes that have virtual bases need a VTT.
6905 if (RD->getNumVBases() == 0)
6906 return;
6907
6908 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6909 e = RD->bases_end(); i != e; ++i) {
6910 const CXXRecordDecl *Base =
6911 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00006912 if (Base->getNumVBases() == 0)
6913 continue;
6914 MarkVirtualMembersReferenced(Loc, Base);
6915 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006916}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006917
6918/// SetIvarInitializers - This routine builds initialization ASTs for the
6919/// Objective-C implementation whose ivars need be initialized.
6920void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6921 if (!getLangOptions().CPlusPlus)
6922 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00006923 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006924 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6925 CollectIvarsToConstructOrDestruct(OID, ivars);
6926 if (ivars.empty())
6927 return;
6928 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6929 for (unsigned i = 0; i < ivars.size(); i++) {
6930 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00006931 if (Field->isInvalidDecl())
6932 continue;
6933
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006934 CXXBaseOrMemberInitializer *Member;
6935 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6936 InitializationKind InitKind =
6937 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6938
6939 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00006940 ExprResult MemberInit =
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006941 InitSeq.Perform(*this, InitEntity, InitKind,
6942 Sema::MultiExprArg(*this, 0, 0));
John McCallb268a282010-08-23 23:25:46 +00006943 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006944 // Note, MemberInit could actually come back empty if no initialization
6945 // is required (e.g., because it would call a trivial default constructor)
6946 if (!MemberInit.get() || MemberInit.isInvalid())
6947 continue;
6948
6949 Member =
6950 new (Context) CXXBaseOrMemberInitializer(Context,
6951 Field, SourceLocation(),
6952 SourceLocation(),
6953 MemberInit.takeAs<Expr>(),
6954 SourceLocation());
6955 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00006956
6957 // Be sure that the destructor is accessible and is marked as referenced.
6958 if (const RecordType *RecordTy
6959 = Context.getBaseElementType(Field->getType())
6960 ->getAs<RecordType>()) {
6961 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00006962 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00006963 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6964 CheckDestructorAccess(Field->getLocation(), Destructor,
6965 PDiag(diag::err_access_dtor_ivar)
6966 << Context.getBaseElementType(Field->getType()));
6967 }
6968 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006969 }
6970 ObjCImplementation->setIvarInitializers(Context,
6971 AllToInit.data(), AllToInit.size());
6972 }
6973}