blob: c9757d728a64427c1f2edb47636c5ff6433f8bc0 [file] [log] [blame]
Chris Lattner3d1cee32008-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
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000273 // FIXME: If the parameter doesn't have an identifier then the location
274 // points to the '=' which means that the fixit hint won't remove any
275 // extra spaces between the type and the '='.
276 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000277 if (NewParam->getIdentifier())
278 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000279
Mike Stump1eb44332009-09-09 15:08:12 +0000280 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000282 << NewParam->getDefaultArgRange()
283 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
284 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-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 Gregor096ebfd2009-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 Gregor8c638ab2009-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 Gregor096ebfd2009-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 Gregor6cc15182009-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 Lattner3d1cee32008-04-08 05:04:30 +0000356 }
357 }
358
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000359 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000363
Douglas Gregorcda9c672009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 else
Mike Stump1eb44332009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
434 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000448 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000449 SourceLocation BaseLoc) {
450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460 Class->getTagKind() == RecordDecl::TK_class,
461 Access, BaseType);
462
463 // Base specifiers must be record types.
464 if (!BaseType->isRecordType()) {
465 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466 return 0;
467 }
468
469 // C++ [class.union]p1:
470 // A union shall not be used as a base class.
471 if (BaseType->isUnionType()) {
472 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473 return 0;
474 }
475
476 // C++ [class.derived]p2:
477 // The class-name in a base-specifier shall not be an incompletely
478 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000479 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000480 PDiag(diag::err_incomplete_base_class)
481 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 return 0;
483
Eli Friedman1d954f62009-08-15 21:55:26 +0000484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 assert(BaseDecl && "Record type has no declaration");
487 BaseDecl = BaseDecl->getDefinition(Context);
488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000489 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000491
Sean Huntbbd37c62009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000497 return 0;
498 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499
Eli Friedmand0137332009-12-05 23:03:49 +0000500 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000501
502 // Create the base specifier.
503 // FIXME: Allocate via ASTContext?
504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505 Class->getTagKind() == RecordDecl::TK_class,
506 Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510 const CXXRecordDecl *BaseClass,
511 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000512 // A class with a non-empty base class is not empty.
513 // FIXME: Standard ref?
514 if (!BaseClass->isEmpty())
515 Class->setEmpty(false);
516
517 // C++ [class.virtual]p1:
518 // A class that [...] inherits a virtual function is called a polymorphic
519 // class.
520 if (BaseClass->isPolymorphic())
521 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000522
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is [...] a class with [...] no base classes [...].
525 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000526
527 // C++ [class]p4:
528 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 Class->setPOD(false);
530
Anders Carlsson51f94042009-12-03 17:49:57 +0000531 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000532 // C++ [class.ctor]p5:
533 // A constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000535
536 // C++ [class.copy]p6:
537 // A copy constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialCopyConstructor(false);
539
540 // C++ [class.copy]p11:
541 // A copy assignment operator is trivial if its class has no virtual
542 // base classes.
543 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000544
545 // C++0x [meta.unary.prop] is_empty:
546 // T is a class type, but not a union type, with ... no virtual base
547 // classes
548 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000549 } else {
550 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000551 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000553 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000554 Class->setHasTrivialConstructor(false);
555
556 // C++ [class.copy]p6:
557 // A copy constructor is trivial if all the direct base classes of its
558 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialCopyConstructor(false);
561
562 // C++ [class.copy]p11:
563 // A copy assignment operator is trivial if all the direct base classes
564 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000567 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000568
569 // C++ [class.ctor]p3:
570 // A destructor is trivial if all the direct base classes of its class
571 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000572 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000573 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574}
575
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000578/// example:
579/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000580/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000581Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 bool Virtual, AccessSpecifier Access,
584 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000585 if (!classdecl)
586 return true;
587
Douglas Gregor40808ce2009-03-09 23:48:35 +0000588 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000590 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
592 Virtual, Access,
593 BaseType, BaseLoc))
594 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000597}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599/// \brief Performs the actual work of attaching the given base class
600/// specifiers to a C++ class.
601bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
602 unsigned NumBases) {
603 if (NumBases == 0)
604 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605
606 // Used to keep track of which base types we have already seen, so
607 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608 // that the key is always the unqualified canonical type of the base
609 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
611
612 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000616 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000618 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 if (KnownBaseTypes[NewBaseType]) {
621 // C++ [class.mi]p3:
622 // A class shall not be specified as a direct base class of a
623 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000625 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000626 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the duplicate base class specifier; we're going to
630 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000631 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632
633 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000634 } else {
635 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 KnownBaseTypes[NewBaseType] = Bases[idx];
637 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 }
639 }
640
641 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000642 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the remaining (good) base class specifiers, since their
645 // data has been copied into the CXXRecordDecl.
646 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000647 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648
649 return Invalid;
650}
651
652/// ActOnBaseSpecifiers - Attach the given base specifiers to the
653/// class, after checking whether there are any duplicate base
654/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000655void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000656 unsigned NumBases) {
657 if (!ClassDecl || !Bases || !NumBases)
658 return;
659
660 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000661 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000664
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665/// \brief Determine whether the type \p Derived is a C++ class that is
666/// derived from the type \p Base.
667bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
668 if (!getLangOptions().CPlusPlus)
669 return false;
670
671 const RecordType *DerivedRT = Derived->getAs<RecordType>();
672 if (!DerivedRT)
673 return false;
674
675 const RecordType *BaseRT = Base->getAs<RecordType>();
676 if (!BaseRT)
677 return false;
678
679 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
680 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
681 return DerivedRD->isDerivedFrom(BaseRD);
682}
683
684/// \brief Determine whether the type \p Derived is a C++ class that is
685/// derived from the type \p Base.
686bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
687 if (!getLangOptions().CPlusPlus)
688 return false;
689
690 const RecordType *DerivedRT = Derived->getAs<RecordType>();
691 if (!DerivedRT)
692 return false;
693
694 const RecordType *BaseRT = Base->getAs<RecordType>();
695 if (!BaseRT)
696 return false;
697
698 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
699 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
700 return DerivedRD->isDerivedFrom(BaseRD, Paths);
701}
702
703/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
704/// conversion (where Derived and Base are class types) is
705/// well-formed, meaning that the conversion is unambiguous (and
706/// that all of the base classes are accessible). Returns true
707/// and emits a diagnostic if the code is ill-formed, returns false
708/// otherwise. Loc is the location where this routine should point to
709/// if there is an error, and Range is the source range to highlight
710/// if there is an error.
711bool
712Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
713 unsigned InaccessibleBaseID,
714 unsigned AmbigiousBaseConvID,
715 SourceLocation Loc, SourceRange Range,
716 DeclarationName Name) {
717 // First, determine whether the path from Derived to Base is
718 // ambiguous. This is slightly more expensive than checking whether
719 // the Derived to Base conversion exists, because here we need to
720 // explore multiple paths to determine if there is an ambiguity.
721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
722 /*DetectVirtual=*/false);
723 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
724 assert(DerivationOkay &&
725 "Can only be used with a derived-to-base conversion");
726 (void)DerivationOkay;
727
728 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000729 if (InaccessibleBaseID == 0)
730 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000731 // Check that the base class can be accessed.
732 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
733 Name);
734 }
735
736 // We know that the derived-to-base conversion is ambiguous, and
737 // we're going to produce a diagnostic. Perform the derived-to-base
738 // search just one more time to compute all of the possible paths so
739 // that we can print them out. This is more expensive than any of
740 // the previous derived-to-base checks we've done, but at this point
741 // performance isn't as much of an issue.
742 Paths.clear();
743 Paths.setRecordingPaths(true);
744 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
745 assert(StillOkay && "Can only be used with a derived-to-base conversion");
746 (void)StillOkay;
747
748 // Build up a textual representation of the ambiguous paths, e.g.,
749 // D -> B -> A, that will be used to illustrate the ambiguous
750 // conversions in the diagnostic. We only print one of the paths
751 // to each base class subobject.
752 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
753
754 Diag(Loc, AmbigiousBaseConvID)
755 << Derived << Base << PathDisplayStr << Range << Name;
756 return true;
757}
758
759bool
760Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000761 SourceLocation Loc, SourceRange Range,
762 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000763 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000764 IgnoreAccess ? 0 :
765 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000766 diag::err_ambiguous_derived_to_base_conv,
767 Loc, Range, DeclarationName());
768}
769
770
771/// @brief Builds a string representing ambiguous paths from a
772/// specific derived class to different subobjects of the same base
773/// class.
774///
775/// This function builds a string that can be used in error messages
776/// to show the different paths that one can take through the
777/// inheritance hierarchy to go from the derived class to different
778/// subobjects of a base class. The result looks something like this:
779/// @code
780/// struct D -> struct B -> struct A
781/// struct D -> struct C -> struct A
782/// @endcode
783std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
784 std::string PathDisplayStr;
785 std::set<unsigned> DisplayedPaths;
786 for (CXXBasePaths::paths_iterator Path = Paths.begin();
787 Path != Paths.end(); ++Path) {
788 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
789 // We haven't displayed a path to this particular base
790 // class subobject yet.
791 PathDisplayStr += "\n ";
792 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
793 for (CXXBasePath::const_iterator Element = Path->begin();
794 Element != Path->end(); ++Element)
795 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
796 }
797 }
798
799 return PathDisplayStr;
800}
801
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000802//===----------------------------------------------------------------------===//
803// C++ class member Handling
804//===----------------------------------------------------------------------===//
805
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000806/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
807/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
808/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000809/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000810Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000812 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000813 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
814 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000815 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000816 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000817 Expr *BitWidth = static_cast<Expr*>(BW);
818 Expr *Init = static_cast<Expr*>(InitExpr);
819 SourceLocation Loc = D.getIdentifierLoc();
820
Sebastian Redl669d5d72008-11-14 23:42:31 +0000821 bool isFunc = D.isFunctionDeclarator();
822
John McCall67d1a672009-08-06 02:15:43 +0000823 assert(!DS.isFriendSpecified());
824
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000825 // C++ 9.2p6: A member shall not be declared to have automatic storage
826 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000827 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
828 // data members and cannot be applied to names declared const or static,
829 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000830 switch (DS.getStorageClassSpec()) {
831 case DeclSpec::SCS_unspecified:
832 case DeclSpec::SCS_typedef:
833 case DeclSpec::SCS_static:
834 // FALL THROUGH.
835 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000836 case DeclSpec::SCS_mutable:
837 if (isFunc) {
838 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000839 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000840 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000841 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Sebastian Redla11f42f2008-11-17 23:24:37 +0000843 // FIXME: It would be nicer if the keyword was ignored only for this
844 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000845 D.getMutableDeclSpec().ClearStorageClassSpecs();
846 } else {
847 QualType T = GetTypeForDeclarator(D, S);
848 diag::kind err = static_cast<diag::kind>(0);
849 if (T->isReferenceType())
850 err = diag::err_mutable_reference;
851 else if (T.isConstQualified())
852 err = diag::err_mutable_const;
853 if (err != 0) {
854 if (DS.getStorageClassSpecLoc().isValid())
855 Diag(DS.getStorageClassSpecLoc(), err);
856 else
857 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000858 // FIXME: It would be nicer if the keyword was ignored only for this
859 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000860 D.getMutableDeclSpec().ClearStorageClassSpecs();
861 }
862 }
863 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864 default:
865 if (DS.getStorageClassSpecLoc().isValid())
866 Diag(DS.getStorageClassSpecLoc(),
867 diag::err_storageclass_invalid_for_member);
868 else
869 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
870 D.getMutableDeclSpec().ClearStorageClassSpecs();
871 }
872
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000873 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000874 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000875 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000876 // Check also for this case:
877 //
878 // typedef int f();
879 // f a;
880 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000881 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000882 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000883 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000884
Sebastian Redl669d5d72008-11-14 23:42:31 +0000885 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
886 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000887 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888
889 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000890 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000891 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000892 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
893 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000894 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000895 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000896 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000897 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000898 if (!Member) {
899 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000900 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000901 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000902
903 // Non-instance-fields can't have a bitfield.
904 if (BitWidth) {
905 if (Member->isInvalidDecl()) {
906 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000907 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000908 // C++ 9.6p3: A bit-field shall not be a static member.
909 // "static member 'A' cannot be a bit-field"
910 Diag(Loc, diag::err_static_not_bitfield)
911 << Name << BitWidth->getSourceRange();
912 } else if (isa<TypedefDecl>(Member)) {
913 // "typedef member 'x' cannot be a bit-field"
914 Diag(Loc, diag::err_typedef_not_bitfield)
915 << Name << BitWidth->getSourceRange();
916 } else {
917 // A function typedef ("typedef int f(); f a;").
918 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
919 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000920 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000921 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattner8b963ef2009-03-05 23:01:03 +0000924 DeleteExpr(BitWidth);
925 BitWidth = 0;
926 Member->setInvalidDecl();
927 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000928
929 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregor37b372b2009-08-20 22:52:58 +0000931 // If we have declared a member function template, set the access of the
932 // templated declaration as well.
933 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
934 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000935 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000936
Douglas Gregor10bd3682008-11-17 22:58:34 +0000937 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000938
Douglas Gregor021c3b32009-03-11 23:00:04 +0000939 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000940 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000941 if (Deleted) // FIXME: Source location is not very good.
942 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000943
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000944 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000945 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000946 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000948 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949}
950
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000951/// \brief Find the direct and/or virtual base specifiers that
952/// correspond to the given base type, for use in base initialization
953/// within a constructor.
954static bool FindBaseInitializer(Sema &SemaRef,
955 CXXRecordDecl *ClassDecl,
956 QualType BaseType,
957 const CXXBaseSpecifier *&DirectBaseSpec,
958 const CXXBaseSpecifier *&VirtualBaseSpec) {
959 // First, check for a direct base class.
960 DirectBaseSpec = 0;
961 for (CXXRecordDecl::base_class_const_iterator Base
962 = ClassDecl->bases_begin();
963 Base != ClassDecl->bases_end(); ++Base) {
964 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
965 // We found a direct base of this type. That's what we're
966 // initializing.
967 DirectBaseSpec = &*Base;
968 break;
969 }
970 }
971
972 // Check for a virtual base class.
973 // FIXME: We might be able to short-circuit this if we know in advance that
974 // there are no virtual bases.
975 VirtualBaseSpec = 0;
976 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
977 // We haven't found a base yet; search the class hierarchy for a
978 // virtual base class.
979 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
980 /*DetectVirtual=*/false);
981 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
982 BaseType, Paths)) {
983 for (CXXBasePaths::paths_iterator Path = Paths.begin();
984 Path != Paths.end(); ++Path) {
985 if (Path->back().Base->isVirtual()) {
986 VirtualBaseSpec = Path->back().Base;
987 break;
988 }
989 }
990 }
991 }
992
993 return DirectBaseSpec || VirtualBaseSpec;
994}
995
Douglas Gregor7ad83902008-11-05 04:29:56 +0000996/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000997Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000998Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000999 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001000 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001001 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001002 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001003 SourceLocation IdLoc,
1004 SourceLocation LParenLoc,
1005 ExprTy **Args, unsigned NumArgs,
1006 SourceLocation *CommaLocs,
1007 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001008 if (!ConstructorD)
1009 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001011 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001012
1013 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001014 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001015 if (!Constructor) {
1016 // The user wrote a constructor initializer on a function that is
1017 // not a C++ constructor. Ignore the error for now, because we may
1018 // have more member initializers coming; we'll diagnose it just
1019 // once in ActOnMemInitializers.
1020 return true;
1021 }
1022
1023 CXXRecordDecl *ClassDecl = Constructor->getParent();
1024
1025 // C++ [class.base.init]p2:
1026 // Names in a mem-initializer-id are looked up in the scope of the
1027 // constructor’s class and, if not found in that scope, are looked
1028 // up in the scope containing the constructor’s
1029 // definition. [Note: if the constructor’s class contains a member
1030 // with the same name as a direct or virtual base class of the
1031 // class, a mem-initializer-id naming the member or base class and
1032 // composed of a single identifier refers to the class member. A
1033 // mem-initializer-id for the hidden base class may be specified
1034 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001035 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001036 // Look for a member, first.
1037 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001038 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001039 = ClassDecl->lookup(MemberOrBase);
1040 if (Result.first != Result.second)
1041 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001042
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001043 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001044
Eli Friedman59c04372009-07-29 19:44:27 +00001045 if (Member)
1046 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001047 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001048 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001049 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001050 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001051 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001052
1053 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001054 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001055 } else {
1056 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1057 LookupParsedName(R, S, &SS);
1058
1059 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1060 if (!TyD) {
1061 if (R.isAmbiguous()) return true;
1062
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001063 // If no results were found, try to correct typos.
1064 if (R.empty() &&
1065 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1066 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1067 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1068 // We have found a non-static data member with a similar
1069 // name to what was typed; complain and initialize that
1070 // member.
1071 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1072 << MemberOrBase << true << R.getLookupName()
1073 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1074 R.getLookupName().getAsString());
1075
1076 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1077 LParenLoc, RParenLoc);
1078 }
1079 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1080 const CXXBaseSpecifier *DirectBaseSpec;
1081 const CXXBaseSpecifier *VirtualBaseSpec;
1082 if (FindBaseInitializer(*this, ClassDecl,
1083 Context.getTypeDeclType(Type),
1084 DirectBaseSpec, VirtualBaseSpec)) {
1085 // We have found a direct or virtual base class with a
1086 // similar name to what was typed; complain and initialize
1087 // that base class.
1088 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1089 << MemberOrBase << false << R.getLookupName()
1090 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1091 R.getLookupName().getAsString());
1092
1093 TyD = Type;
1094 }
1095 }
1096 }
1097
1098 if (!TyD) {
1099 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1100 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1101 return true;
1102 }
John McCall2b194412009-12-21 10:41:20 +00001103 }
1104
1105 BaseType = Context.getTypeDeclType(TyD);
1106 if (SS.isSet()) {
1107 NestedNameSpecifier *Qualifier =
1108 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1109
1110 // FIXME: preserve source range information
1111 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1112 }
1113 }
Mike Stump1eb44332009-09-09 15:08:12 +00001114
John McCalla93c9342009-12-07 02:54:59 +00001115 if (!TInfo)
1116 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001117
John McCalla93c9342009-12-07 02:54:59 +00001118 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001119 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001120}
1121
John McCallb4190042009-11-04 23:02:40 +00001122/// Checks an initializer expression for use of uninitialized fields, such as
1123/// containing the field that is being initialized. Returns true if there is an
1124/// uninitialized field was used an updates the SourceLocation parameter; false
1125/// otherwise.
1126static bool InitExprContainsUninitializedFields(const Stmt* S,
1127 const FieldDecl* LhsField,
1128 SourceLocation* L) {
1129 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1130 if (ME) {
1131 const NamedDecl* RhsField = ME->getMemberDecl();
1132 if (RhsField == LhsField) {
1133 // Initializing a field with itself. Throw a warning.
1134 // But wait; there are exceptions!
1135 // Exception #1: The field may not belong to this record.
1136 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1137 const Expr* base = ME->getBase();
1138 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1139 // Even though the field matches, it does not belong to this record.
1140 return false;
1141 }
1142 // None of the exceptions triggered; return true to indicate an
1143 // uninitialized field was used.
1144 *L = ME->getMemberLoc();
1145 return true;
1146 }
1147 }
1148 bool found = false;
1149 for (Stmt::const_child_iterator it = S->child_begin();
1150 it != S->child_end() && found == false;
1151 ++it) {
1152 if (isa<CallExpr>(S)) {
1153 // Do not descend into function calls or constructors, as the use
1154 // of an uninitialized field may be valid. One would have to inspect
1155 // the contents of the function/ctor to determine if it is safe or not.
1156 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1157 // may be safe, depending on what the function/ctor does.
1158 continue;
1159 }
1160 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1161 }
1162 return found;
1163}
1164
Eli Friedman59c04372009-07-29 19:44:27 +00001165Sema::MemInitResult
1166Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1167 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001168 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001169 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001170 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1171 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1172 ExprTemporaries.clear();
1173
John McCallb4190042009-11-04 23:02:40 +00001174 // Diagnose value-uses of fields to initialize themselves, e.g.
1175 // foo(foo)
1176 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001177 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001178 for (unsigned i = 0; i < NumArgs; ++i) {
1179 SourceLocation L;
1180 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1181 // FIXME: Return true in the case when other fields are used before being
1182 // uninitialized. For example, let this field be the i'th field. When
1183 // initializing the i'th field, throw a warning if any of the >= i'th
1184 // fields are used, as they are not yet initialized.
1185 // Right now we are only handling the case where the i'th field uses
1186 // itself in its initializer.
1187 Diag(L, diag::warn_field_is_uninit);
1188 }
1189 }
1190
Eli Friedman59c04372009-07-29 19:44:27 +00001191 bool HasDependentArg = false;
1192 for (unsigned i = 0; i < NumArgs; i++)
1193 HasDependentArg |= Args[i]->isTypeDependent();
1194
1195 CXXConstructorDecl *C = 0;
1196 QualType FieldType = Member->getType();
1197 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1198 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001199 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Eli Friedman59c04372009-07-29 19:44:27 +00001200 if (FieldType->isDependentType()) {
1201 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001202 } else if (FieldType->isRecordType()) {
1203 // Member is a record (struct/union/class), so pass the initializer
1204 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001205 if (!HasDependentArg) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00001206 C = PerformInitializationByConstructor(FieldType,
1207 MultiExprArg(*this,
1208 (void**)Args,
1209 NumArgs),
1210 IdLoc,
1211 SourceRange(IdLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001212 Member->getDeclName(),
1213 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001214 ConstructorArgs);
1215
1216 if (C) {
1217 // Take over the constructor arguments as our own.
1218 NumArgs = ConstructorArgs.size();
1219 Args = (Expr **)ConstructorArgs.take();
1220 }
1221 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001222 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001223 // The member type is not a record type (or an array of record
1224 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001225 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001226 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1227 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001228 Expr *NewExp;
1229 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001230 if (FieldType->isReferenceType()) {
1231 Diag(IdLoc, diag::err_null_intialized_reference_member)
1232 << Member->getDeclName();
1233 return Diag(Member->getLocation(), diag::note_declared_at);
1234 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001235 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1236 NumArgs = 1;
1237 }
1238 else
1239 NewExp = (Expr*)Args[0];
Chris Lattner8c3f8902009-12-31 03:10:55 +00001240 if (!Member->isInvalidDecl() &&
1241 PerformCopyInitialization(NewExp, FieldType, AA_Passing))
Eli Friedman59c04372009-07-29 19:44:27 +00001242 return true;
1243 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001244 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001245
1246 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1247 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1248 ExprTemporaries.clear();
1249
Eli Friedman59c04372009-07-29 19:44:27 +00001250 // FIXME: Perform direct initialization of the member.
Douglas Gregor802ab452009-12-02 22:36:29 +00001251 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1252 C, LParenLoc, (Expr **)Args,
1253 NumArgs, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001254}
1255
1256Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001257Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001258 Expr **Args, unsigned NumArgs,
1259 SourceLocation LParenLoc, SourceLocation RParenLoc,
1260 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001261 bool HasDependentArg = false;
1262 for (unsigned i = 0; i < NumArgs; i++)
1263 HasDependentArg |= Args[i]->isTypeDependent();
1264
John McCalla93c9342009-12-07 02:54:59 +00001265 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman59c04372009-07-29 19:44:27 +00001266 if (!BaseType->isDependentType()) {
1267 if (!BaseType->isRecordType())
Douglas Gregor802ab452009-12-02 22:36:29 +00001268 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCalla93c9342009-12-07 02:54:59 +00001269 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001270
1271 // C++ [class.base.init]p2:
1272 // [...] Unless the mem-initializer-id names a nonstatic data
1273 // member of the constructor’s class or a direct or virtual base
1274 // of that class, the mem-initializer is ill-formed. A
1275 // mem-initializer-list can initialize a base class using any
1276 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001278 // Check for direct and virtual base classes.
Eli Friedman59c04372009-07-29 19:44:27 +00001279 const CXXBaseSpecifier *DirectBaseSpec = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001280 const CXXBaseSpecifier *VirtualBaseSpec = 0;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001281 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1282 VirtualBaseSpec);
Eli Friedman59c04372009-07-29 19:44:27 +00001283
1284 // C++ [base.class.init]p2:
1285 // If a mem-initializer-id is ambiguous because it designates both
1286 // a direct non-virtual base class and an inherited virtual base
1287 // class, the mem-initializer is ill-formed.
1288 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001289 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCalla93c9342009-12-07 02:54:59 +00001290 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001291 // C++ [base.class.init]p2:
1292 // Unless the mem-initializer-id names a nonstatic data membeer of the
1293 // constructor's class ot a direst or virtual base of that class, the
1294 // mem-initializer is ill-formed.
1295 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001296 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1297 << BaseType << ClassDecl->getNameAsCString()
John McCalla93c9342009-12-07 02:54:59 +00001298 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregor7ad83902008-11-05 04:29:56 +00001299 }
1300
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001301 CXXConstructorDecl *C = 0;
Eli Friedmane6d11b72009-12-25 23:59:21 +00001302 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Eli Friedman59c04372009-07-29 19:44:27 +00001303 if (!BaseType->isDependentType() && !HasDependentArg) {
1304 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001305 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001306
1307 C = PerformInitializationByConstructor(BaseType,
1308 MultiExprArg(*this,
1309 (void**)Args, NumArgs),
Douglas Gregor802ab452009-12-02 22:36:29 +00001310 BaseLoc,
1311 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001312 Name,
1313 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001314 ConstructorArgs);
1315 if (C) {
1316 // Take over the constructor arguments as our own.
1317 NumArgs = ConstructorArgs.size();
1318 Args = (Expr **)ConstructorArgs.take();
1319 }
Eli Friedman59c04372009-07-29 19:44:27 +00001320 }
1321
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001322 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1323 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1324 ExprTemporaries.clear();
1325
John McCalla93c9342009-12-07 02:54:59 +00001326 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregor802ab452009-12-02 22:36:29 +00001327 LParenLoc, (Expr **)Args,
1328 NumArgs, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001329}
1330
Eli Friedman80c30da2009-11-09 19:20:36 +00001331bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001332Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001333 CXXBaseOrMemberInitializer **Initializers,
1334 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001335 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001336 // We need to build the initializer AST according to order of construction
1337 // and not what user specified in the Initializers list.
1338 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1339 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1340 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1341 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001342 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001344 for (unsigned i = 0; i < NumInitializers; i++) {
1345 CXXBaseOrMemberInitializer *Member = Initializers[i];
1346 if (Member->isBaseInitializer()) {
1347 if (Member->getBaseClass()->isDependentType())
1348 HasDependentBaseInit = true;
1349 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1350 } else {
1351 AllBaseFields[Member->getMember()] = Member;
1352 }
1353 }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001355 if (HasDependentBaseInit) {
1356 // FIXME. This does not preserve the ordering of the initializers.
1357 // Try (with -Wreorder)
1358 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001359 // template<class X> struct B : A<X> {
1360 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001361 // int x1;
1362 // };
1363 // B<int> x;
1364 // On seeing one dependent type, we should essentially exit this routine
1365 // while preserving user-declared initializer list. When this routine is
1366 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001367 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001369 // If we have a dependent base initialization, we can't determine the
1370 // association between initializers and bases; just dump the known
1371 // initializers into the list, and don't try to deal with other bases.
1372 for (unsigned i = 0; i < NumInitializers; i++) {
1373 CXXBaseOrMemberInitializer *Member = Initializers[i];
1374 if (Member->isBaseInitializer())
1375 AllToInit.push_back(Member);
1376 }
1377 } else {
1378 // Push virtual bases before others.
1379 for (CXXRecordDecl::base_class_iterator VBase =
1380 ClassDecl->vbases_begin(),
1381 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1382 if (VBase->getType()->isDependentType())
1383 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001384 if (CXXBaseOrMemberInitializer *Value
1385 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001386 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001387 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001388 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001389 CXXRecordDecl *VBaseDecl =
Douglas Gregor802ab452009-12-02 22:36:29 +00001390 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001391 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001392 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001393 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001394 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1395 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1396 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001397 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001398 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001399 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001400 continue;
1401 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001402
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001403 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1404 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1405 Constructor->getLocation(), CtorArgs))
1406 continue;
1407
1408 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1409
Anders Carlsson8db68da2009-11-13 20:11:49 +00001410 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001411 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1412 // necessary.
1413 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001414 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001415 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001416 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001417 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001418 SourceLocation()),
1419 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001420 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001421 CtorArgs.takeAs<Expr>(),
1422 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001423 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001424 AllToInit.push_back(Member);
1425 }
1426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001428 for (CXXRecordDecl::base_class_iterator Base =
1429 ClassDecl->bases_begin(),
1430 E = ClassDecl->bases_end(); Base != E; ++Base) {
1431 // Virtuals are in the virtual base list and already constructed.
1432 if (Base->isVirtual())
1433 continue;
1434 // Skip dependent types.
1435 if (Base->getType()->isDependentType())
1436 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001437 if (CXXBaseOrMemberInitializer *Value
1438 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001439 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001440 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001441 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001442 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001443 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001444 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001445 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001446 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001447 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1448 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1449 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001450 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001451 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001452 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001453 continue;
1454 }
1455
1456 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1457 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1458 Constructor->getLocation(), CtorArgs))
1459 continue;
1460
1461 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001462
Anders Carlsson8db68da2009-11-13 20:11:49 +00001463 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001464 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1465 // necessary.
1466 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001467 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001468 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001469 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001470 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001471 SourceLocation()),
1472 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001473 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001474 CtorArgs.takeAs<Expr>(),
1475 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001476 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001477 AllToInit.push_back(Member);
1478 }
1479 }
1480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001482 // non-static data members.
1483 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1484 E = ClassDecl->field_end(); Field != E; ++Field) {
1485 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001486 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001487 Field->getType()->getAs<RecordType>()) {
1488 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001489 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001490 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001491 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1492 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1493 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1494 // set to the anonymous union data member used in the initializer
1495 // list.
1496 Value->setMember(*Field);
1497 Value->setAnonUnionMember(*FA);
1498 AllToInit.push_back(Value);
1499 break;
1500 }
1501 }
1502 }
1503 continue;
1504 }
1505 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1506 AllToInit.push_back(Value);
1507 continue;
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Eli Friedman49c16da2009-11-09 01:05:47 +00001510 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001511 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001512
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001513 QualType FT = Context.getBaseElementType((*Field)->getType());
1514 if (const RecordType* RT = FT->getAs<RecordType>()) {
1515 CXXConstructorDecl *Ctor =
1516 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001517 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001518 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1519 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1520 << 1 << (*Field)->getDeclName();
1521 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001522 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001523 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001524 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001525 continue;
1526 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001527
1528 if (FT.isConstQualified() && Ctor->isTrivial()) {
1529 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1530 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1531 << 1 << (*Field)->getDeclName();
1532 Diag((*Field)->getLocation(), diag::note_declared_at);
1533 HadError = true;
1534 }
1535
1536 // Don't create initializers for trivial constructors, since they don't
1537 // actually need to be run.
1538 if (Ctor->isTrivial())
1539 continue;
1540
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001541 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1542 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1543 Constructor->getLocation(), CtorArgs))
1544 continue;
1545
Anders Carlsson8db68da2009-11-13 20:11:49 +00001546 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1547 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1548 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001549 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001550 new (Context) CXXBaseOrMemberInitializer(Context,
1551 *Field, SourceLocation(),
1552 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001553 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001554 CtorArgs.takeAs<Expr>(),
1555 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001556 SourceLocation());
1557
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001558 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001559 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001560 }
1561 else if (FT->isReferenceType()) {
1562 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001563 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1564 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001565 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001566 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001567 }
1568 else if (FT.isConstQualified()) {
1569 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001570 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1571 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001572 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001573 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001574 }
1575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001577 NumInitializers = AllToInit.size();
1578 if (NumInitializers > 0) {
1579 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1580 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1581 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001583 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1584 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1585 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1586 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001587
1588 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001589}
1590
Eli Friedman6347f422009-07-21 19:28:10 +00001591static void *GetKeyForTopLevelField(FieldDecl *Field) {
1592 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001593 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001594 if (RT->getDecl()->isAnonymousStructOrUnion())
1595 return static_cast<void *>(RT->getDecl());
1596 }
1597 return static_cast<void *>(Field);
1598}
1599
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001600static void *GetKeyForBase(QualType BaseType) {
1601 if (const RecordType *RT = BaseType->getAs<RecordType>())
1602 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001604 assert(0 && "Unexpected base type!");
1605 return 0;
1606}
1607
Mike Stump1eb44332009-09-09 15:08:12 +00001608static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001609 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001610 // For fields injected into the class via declaration of an anonymous union,
1611 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001612 if (Member->isMemberInitializer()) {
1613 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Eli Friedman49c16da2009-11-09 01:05:47 +00001615 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001616 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001617 // in AnonUnionMember field.
1618 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1619 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001620 if (Field->getDeclContext()->isRecord()) {
1621 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1622 if (RD->isAnonymousStructOrUnion())
1623 return static_cast<void *>(RD);
1624 }
1625 return static_cast<void *>(Field);
1626 }
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001628 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001629}
1630
John McCall6aee6212009-11-04 23:13:52 +00001631/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001632void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001633 SourceLocation ColonLoc,
1634 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001635 if (!ConstructorDecl)
1636 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001637
1638 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
1640 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001641 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Anders Carlssona7b35212009-03-25 02:58:17 +00001643 if (!Constructor) {
1644 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1645 return;
1646 }
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001648 if (!Constructor->isDependentContext()) {
1649 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1650 bool err = false;
1651 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001652 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001653 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1654 void *KeyToMember = GetKeyForMember(Member);
1655 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1656 if (!PrevMember) {
1657 PrevMember = Member;
1658 continue;
1659 }
1660 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001661 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001662 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001663 << Field->getNameAsString()
1664 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001665 else {
1666 Type *BaseClass = Member->getBaseClass();
1667 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001668 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001669 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001670 << QualType(BaseClass, 0)
1671 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001672 }
1673 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1674 << 0;
1675 err = true;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001678 if (err)
1679 return;
1680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Eli Friedman49c16da2009-11-09 01:05:47 +00001682 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001683 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001684 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001686 if (Constructor->isDependentContext())
1687 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001688
1689 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001690 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001691 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001692 Diagnostic::Ignored)
1693 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001695 // Also issue warning if order of ctor-initializer list does not match order
1696 // of 1) base class declarations and 2) order of non-static data members.
1697 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001699 CXXRecordDecl *ClassDecl
1700 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1701 // Push virtual bases before others.
1702 for (CXXRecordDecl::base_class_iterator VBase =
1703 ClassDecl->vbases_begin(),
1704 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001705 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001707 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1708 E = ClassDecl->bases_end(); Base != E; ++Base) {
1709 // Virtuals are alread in the virtual base list and are constructed
1710 // first.
1711 if (Base->isVirtual())
1712 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001713 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001714 }
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001716 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1717 E = ClassDecl->field_end(); Field != E; ++Field)
1718 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001720 int Last = AllBaseOrMembers.size();
1721 int curIndex = 0;
1722 CXXBaseOrMemberInitializer *PrevMember = 0;
1723 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001724 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001725 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1726 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001727
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001728 for (; curIndex < Last; curIndex++)
1729 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1730 break;
1731 if (curIndex == Last) {
1732 assert(PrevMember && "Member not in member list?!");
1733 // Initializer as specified in ctor-initializer list is out of order.
1734 // Issue a warning diagnostic.
1735 if (PrevMember->isBaseInitializer()) {
1736 // Diagnostics is for an initialized base class.
1737 Type *BaseClass = PrevMember->getBaseClass();
1738 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001739 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001740 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001741 } else {
1742 FieldDecl *Field = PrevMember->getMember();
1743 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001744 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001745 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001746 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001747 // Also the note!
1748 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001749 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001750 diag::note_fieldorbase_initialized_here) << 0
1751 << Field->getNameAsString();
1752 else {
1753 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001754 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001755 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001756 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001757 }
1758 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001759 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001760 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001761 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001762 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001763 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001764}
1765
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001766void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001767Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1768 // Ignore dependent destructors.
1769 if (Destructor->isDependentContext())
1770 return;
1771
1772 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Anders Carlsson9f853df2009-11-17 04:44:12 +00001774 // Non-static data members.
1775 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1776 E = ClassDecl->field_end(); I != E; ++I) {
1777 FieldDecl *Field = *I;
1778
1779 QualType FieldType = Context.getBaseElementType(Field->getType());
1780
1781 const RecordType* RT = FieldType->getAs<RecordType>();
1782 if (!RT)
1783 continue;
1784
1785 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1786 if (FieldClassDecl->hasTrivialDestructor())
1787 continue;
1788
1789 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1790 MarkDeclarationReferenced(Destructor->getLocation(),
1791 const_cast<CXXDestructorDecl*>(Dtor));
1792 }
1793
1794 // Bases.
1795 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1796 E = ClassDecl->bases_end(); Base != E; ++Base) {
1797 // Ignore virtual bases.
1798 if (Base->isVirtual())
1799 continue;
1800
1801 // Ignore trivial destructors.
1802 CXXRecordDecl *BaseClassDecl
1803 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1804 if (BaseClassDecl->hasTrivialDestructor())
1805 continue;
1806
1807 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1808 MarkDeclarationReferenced(Destructor->getLocation(),
1809 const_cast<CXXDestructorDecl*>(Dtor));
1810 }
1811
1812 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001813 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1814 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001815 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001816 CXXRecordDecl *BaseClassDecl
1817 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1818 if (BaseClassDecl->hasTrivialDestructor())
1819 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001820
1821 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1822 MarkDeclarationReferenced(Destructor->getLocation(),
1823 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001824 }
1825}
1826
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001827void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001828 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001829 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001831 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001832
1833 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001834 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001835 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001836}
1837
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001838namespace {
1839 /// PureVirtualMethodCollector - traverses a class and its superclasses
1840 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001841 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001842 ASTContext &Context;
1843
Sebastian Redldfe292d2009-03-22 21:28:55 +00001844 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001845 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001846
1847 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001848 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001850 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001852 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001853 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001854 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001856 MethodList List;
1857 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001859 // Copy the temporary list to methods, and make sure to ignore any
1860 // null entries.
1861 for (size_t i = 0, e = List.size(); i != e; ++i) {
1862 if (List[i])
1863 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001864 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001867 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001869 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1870 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001871 };
Mike Stump1eb44332009-09-09 15:08:12 +00001872
1873 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001874 MethodList& Methods) {
1875 // First, collect the pure virtual methods for the base classes.
1876 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1877 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001878 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001879 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001880 if (BaseDecl && BaseDecl->isAbstract())
1881 Collect(BaseDecl, Methods);
1882 }
1883 }
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001885 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001886 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001888 MethodSetTy OverriddenMethods;
1889 size_t MethodsSize = Methods.size();
1890
Mike Stump1eb44332009-09-09 15:08:12 +00001891 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001892 i != e; ++i) {
1893 // Traverse the record, looking for methods.
1894 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001895 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001896 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001897 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Anders Carlsson27823022009-10-18 19:34:08 +00001899 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001900 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1901 E = MD->end_overridden_methods(); I != E; ++I) {
1902 // Keep track of the overridden methods.
1903 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001904 }
1905 }
1906 }
Mike Stump1eb44332009-09-09 15:08:12 +00001907
1908 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001909 // overridden.
1910 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1911 if (OverriddenMethods.count(Methods[i]))
1912 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001913 }
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001915 }
1916}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001917
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001918
Mike Stump1eb44332009-09-09 15:08:12 +00001919bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001920 unsigned DiagID, AbstractDiagSelID SelID,
1921 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001922 if (SelID == -1)
1923 return RequireNonAbstractType(Loc, T,
1924 PDiag(DiagID), CurrentRD);
1925 else
1926 return RequireNonAbstractType(Loc, T,
1927 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001928}
1929
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001930bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1931 const PartialDiagnostic &PD,
1932 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001933 if (!getLangOptions().CPlusPlus)
1934 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Anders Carlsson11f21a02009-03-23 19:10:31 +00001936 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001937 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001938 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Ted Kremenek6217b802009-07-29 21:53:49 +00001940 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001941 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001942 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001943 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001945 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001946 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001947 }
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Ted Kremenek6217b802009-07-29 21:53:49 +00001949 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001950 if (!RT)
1951 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001953 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1954 if (!RD)
1955 return false;
1956
Anders Carlssone65a3c82009-03-24 17:23:42 +00001957 if (CurrentRD && CurrentRD != RD)
1958 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001960 if (!RD->isAbstract())
1961 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001963 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001965 // Check if we've already emitted the list of pure virtual functions for this
1966 // class.
1967 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1968 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001970 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
1972 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001973 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1974 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001975
1976 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001977 MD->getDeclName();
1978 }
1979
1980 if (!PureVirtualClassDiagSet)
1981 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1982 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001984 return true;
1985}
1986
Anders Carlsson8211eff2009-03-24 01:19:16 +00001987namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001988 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001989 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1990 Sema &SemaRef;
1991 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Anders Carlssone65a3c82009-03-24 17:23:42 +00001993 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001994 bool Invalid = false;
1995
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001996 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1997 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001998 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001999
Anders Carlsson8211eff2009-03-24 01:19:16 +00002000 return Invalid;
2001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlssone65a3c82009-03-24 17:23:42 +00002003 public:
2004 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2005 : SemaRef(SemaRef), AbstractClass(ac) {
2006 Visit(SemaRef.Context.getTranslationUnitDecl());
2007 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002008
Anders Carlssone65a3c82009-03-24 17:23:42 +00002009 bool VisitFunctionDecl(const FunctionDecl *FD) {
2010 if (FD->isThisDeclarationADefinition()) {
2011 // No need to do the check if we're in a definition, because it requires
2012 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002013 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002014 return VisitDeclContext(FD);
2015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Anders Carlssone65a3c82009-03-24 17:23:42 +00002017 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002018 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002019 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002020 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2021 diag::err_abstract_type_in_decl,
2022 Sema::AbstractReturnType,
2023 AbstractClass);
2024
Mike Stump1eb44332009-09-09 15:08:12 +00002025 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002026 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002027 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002028 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002029 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002030 VD->getOriginalType(),
2031 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002032 Sema::AbstractParamType,
2033 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002034 }
2035
2036 return Invalid;
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Anders Carlssone65a3c82009-03-24 17:23:42 +00002039 bool VisitDecl(const Decl* D) {
2040 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2041 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Anders Carlssone65a3c82009-03-24 17:23:42 +00002043 return false;
2044 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002045 };
2046}
2047
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002048/// \brief Perform semantic checks on a class definition that has been
2049/// completing, introducing implicitly-declared members, checking for
2050/// abstract types, etc.
2051void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2052 if (!Record || Record->isInvalidDecl())
2053 return;
2054
Eli Friedmanff2d8782009-12-16 20:00:27 +00002055 if (!Record->isDependentType())
2056 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002057
Eli Friedmanff2d8782009-12-16 20:00:27 +00002058 if (Record->isInvalidDecl())
2059 return;
2060
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002061 if (!Record->isAbstract()) {
2062 // Collect all the pure virtual methods and see if this is an abstract
2063 // class after all.
2064 PureVirtualMethodCollector Collector(Context, Record);
2065 if (!Collector.empty())
2066 Record->setAbstract(true);
2067 }
2068
2069 if (Record->isAbstract())
2070 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002071}
2072
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002073void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002074 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002075 SourceLocation LBrac,
2076 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002077 if (!TagDecl)
2078 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregor42af25f2009-05-11 19:58:34 +00002080 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002081
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002082 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002083 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002084 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002085
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002086 CheckCompletedCXXClass(
2087 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002088}
2089
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002090/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2091/// special functions, such as the default constructor, copy
2092/// constructor, or destructor, to the given C++ class (C++
2093/// [special]p1). This routine can only be executed just before the
2094/// definition of the class is complete.
2095void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002096 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002097 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002098
Sebastian Redl465226e2009-05-27 22:11:52 +00002099 // FIXME: Implicit declarations have exception specifications, which are
2100 // the union of the specifications of the implicitly called functions.
2101
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002102 if (!ClassDecl->hasUserDeclaredConstructor()) {
2103 // C++ [class.ctor]p5:
2104 // A default constructor for a class X is a constructor of class X
2105 // that can be called without an argument. If there is no
2106 // user-declared constructor for class X, a default constructor is
2107 // implicitly declared. An implicitly-declared default constructor
2108 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002109 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002110 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002111 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002112 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002113 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002114 Context.getFunctionType(Context.VoidTy,
2115 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002116 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002117 /*isExplicit=*/false,
2118 /*isInline=*/true,
2119 /*isImplicitlyDeclared=*/true);
2120 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002121 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002122 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002123 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002124 }
2125
2126 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2127 // C++ [class.copy]p4:
2128 // If the class definition does not explicitly declare a copy
2129 // constructor, one is declared implicitly.
2130
2131 // C++ [class.copy]p5:
2132 // The implicitly-declared copy constructor for a class X will
2133 // have the form
2134 //
2135 // X::X(const X&)
2136 //
2137 // if
2138 bool HasConstCopyConstructor = true;
2139
2140 // -- each direct or virtual base class B of X has a copy
2141 // constructor whose first parameter is of type const B& or
2142 // const volatile B&, and
2143 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2144 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2145 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002146 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002147 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002148 = BaseClassDecl->hasConstCopyConstructor(Context);
2149 }
2150
2151 // -- for all the nonstatic data members of X that are of a
2152 // class type M (or array thereof), each such class type
2153 // has a copy constructor whose first parameter is of type
2154 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002155 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2156 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002157 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002158 QualType FieldType = (*Field)->getType();
2159 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2160 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002161 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002162 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002163 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002164 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002165 = FieldClassDecl->hasConstCopyConstructor(Context);
2166 }
2167 }
2168
Sebastian Redl64b45f72009-01-05 20:52:13 +00002169 // Otherwise, the implicitly declared copy constructor will have
2170 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002171 //
2172 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002173 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002174 if (HasConstCopyConstructor)
2175 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002176 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002177
Sebastian Redl64b45f72009-01-05 20:52:13 +00002178 // An implicitly-declared copy constructor is an inline public
2179 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002180 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002181 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002182 CXXConstructorDecl *CopyConstructor
2183 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002184 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002185 Context.getFunctionType(Context.VoidTy,
2186 &ArgType, 1,
2187 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002188 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002189 /*isExplicit=*/false,
2190 /*isInline=*/true,
2191 /*isImplicitlyDeclared=*/true);
2192 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002193 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002194 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002195
2196 // Add the parameter to the constructor.
2197 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2198 ClassDecl->getLocation(),
2199 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002200 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002201 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002202 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002203 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002204 }
2205
Sebastian Redl64b45f72009-01-05 20:52:13 +00002206 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2207 // Note: The following rules are largely analoguous to the copy
2208 // constructor rules. Note that virtual bases are not taken into account
2209 // for determining the argument type of the operator. Note also that
2210 // operators taking an object instead of a reference are allowed.
2211 //
2212 // C++ [class.copy]p10:
2213 // If the class definition does not explicitly declare a copy
2214 // assignment operator, one is declared implicitly.
2215 // The implicitly-defined copy assignment operator for a class X
2216 // will have the form
2217 //
2218 // X& X::operator=(const X&)
2219 //
2220 // if
2221 bool HasConstCopyAssignment = true;
2222
2223 // -- each direct base class B of X has a copy assignment operator
2224 // whose parameter is of type const B&, const volatile B& or B,
2225 // and
2226 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2227 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002228 assert(!Base->getType()->isDependentType() &&
2229 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002230 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002231 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002232 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002233 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002234 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002235 }
2236
2237 // -- for all the nonstatic data members of X that are of a class
2238 // type M (or array thereof), each such class type has a copy
2239 // assignment operator whose parameter is of type const M&,
2240 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002241 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2242 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002243 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002244 QualType FieldType = (*Field)->getType();
2245 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2246 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002247 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002248 const CXXRecordDecl *FieldClassDecl
2249 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002250 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002251 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002252 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002253 }
2254 }
2255
2256 // Otherwise, the implicitly declared copy assignment operator will
2257 // have the form
2258 //
2259 // X& X::operator=(X&)
2260 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002261 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002262 if (HasConstCopyAssignment)
2263 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002264 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002265
2266 // An implicitly-declared copy assignment operator is an inline public
2267 // member of its class.
2268 DeclarationName Name =
2269 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2270 CXXMethodDecl *CopyAssignment =
2271 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2272 Context.getFunctionType(RetType, &ArgType, 1,
2273 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002274 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002275 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002276 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002277 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002278 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002279
2280 // Add the parameter to the operator.
2281 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2282 ClassDecl->getLocation(),
2283 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002284 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002285 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002286 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002287
2288 // Don't call addedAssignmentOperator. There is no way to distinguish an
2289 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002290 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002291 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002292 }
2293
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002294 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002295 // C++ [class.dtor]p2:
2296 // If a class has no user-declared destructor, a destructor is
2297 // declared implicitly. An implicitly-declared destructor is an
2298 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002299 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002300 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002301 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002302 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002303 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002304 Context.getFunctionType(Context.VoidTy,
2305 0, 0, false, 0),
2306 /*isInline=*/true,
2307 /*isImplicitlyDeclared=*/true);
2308 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002309 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002310 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002311 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002312
2313 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002314 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002315}
2316
Douglas Gregor6569d682009-05-27 23:11:45 +00002317void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002318 Decl *D = TemplateD.getAs<Decl>();
2319 if (!D)
2320 return;
2321
2322 TemplateParameterList *Params = 0;
2323 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2324 Params = Template->getTemplateParameters();
2325 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2326 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2327 Params = PartialSpec->getTemplateParameters();
2328 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002329 return;
2330
Douglas Gregor6569d682009-05-27 23:11:45 +00002331 for (TemplateParameterList::iterator Param = Params->begin(),
2332 ParamEnd = Params->end();
2333 Param != ParamEnd; ++Param) {
2334 NamedDecl *Named = cast<NamedDecl>(*Param);
2335 if (Named->getDeclName()) {
2336 S->AddDecl(DeclPtrTy::make(Named));
2337 IdResolver.AddDecl(Named);
2338 }
2339 }
2340}
2341
John McCall7a1dc562009-12-19 10:49:29 +00002342void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2343 if (!RecordD) return;
2344 AdjustDeclIfTemplate(RecordD);
2345 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2346 PushDeclContext(S, Record);
2347}
2348
2349void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2350 if (!RecordD) return;
2351 PopDeclContext();
2352}
2353
Douglas Gregor72b505b2008-12-16 21:30:33 +00002354/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2355/// parsing a top-level (non-nested) C++ class, and we are now
2356/// parsing those parts of the given Method declaration that could
2357/// not be parsed earlier (C++ [class.mem]p2), such as default
2358/// arguments. This action should enter the scope of the given
2359/// Method declaration as if we had just parsed the qualified method
2360/// name. However, it should not bring the parameters into scope;
2361/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002362void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002363}
2364
2365/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2366/// C++ method declaration. We're (re-)introducing the given
2367/// function parameter into scope for use in parsing later parts of
2368/// the method declaration. For example, we could see an
2369/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002370void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002371 if (!ParamD)
2372 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002373
Chris Lattnerb28317a2009-03-28 19:18:32 +00002374 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002375
2376 // If this parameter has an unparsed default argument, clear it out
2377 // to make way for the parsed default argument.
2378 if (Param->hasUnparsedDefaultArg())
2379 Param->setDefaultArg(0);
2380
Chris Lattnerb28317a2009-03-28 19:18:32 +00002381 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002382 if (Param->getDeclName())
2383 IdResolver.AddDecl(Param);
2384}
2385
2386/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2387/// processing the delayed method declaration for Method. The method
2388/// declaration is now considered finished. There may be a separate
2389/// ActOnStartOfFunctionDef action later (not necessarily
2390/// immediately!) for this method, if it was also defined inside the
2391/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002392void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002393 if (!MethodD)
2394 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002396 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Chris Lattnerb28317a2009-03-28 19:18:32 +00002398 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002399
2400 // Now that we have our default arguments, check the constructor
2401 // again. It could produce additional diagnostics or affect whether
2402 // the class has implicitly-declared destructors, among other
2403 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002404 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2405 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002406
2407 // Check the default arguments, which we may have added.
2408 if (!Method->isInvalidDecl())
2409 CheckCXXDefaultArguments(Method);
2410}
2411
Douglas Gregor42a552f2008-11-05 20:51:48 +00002412/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002413/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002414/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002415/// emit diagnostics and set the invalid bit to true. In any case, the type
2416/// will be updated to reflect a well-formed type for the constructor and
2417/// returned.
2418QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2419 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002420 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002421
2422 // C++ [class.ctor]p3:
2423 // A constructor shall not be virtual (10.3) or static (9.4). A
2424 // constructor can be invoked for a const, volatile or const
2425 // volatile object. A constructor shall not be declared const,
2426 // volatile, or const volatile (9.3.2).
2427 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002428 if (!D.isInvalidType())
2429 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2430 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2431 << SourceRange(D.getIdentifierLoc());
2432 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002433 }
2434 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002435 if (!D.isInvalidType())
2436 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2437 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2438 << SourceRange(D.getIdentifierLoc());
2439 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002440 SC = FunctionDecl::None;
2441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Chris Lattner65401802009-04-25 08:28:21 +00002443 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2444 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002445 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002446 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2447 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002448 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002449 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2450 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002451 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002452 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2453 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002454 }
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Douglas Gregor42a552f2008-11-05 20:51:48 +00002456 // Rebuild the function type "R" without any type qualifiers (in
2457 // case any of the errors above fired) and with "void" as the
2458 // return type, since constructors don't have return types. We
2459 // *always* have to do this, because GetTypeForDeclarator will
2460 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002461 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002462 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2463 Proto->getNumArgs(),
2464 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002465}
2466
Douglas Gregor72b505b2008-12-16 21:30:33 +00002467/// CheckConstructor - Checks a fully-formed constructor for
2468/// well-formedness, issuing any diagnostics required. Returns true if
2469/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002470void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002471 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002472 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2473 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002474 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002475
2476 // C++ [class.copy]p3:
2477 // A declaration of a constructor for a class X is ill-formed if
2478 // its first parameter is of type (optionally cv-qualified) X and
2479 // either there are no other parameters or else all other
2480 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002481 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002482 ((Constructor->getNumParams() == 1) ||
2483 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002484 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2485 Constructor->getTemplateSpecializationKind()
2486 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002487 QualType ParamType = Constructor->getParamDecl(0)->getType();
2488 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2489 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002490 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2491 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002492 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002493
2494 // FIXME: Rather that making the constructor invalid, we should endeavor
2495 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002496 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002497 }
2498 }
Mike Stump1eb44332009-09-09 15:08:12 +00002499
Douglas Gregor72b505b2008-12-16 21:30:33 +00002500 // Notify the class that we've added a constructor.
2501 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002502}
2503
Anders Carlsson37909802009-11-30 21:24:50 +00002504/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2505/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002506bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002507 CXXRecordDecl *RD = Destructor->getParent();
2508
2509 if (Destructor->isVirtual()) {
2510 SourceLocation Loc;
2511
2512 if (!Destructor->isImplicit())
2513 Loc = Destructor->getLocation();
2514 else
2515 Loc = RD->getLocation();
2516
2517 // If we have a virtual destructor, look up the deallocation function
2518 FunctionDecl *OperatorDelete = 0;
2519 DeclarationName Name =
2520 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002521 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002522 return true;
2523
2524 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002525 }
Anders Carlsson37909802009-11-30 21:24:50 +00002526
2527 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002528}
2529
Mike Stump1eb44332009-09-09 15:08:12 +00002530static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002531FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2532 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2533 FTI.ArgInfo[0].Param &&
2534 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2535}
2536
Douglas Gregor42a552f2008-11-05 20:51:48 +00002537/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2538/// the well-formednes of the destructor declarator @p D with type @p
2539/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002540/// emit diagnostics and set the declarator to invalid. Even if this happens,
2541/// will be updated to reflect a well-formed type for the destructor and
2542/// returned.
2543QualType Sema::CheckDestructorDeclarator(Declarator &D,
2544 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002545 // C++ [class.dtor]p1:
2546 // [...] A typedef-name that names a class is a class-name
2547 // (7.1.3); however, a typedef-name that names a class shall not
2548 // be used as the identifier in the declarator for a destructor
2549 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002550 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002551 if (isa<TypedefType>(DeclaratorType)) {
2552 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002553 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002554 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002555 }
2556
2557 // C++ [class.dtor]p2:
2558 // A destructor is used to destroy objects of its class type. A
2559 // destructor takes no parameters, and no return type can be
2560 // specified for it (not even void). The address of a destructor
2561 // shall not be taken. A destructor shall not be static. A
2562 // destructor can be invoked for a const, volatile or const
2563 // volatile object. A destructor shall not be declared const,
2564 // volatile or const volatile (9.3.2).
2565 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002566 if (!D.isInvalidType())
2567 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2568 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2569 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002570 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002571 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002572 }
Chris Lattner65401802009-04-25 08:28:21 +00002573 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002574 // Destructors don't have return types, but the parser will
2575 // happily parse something like:
2576 //
2577 // class X {
2578 // float ~X();
2579 // };
2580 //
2581 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002582 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2583 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2584 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Chris Lattner65401802009-04-25 08:28:21 +00002587 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2588 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002589 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002590 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2591 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002592 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002593 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2594 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002595 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002596 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2597 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002598 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002599 }
2600
2601 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002602 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002603 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2604
2605 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002606 FTI.freeArgs();
2607 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002608 }
2609
Mike Stump1eb44332009-09-09 15:08:12 +00002610 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002611 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002612 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002613 D.setInvalidType();
2614 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002615
2616 // Rebuild the function type "R" without any type qualifiers or
2617 // parameters (in case any of the errors above fired) and with
2618 // "void" as the return type, since destructors don't have return
2619 // types. We *always* have to do this, because GetTypeForDeclarator
2620 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002621 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002622}
2623
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002624/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2625/// well-formednes of the conversion function declarator @p D with
2626/// type @p R. If there are any errors in the declarator, this routine
2627/// will emit diagnostics and return true. Otherwise, it will return
2628/// false. Either way, the type @p R will be updated to reflect a
2629/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002630void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002631 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002632 // C++ [class.conv.fct]p1:
2633 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002634 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002635 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002636 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002637 if (!D.isInvalidType())
2638 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2639 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2640 << SourceRange(D.getIdentifierLoc());
2641 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002642 SC = FunctionDecl::None;
2643 }
Chris Lattner6e475012009-04-25 08:35:12 +00002644 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002645 // Conversion functions don't have return types, but the parser will
2646 // happily parse something like:
2647 //
2648 // class X {
2649 // float operator bool();
2650 // };
2651 //
2652 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002653 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2654 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2655 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002656 }
2657
2658 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002659 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002660 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2661
2662 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002663 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002664 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002665 }
2666
Mike Stump1eb44332009-09-09 15:08:12 +00002667 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002668 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002669 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002670 D.setInvalidType();
2671 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002672
2673 // C++ [class.conv.fct]p4:
2674 // The conversion-type-id shall not represent a function type nor
2675 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002676 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002677 if (ConvType->isArrayType()) {
2678 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2679 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002680 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002681 } else if (ConvType->isFunctionType()) {
2682 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2683 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002684 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002685 }
2686
2687 // Rebuild the function type "R" without any parameters (in case any
2688 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002689 // return type.
2690 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002691 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002692
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002693 // C++0x explicit conversion operators.
2694 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002695 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002696 diag::warn_explicit_conversion_functions)
2697 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002698}
2699
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002700/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2701/// the declaration of the given C++ conversion function. This routine
2702/// is responsible for recording the conversion function in the C++
2703/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002704Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002705 assert(Conversion && "Expected to receive a conversion function declaration");
2706
Douglas Gregor9d350972008-12-12 08:25:50 +00002707 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002708
2709 // Make sure we aren't redeclaring the conversion function.
2710 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002711
2712 // C++ [class.conv.fct]p1:
2713 // [...] A conversion function is never used to convert a
2714 // (possibly cv-qualified) object to the (possibly cv-qualified)
2715 // same object type (or a reference to it), to a (possibly
2716 // cv-qualified) base class of that type (or a reference to it),
2717 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002718 // FIXME: Suppress this warning if the conversion function ends up being a
2719 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002720 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002721 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002722 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002723 ConvType = ConvTypeRef->getPointeeType();
2724 if (ConvType->isRecordType()) {
2725 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2726 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002727 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002728 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002729 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002730 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002731 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002732 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002733 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002734 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002735 }
2736
Douglas Gregor70316a02008-12-26 15:00:45 +00002737 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002738 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002739 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002740 = Conversion->getDescribedFunctionTemplate())
2741 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002742 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2743 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002744 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002745 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002746 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002747 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002748 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002749 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002750
Chris Lattnerb28317a2009-03-28 19:18:32 +00002751 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002752}
2753
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002754//===----------------------------------------------------------------------===//
2755// Namespace Handling
2756//===----------------------------------------------------------------------===//
2757
2758/// ActOnStartNamespaceDef - This is called at the start of a namespace
2759/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002760Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2761 SourceLocation IdentLoc,
2762 IdentifierInfo *II,
2763 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002764 NamespaceDecl *Namespc =
2765 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2766 Namespc->setLBracLoc(LBrace);
2767
2768 Scope *DeclRegionScope = NamespcScope->getParent();
2769
2770 if (II) {
2771 // C++ [namespace.def]p2:
2772 // The identifier in an original-namespace-definition shall not have been
2773 // previously defined in the declarative region in which the
2774 // original-namespace-definition appears. The identifier in an
2775 // original-namespace-definition is the name of the namespace. Subsequently
2776 // in that declarative region, it is treated as an original-namespace-name.
2777
John McCallf36e02d2009-10-09 21:13:30 +00002778 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002779 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002780 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Douglas Gregor44b43212008-12-11 16:49:14 +00002782 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2783 // This is an extended namespace definition.
2784 // Attach this namespace decl to the chain of extended namespace
2785 // definitions.
2786 OrigNS->setNextNamespace(Namespc);
2787 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002788
Mike Stump1eb44332009-09-09 15:08:12 +00002789 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002790 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002791 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002792 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002793 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002794 } else if (PrevDecl) {
2795 // This is an invalid name redefinition.
2796 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2797 << Namespc->getDeclName();
2798 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2799 Namespc->setInvalidDecl();
2800 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002801 } else if (II->isStr("std") &&
2802 CurContext->getLookupContext()->isTranslationUnit()) {
2803 // This is the first "real" definition of the namespace "std", so update
2804 // our cache of the "std" namespace to point at this definition.
2805 if (StdNamespace) {
2806 // We had already defined a dummy namespace "std". Link this new
2807 // namespace definition to the dummy namespace "std".
2808 StdNamespace->setNextNamespace(Namespc);
2809 StdNamespace->setLocation(IdentLoc);
2810 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2811 }
2812
2813 // Make our StdNamespace cache point at the first real definition of the
2814 // "std" namespace.
2815 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002816 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002817
2818 PushOnScopeChains(Namespc, DeclRegionScope);
2819 } else {
John McCall9aeed322009-10-01 00:25:31 +00002820 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002821 assert(Namespc->isAnonymousNamespace());
2822 CurContext->addDecl(Namespc);
2823
2824 // Link the anonymous namespace into its parent.
2825 NamespaceDecl *PrevDecl;
2826 DeclContext *Parent = CurContext->getLookupContext();
2827 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2828 PrevDecl = TU->getAnonymousNamespace();
2829 TU->setAnonymousNamespace(Namespc);
2830 } else {
2831 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2832 PrevDecl = ND->getAnonymousNamespace();
2833 ND->setAnonymousNamespace(Namespc);
2834 }
2835
2836 // Link the anonymous namespace with its previous declaration.
2837 if (PrevDecl) {
2838 assert(PrevDecl->isAnonymousNamespace());
2839 assert(!PrevDecl->getNextNamespace());
2840 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2841 PrevDecl->setNextNamespace(Namespc);
2842 }
John McCall9aeed322009-10-01 00:25:31 +00002843
2844 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2845 // behaves as if it were replaced by
2846 // namespace unique { /* empty body */ }
2847 // using namespace unique;
2848 // namespace unique { namespace-body }
2849 // where all occurrences of 'unique' in a translation unit are
2850 // replaced by the same identifier and this identifier differs
2851 // from all other identifiers in the entire program.
2852
2853 // We just create the namespace with an empty name and then add an
2854 // implicit using declaration, just like the standard suggests.
2855 //
2856 // CodeGen enforces the "universally unique" aspect by giving all
2857 // declarations semantically contained within an anonymous
2858 // namespace internal linkage.
2859
John McCall5fdd7642009-12-16 02:06:49 +00002860 if (!PrevDecl) {
2861 UsingDirectiveDecl* UD
2862 = UsingDirectiveDecl::Create(Context, CurContext,
2863 /* 'using' */ LBrace,
2864 /* 'namespace' */ SourceLocation(),
2865 /* qualifier */ SourceRange(),
2866 /* NNS */ NULL,
2867 /* identifier */ SourceLocation(),
2868 Namespc,
2869 /* Ancestor */ CurContext);
2870 UD->setImplicit();
2871 CurContext->addDecl(UD);
2872 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002873 }
2874
2875 // Although we could have an invalid decl (i.e. the namespace name is a
2876 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002877 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2878 // for the namespace has the declarations that showed up in that particular
2879 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002880 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002881 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002882}
2883
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002884/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2885/// is a namespace alias, returns the namespace it points to.
2886static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2887 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2888 return AD->getNamespace();
2889 return dyn_cast_or_null<NamespaceDecl>(D);
2890}
2891
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002892/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2893/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002894void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2895 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002896 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2897 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2898 Namespc->setRBracLoc(RBrace);
2899 PopDeclContext();
2900}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002901
Chris Lattnerb28317a2009-03-28 19:18:32 +00002902Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2903 SourceLocation UsingLoc,
2904 SourceLocation NamespcLoc,
2905 const CXXScopeSpec &SS,
2906 SourceLocation IdentLoc,
2907 IdentifierInfo *NamespcName,
2908 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002909 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2910 assert(NamespcName && "Invalid NamespcName.");
2911 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002912 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002913
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002914 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002915
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002916 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002917 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2918 LookupParsedName(R, S, &SS);
2919 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002920 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002921
John McCallf36e02d2009-10-09 21:13:30 +00002922 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002923 NamedDecl *Named = R.getFoundDecl();
2924 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2925 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002926 // C++ [namespace.udir]p1:
2927 // A using-directive specifies that the names in the nominated
2928 // namespace can be used in the scope in which the
2929 // using-directive appears after the using-directive. During
2930 // unqualified name lookup (3.4.1), the names appear as if they
2931 // were declared in the nearest enclosing namespace which
2932 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002933 // namespace. [Note: in this context, "contains" means "contains
2934 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002935
2936 // Find enclosing context containing both using-directive and
2937 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002938 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002939 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2940 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2941 CommonAncestor = CommonAncestor->getParent();
2942
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002943 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002944 SS.getRange(),
2945 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002946 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002947 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002948 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002949 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002950 }
2951
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002952 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002953 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002954 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002955}
2956
2957void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2958 // If scope has associated entity, then using directive is at namespace
2959 // or translation unit scope. We add UsingDirectiveDecls, into
2960 // it's lookup structure.
2961 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002962 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002963 else
2964 // Otherwise it is block-sope. using-directives will affect lookup
2965 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002966 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002967}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002968
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002969
2970Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002971 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00002972 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002973 SourceLocation UsingLoc,
2974 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002975 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002976 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002977 bool IsTypeName,
2978 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002979 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Douglas Gregor12c118a2009-11-04 16:30:06 +00002981 switch (Name.getKind()) {
2982 case UnqualifiedId::IK_Identifier:
2983 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002984 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002985 case UnqualifiedId::IK_ConversionFunctionId:
2986 break;
2987
2988 case UnqualifiedId::IK_ConstructorName:
John McCall604e7f12009-12-08 07:46:18 +00002989 // C++0x inherited constructors.
2990 if (getLangOptions().CPlusPlus0x) break;
2991
Douglas Gregor12c118a2009-11-04 16:30:06 +00002992 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2993 << SS.getRange();
2994 return DeclPtrTy();
2995
2996 case UnqualifiedId::IK_DestructorName:
2997 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2998 << SS.getRange();
2999 return DeclPtrTy();
3000
3001 case UnqualifiedId::IK_TemplateId:
3002 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3003 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3004 return DeclPtrTy();
3005 }
3006
3007 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003008 if (!TargetName)
3009 return DeclPtrTy();
3010
John McCall60fa3cf2009-12-11 02:10:03 +00003011 // Warn about using declarations.
3012 // TODO: store that the declaration was written without 'using' and
3013 // talk about access decls instead of using decls in the
3014 // diagnostics.
3015 if (!HasUsingKeyword) {
3016 UsingLoc = Name.getSourceRange().getBegin();
3017
3018 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3019 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3020 "using ");
3021 }
3022
John McCall9488ea12009-11-17 05:59:44 +00003023 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003024 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003025 TargetName, AttrList,
3026 /* IsInstantiation */ false,
3027 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003028 if (UD)
3029 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Anders Carlssonc72160b2009-08-28 05:40:36 +00003031 return DeclPtrTy::make(UD);
3032}
3033
John McCall9f54ad42009-12-10 09:41:52 +00003034/// Determines whether to create a using shadow decl for a particular
3035/// decl, given the set of decls existing prior to this using lookup.
3036bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3037 const LookupResult &Previous) {
3038 // Diagnose finding a decl which is not from a base class of the
3039 // current class. We do this now because there are cases where this
3040 // function will silently decide not to build a shadow decl, which
3041 // will pre-empt further diagnostics.
3042 //
3043 // We don't need to do this in C++0x because we do the check once on
3044 // the qualifier.
3045 //
3046 // FIXME: diagnose the following if we care enough:
3047 // struct A { int foo; };
3048 // struct B : A { using A::foo; };
3049 // template <class T> struct C : A {};
3050 // template <class T> struct D : C<T> { using B::foo; } // <---
3051 // This is invalid (during instantiation) in C++03 because B::foo
3052 // resolves to the using decl in B, which is not a base class of D<T>.
3053 // We can't diagnose it immediately because C<T> is an unknown
3054 // specialization. The UsingShadowDecl in D<T> then points directly
3055 // to A::foo, which will look well-formed when we instantiate.
3056 // The right solution is to not collapse the shadow-decl chain.
3057 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3058 DeclContext *OrigDC = Orig->getDeclContext();
3059
3060 // Handle enums and anonymous structs.
3061 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3062 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3063 while (OrigRec->isAnonymousStructOrUnion())
3064 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3065
3066 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3067 if (OrigDC == CurContext) {
3068 Diag(Using->getLocation(),
3069 diag::err_using_decl_nested_name_specifier_is_current_class)
3070 << Using->getNestedNameRange();
3071 Diag(Orig->getLocation(), diag::note_using_decl_target);
3072 return true;
3073 }
3074
3075 Diag(Using->getNestedNameRange().getBegin(),
3076 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3077 << Using->getTargetNestedNameDecl()
3078 << cast<CXXRecordDecl>(CurContext)
3079 << Using->getNestedNameRange();
3080 Diag(Orig->getLocation(), diag::note_using_decl_target);
3081 return true;
3082 }
3083 }
3084
3085 if (Previous.empty()) return false;
3086
3087 NamedDecl *Target = Orig;
3088 if (isa<UsingShadowDecl>(Target))
3089 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3090
John McCalld7533ec2009-12-11 02:33:26 +00003091 // If the target happens to be one of the previous declarations, we
3092 // don't have a conflict.
3093 //
3094 // FIXME: but we might be increasing its access, in which case we
3095 // should redeclare it.
3096 NamedDecl *NonTag = 0, *Tag = 0;
3097 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3098 I != E; ++I) {
3099 NamedDecl *D = (*I)->getUnderlyingDecl();
3100 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3101 return false;
3102
3103 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3104 }
3105
John McCall9f54ad42009-12-10 09:41:52 +00003106 if (Target->isFunctionOrFunctionTemplate()) {
3107 FunctionDecl *FD;
3108 if (isa<FunctionTemplateDecl>(Target))
3109 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3110 else
3111 FD = cast<FunctionDecl>(Target);
3112
3113 NamedDecl *OldDecl = 0;
3114 switch (CheckOverload(FD, Previous, OldDecl)) {
3115 case Ovl_Overload:
3116 return false;
3117
3118 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003119 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003120 break;
3121
3122 // We found a decl with the exact signature.
3123 case Ovl_Match:
3124 if (isa<UsingShadowDecl>(OldDecl)) {
3125 // Silently ignore the possible conflict.
3126 return false;
3127 }
3128
3129 // If we're in a record, we want to hide the target, so we
3130 // return true (without a diagnostic) to tell the caller not to
3131 // build a shadow decl.
3132 if (CurContext->isRecord())
3133 return true;
3134
3135 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003136 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003137 break;
3138 }
3139
3140 Diag(Target->getLocation(), diag::note_using_decl_target);
3141 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3142 return true;
3143 }
3144
3145 // Target is not a function.
3146
John McCall9f54ad42009-12-10 09:41:52 +00003147 if (isa<TagDecl>(Target)) {
3148 // No conflict between a tag and a non-tag.
3149 if (!Tag) return false;
3150
John McCall41ce66f2009-12-10 19:51:03 +00003151 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003152 Diag(Target->getLocation(), diag::note_using_decl_target);
3153 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3154 return true;
3155 }
3156
3157 // No conflict between a tag and a non-tag.
3158 if (!NonTag) return false;
3159
John McCall41ce66f2009-12-10 19:51:03 +00003160 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003161 Diag(Target->getLocation(), diag::note_using_decl_target);
3162 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3163 return true;
3164}
3165
John McCall9488ea12009-11-17 05:59:44 +00003166/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003167UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003168 UsingDecl *UD,
3169 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003170
3171 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003172 NamedDecl *Target = Orig;
3173 if (isa<UsingShadowDecl>(Target)) {
3174 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3175 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003176 }
3177
3178 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003179 = UsingShadowDecl::Create(Context, CurContext,
3180 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003181 UD->addShadowDecl(Shadow);
3182
3183 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003184 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003185 else
John McCall604e7f12009-12-08 07:46:18 +00003186 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003187 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003188
John McCall604e7f12009-12-08 07:46:18 +00003189 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3190 Shadow->setInvalidDecl();
3191
John McCall9f54ad42009-12-10 09:41:52 +00003192 return Shadow;
3193}
John McCall604e7f12009-12-08 07:46:18 +00003194
John McCall9f54ad42009-12-10 09:41:52 +00003195/// Hides a using shadow declaration. This is required by the current
3196/// using-decl implementation when a resolvable using declaration in a
3197/// class is followed by a declaration which would hide or override
3198/// one or more of the using decl's targets; for example:
3199///
3200/// struct Base { void foo(int); };
3201/// struct Derived : Base {
3202/// using Base::foo;
3203/// void foo(int);
3204/// };
3205///
3206/// The governing language is C++03 [namespace.udecl]p12:
3207///
3208/// When a using-declaration brings names from a base class into a
3209/// derived class scope, member functions in the derived class
3210/// override and/or hide member functions with the same name and
3211/// parameter types in a base class (rather than conflicting).
3212///
3213/// There are two ways to implement this:
3214/// (1) optimistically create shadow decls when they're not hidden
3215/// by existing declarations, or
3216/// (2) don't create any shadow decls (or at least don't make them
3217/// visible) until we've fully parsed/instantiated the class.
3218/// The problem with (1) is that we might have to retroactively remove
3219/// a shadow decl, which requires several O(n) operations because the
3220/// decl structures are (very reasonably) not designed for removal.
3221/// (2) avoids this but is very fiddly and phase-dependent.
3222void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3223 // Remove it from the DeclContext...
3224 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003225
John McCall9f54ad42009-12-10 09:41:52 +00003226 // ...and the scope, if applicable...
3227 if (S) {
3228 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3229 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003230 }
3231
John McCall9f54ad42009-12-10 09:41:52 +00003232 // ...and the using decl.
3233 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3234
3235 // TODO: complain somehow if Shadow was used. It shouldn't
3236 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003237}
3238
John McCall7ba107a2009-11-18 02:36:19 +00003239/// Builds a using declaration.
3240///
3241/// \param IsInstantiation - Whether this call arises from an
3242/// instantiation of an unresolved using declaration. We treat
3243/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003244NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3245 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003246 const CXXScopeSpec &SS,
3247 SourceLocation IdentLoc,
3248 DeclarationName Name,
3249 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003250 bool IsInstantiation,
3251 bool IsTypeName,
3252 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003253 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3254 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003255
Anders Carlsson550b14b2009-08-28 05:49:21 +00003256 // FIXME: We ignore attributes for now.
3257 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003258
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003259 if (SS.isEmpty()) {
3260 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003261 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003262 }
Mike Stump1eb44332009-09-09 15:08:12 +00003263
John McCall9f54ad42009-12-10 09:41:52 +00003264 // Do the redeclaration lookup in the current scope.
3265 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3266 ForRedeclaration);
3267 Previous.setHideTags(false);
3268 if (S) {
3269 LookupName(Previous, S);
3270
3271 // It is really dumb that we have to do this.
3272 LookupResult::Filter F = Previous.makeFilter();
3273 while (F.hasNext()) {
3274 NamedDecl *D = F.next();
3275 if (!isDeclInScope(D, CurContext, S))
3276 F.erase();
3277 }
3278 F.done();
3279 } else {
3280 assert(IsInstantiation && "no scope in non-instantiation");
3281 assert(CurContext->isRecord() && "scope not record in instantiation");
3282 LookupQualifiedName(Previous, CurContext);
3283 }
3284
Mike Stump1eb44332009-09-09 15:08:12 +00003285 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003286 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3287
John McCall9f54ad42009-12-10 09:41:52 +00003288 // Check for invalid redeclarations.
3289 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3290 return 0;
3291
3292 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003293 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3294 return 0;
3295
John McCallaf8e6ed2009-11-12 03:15:40 +00003296 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003297 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003298 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003299 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003300 // FIXME: not all declaration name kinds are legal here
3301 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3302 UsingLoc, TypenameLoc,
3303 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003304 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003305 } else {
3306 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3307 UsingLoc, SS.getRange(), NNS,
3308 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003309 }
John McCalled976492009-12-04 22:46:56 +00003310 } else {
3311 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3312 SS.getRange(), UsingLoc, NNS, Name,
3313 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003314 }
John McCalled976492009-12-04 22:46:56 +00003315 D->setAccess(AS);
3316 CurContext->addDecl(D);
3317
3318 if (!LookupContext) return D;
3319 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003320
John McCall604e7f12009-12-08 07:46:18 +00003321 if (RequireCompleteDeclContext(SS)) {
3322 UD->setInvalidDecl();
3323 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003324 }
3325
John McCall604e7f12009-12-08 07:46:18 +00003326 // Look up the target name.
3327
John McCalla24dc2e2009-11-17 02:14:36 +00003328 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003329
John McCall604e7f12009-12-08 07:46:18 +00003330 // Unlike most lookups, we don't always want to hide tag
3331 // declarations: tag names are visible through the using declaration
3332 // even if hidden by ordinary names, *except* in a dependent context
3333 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003334 if (!IsInstantiation)
3335 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003336
John McCalla24dc2e2009-11-17 02:14:36 +00003337 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003338
John McCallf36e02d2009-10-09 21:13:30 +00003339 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003340 Diag(IdentLoc, diag::err_no_member)
3341 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003342 UD->setInvalidDecl();
3343 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003344 }
3345
John McCalled976492009-12-04 22:46:56 +00003346 if (R.isAmbiguous()) {
3347 UD->setInvalidDecl();
3348 return UD;
3349 }
Mike Stump1eb44332009-09-09 15:08:12 +00003350
John McCall7ba107a2009-11-18 02:36:19 +00003351 if (IsTypeName) {
3352 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003353 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003354 Diag(IdentLoc, diag::err_using_typename_non_type);
3355 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3356 Diag((*I)->getUnderlyingDecl()->getLocation(),
3357 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003358 UD->setInvalidDecl();
3359 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003360 }
3361 } else {
3362 // If we asked for a non-typename and we got a type, error out,
3363 // but only if this is an instantiation of an unresolved using
3364 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003365 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003366 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3367 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003368 UD->setInvalidDecl();
3369 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003370 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003371 }
3372
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003373 // C++0x N2914 [namespace.udecl]p6:
3374 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003375 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003376 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3377 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003378 UD->setInvalidDecl();
3379 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003380 }
Mike Stump1eb44332009-09-09 15:08:12 +00003381
John McCall9f54ad42009-12-10 09:41:52 +00003382 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3383 if (!CheckUsingShadowDecl(UD, *I, Previous))
3384 BuildUsingShadowDecl(S, UD, *I);
3385 }
John McCall9488ea12009-11-17 05:59:44 +00003386
3387 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003388}
3389
John McCall9f54ad42009-12-10 09:41:52 +00003390/// Checks that the given using declaration is not an invalid
3391/// redeclaration. Note that this is checking only for the using decl
3392/// itself, not for any ill-formedness among the UsingShadowDecls.
3393bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3394 bool isTypeName,
3395 const CXXScopeSpec &SS,
3396 SourceLocation NameLoc,
3397 const LookupResult &Prev) {
3398 // C++03 [namespace.udecl]p8:
3399 // C++0x [namespace.udecl]p10:
3400 // A using-declaration is a declaration and can therefore be used
3401 // repeatedly where (and only where) multiple declarations are
3402 // allowed.
3403 // That's only in file contexts.
3404 if (CurContext->getLookupContext()->isFileContext())
3405 return false;
3406
3407 NestedNameSpecifier *Qual
3408 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3409
3410 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3411 NamedDecl *D = *I;
3412
3413 bool DTypename;
3414 NestedNameSpecifier *DQual;
3415 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3416 DTypename = UD->isTypeName();
3417 DQual = UD->getTargetNestedNameDecl();
3418 } else if (UnresolvedUsingValueDecl *UD
3419 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3420 DTypename = false;
3421 DQual = UD->getTargetNestedNameSpecifier();
3422 } else if (UnresolvedUsingTypenameDecl *UD
3423 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3424 DTypename = true;
3425 DQual = UD->getTargetNestedNameSpecifier();
3426 } else continue;
3427
3428 // using decls differ if one says 'typename' and the other doesn't.
3429 // FIXME: non-dependent using decls?
3430 if (isTypeName != DTypename) continue;
3431
3432 // using decls differ if they name different scopes (but note that
3433 // template instantiation can cause this check to trigger when it
3434 // didn't before instantiation).
3435 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3436 Context.getCanonicalNestedNameSpecifier(DQual))
3437 continue;
3438
3439 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003440 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003441 return true;
3442 }
3443
3444 return false;
3445}
3446
John McCall604e7f12009-12-08 07:46:18 +00003447
John McCalled976492009-12-04 22:46:56 +00003448/// Checks that the given nested-name qualifier used in a using decl
3449/// in the current context is appropriately related to the current
3450/// scope. If an error is found, diagnoses it and returns true.
3451bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3452 const CXXScopeSpec &SS,
3453 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003454 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003455
John McCall604e7f12009-12-08 07:46:18 +00003456 if (!CurContext->isRecord()) {
3457 // C++03 [namespace.udecl]p3:
3458 // C++0x [namespace.udecl]p8:
3459 // A using-declaration for a class member shall be a member-declaration.
3460
3461 // If we weren't able to compute a valid scope, it must be a
3462 // dependent class scope.
3463 if (!NamedContext || NamedContext->isRecord()) {
3464 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3465 << SS.getRange();
3466 return true;
3467 }
3468
3469 // Otherwise, everything is known to be fine.
3470 return false;
3471 }
3472
3473 // The current scope is a record.
3474
3475 // If the named context is dependent, we can't decide much.
3476 if (!NamedContext) {
3477 // FIXME: in C++0x, we can diagnose if we can prove that the
3478 // nested-name-specifier does not refer to a base class, which is
3479 // still possible in some cases.
3480
3481 // Otherwise we have to conservatively report that things might be
3482 // okay.
3483 return false;
3484 }
3485
3486 if (!NamedContext->isRecord()) {
3487 // Ideally this would point at the last name in the specifier,
3488 // but we don't have that level of source info.
3489 Diag(SS.getRange().getBegin(),
3490 diag::err_using_decl_nested_name_specifier_is_not_class)
3491 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3492 return true;
3493 }
3494
3495 if (getLangOptions().CPlusPlus0x) {
3496 // C++0x [namespace.udecl]p3:
3497 // In a using-declaration used as a member-declaration, the
3498 // nested-name-specifier shall name a base class of the class
3499 // being defined.
3500
3501 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3502 cast<CXXRecordDecl>(NamedContext))) {
3503 if (CurContext == NamedContext) {
3504 Diag(NameLoc,
3505 diag::err_using_decl_nested_name_specifier_is_current_class)
3506 << SS.getRange();
3507 return true;
3508 }
3509
3510 Diag(SS.getRange().getBegin(),
3511 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3512 << (NestedNameSpecifier*) SS.getScopeRep()
3513 << cast<CXXRecordDecl>(CurContext)
3514 << SS.getRange();
3515 return true;
3516 }
3517
3518 return false;
3519 }
3520
3521 // C++03 [namespace.udecl]p4:
3522 // A using-declaration used as a member-declaration shall refer
3523 // to a member of a base class of the class being defined [etc.].
3524
3525 // Salient point: SS doesn't have to name a base class as long as
3526 // lookup only finds members from base classes. Therefore we can
3527 // diagnose here only if we can prove that that can't happen,
3528 // i.e. if the class hierarchies provably don't intersect.
3529
3530 // TODO: it would be nice if "definitely valid" results were cached
3531 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3532 // need to be repeated.
3533
3534 struct UserData {
3535 llvm::DenseSet<const CXXRecordDecl*> Bases;
3536
3537 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3538 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3539 Data->Bases.insert(Base);
3540 return true;
3541 }
3542
3543 bool hasDependentBases(const CXXRecordDecl *Class) {
3544 return !Class->forallBases(collect, this);
3545 }
3546
3547 /// Returns true if the base is dependent or is one of the
3548 /// accumulated base classes.
3549 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3550 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3551 return !Data->Bases.count(Base);
3552 }
3553
3554 bool mightShareBases(const CXXRecordDecl *Class) {
3555 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3556 }
3557 };
3558
3559 UserData Data;
3560
3561 // Returns false if we find a dependent base.
3562 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3563 return false;
3564
3565 // Returns false if the class has a dependent base or if it or one
3566 // of its bases is present in the base set of the current context.
3567 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3568 return false;
3569
3570 Diag(SS.getRange().getBegin(),
3571 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3572 << (NestedNameSpecifier*) SS.getScopeRep()
3573 << cast<CXXRecordDecl>(CurContext)
3574 << SS.getRange();
3575
3576 return true;
John McCalled976492009-12-04 22:46:56 +00003577}
3578
Mike Stump1eb44332009-09-09 15:08:12 +00003579Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003580 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003581 SourceLocation AliasLoc,
3582 IdentifierInfo *Alias,
3583 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003584 SourceLocation IdentLoc,
3585 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003586
Anders Carlsson81c85c42009-03-28 23:53:49 +00003587 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003588 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3589 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003590
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003591 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003592 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003593 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003594 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003595 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003596 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003597 if (!R.isAmbiguous() && !R.empty() &&
3598 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003599 return DeclPtrTy();
3600 }
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003602 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3603 diag::err_redefinition_different_kind;
3604 Diag(AliasLoc, DiagID) << Alias;
3605 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003606 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003607 }
3608
John McCalla24dc2e2009-11-17 02:14:36 +00003609 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003610 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003611
John McCallf36e02d2009-10-09 21:13:30 +00003612 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003613 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003614 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003615 }
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003617 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003618 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3619 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003620 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003621 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003623 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003624 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003625}
3626
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003627void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3628 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003629 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3630 !Constructor->isUsed()) &&
3631 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Eli Friedman80c30da2009-11-09 19:20:36 +00003633 CXXRecordDecl *ClassDecl
3634 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3635 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003636
Eli Friedman80c30da2009-11-09 19:20:36 +00003637 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003638 Diag(CurrentLocation, diag::note_member_synthesized_at)
3639 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003640 Constructor->setInvalidDecl();
3641 } else {
3642 Constructor->setUsed();
3643 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003644}
3645
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003646void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003647 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003648 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3649 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003650 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003651 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3652 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003653 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003654 // implicitly defined, all the implicitly-declared default destructors
3655 // for its base class and its non-static data members shall have been
3656 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003657 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3658 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003659 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003660 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003661 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003662 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003663 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3664 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3665 else
Mike Stump1eb44332009-09-09 15:08:12 +00003666 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003667 "DefineImplicitDestructor - missing dtor in a base class");
3668 }
3669 }
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003671 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3672 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003673 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3674 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3675 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003676 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003677 CXXRecordDecl *FieldClassDecl
3678 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3679 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003680 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003681 const_cast<CXXDestructorDecl*>(
3682 FieldClassDecl->getDestructor(Context)))
3683 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3684 else
Mike Stump1eb44332009-09-09 15:08:12 +00003685 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003686 "DefineImplicitDestructor - missing dtor in class of a data member");
3687 }
3688 }
3689 }
Anders Carlsson37909802009-11-30 21:24:50 +00003690
3691 // FIXME: If CheckDestructor fails, we should emit a note about where the
3692 // implicit destructor was needed.
3693 if (CheckDestructor(Destructor)) {
3694 Diag(CurrentLocation, diag::note_member_synthesized_at)
3695 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3696
3697 Destructor->setInvalidDecl();
3698 return;
3699 }
3700
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003701 Destructor->setUsed();
3702}
3703
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003704void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3705 CXXMethodDecl *MethodDecl) {
3706 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3707 MethodDecl->getOverloadedOperator() == OO_Equal &&
3708 !MethodDecl->isUsed()) &&
3709 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003711 CXXRecordDecl *ClassDecl
3712 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003714 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003715 // Before the implicitly-declared copy assignment operator for a class is
3716 // implicitly defined, all implicitly-declared copy assignment operators
3717 // for its direct base classes and its nonstatic data members shall have
3718 // been implicitly defined.
3719 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3721 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003722 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003724 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003725 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3726 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003727 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3728 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003729 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3730 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003731 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3732 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3733 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003734 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003735 CXXRecordDecl *FieldClassDecl
3736 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003737 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003738 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3739 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003740 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003741 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003742 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003743 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3744 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003745 Diag(CurrentLocation, diag::note_first_required_here);
3746 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003747 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003748 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003749 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3750 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003751 Diag(CurrentLocation, diag::note_first_required_here);
3752 err = true;
3753 }
3754 }
3755 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003756 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003757}
3758
3759CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003760Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3761 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003762 CXXRecordDecl *ClassDecl) {
3763 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3764 QualType RHSType(LHSType);
3765 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003766 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003767 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003768 RHSType = Context.getCVRQualifiedType(RHSType,
3769 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003770 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003771 LHSType,
3772 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003773 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003774 RHSType,
3775 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003776 Expr *Args[2] = { &*LHS, &*RHS };
3777 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003778 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003779 CandidateSet);
3780 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003781 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003782 return cast<CXXMethodDecl>(Best->Function);
3783 assert(false &&
3784 "getAssignOperatorMethod - copy assignment operator method not found");
3785 return 0;
3786}
3787
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003788void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3789 CXXConstructorDecl *CopyConstructor,
3790 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003791 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003792 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003793 !CopyConstructor->isUsed()) &&
3794 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003796 CXXRecordDecl *ClassDecl
3797 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3798 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003799 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003800 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003801 // implicitly defined, all the implicitly-declared copy constructors
3802 // for its base class and its non-static data members shall have been
3803 // implicitly defined.
3804 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3805 Base != ClassDecl->bases_end(); ++Base) {
3806 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003807 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003808 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003809 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003810 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003811 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003812 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3813 FieldEnd = ClassDecl->field_end();
3814 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003815 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3816 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3817 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003818 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003819 CXXRecordDecl *FieldClassDecl
3820 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003821 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003822 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003823 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003824 }
3825 }
3826 CopyConstructor->setUsed();
3827}
3828
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003829Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003830Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003831 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003832 MultiExprArg ExprArgs,
3833 bool RequiresZeroInit) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003834 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Douglas Gregor39da0b82009-09-09 23:08:42 +00003836 // C++ [class.copy]p15:
3837 // Whenever a temporary class object is copied using a copy constructor, and
3838 // this object and the copy have the same cv-unqualified type, an
3839 // implementation is permitted to treat the original and the copy as two
3840 // different ways of referring to the same object and not perform a copy at
3841 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003842
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003843 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003844 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003845 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003846 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3847 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3848 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003849 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3850 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003851 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3852 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003853 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3854 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3855 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003856
3857 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3858 Elidable = !CE->getCallReturnType()->isReferenceType();
3859 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003860 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003861 else if (isa<CXXConstructExpr>(E))
3862 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003863 }
Mike Stump1eb44332009-09-09 15:08:12 +00003864
3865 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003866 Elidable, move(ExprArgs), RequiresZeroInit);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003867}
3868
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003869/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3870/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003871Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003872Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3873 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003874 MultiExprArg ExprArgs,
3875 bool RequiresZeroInit) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003876 unsigned NumExprs = ExprArgs.size();
3877 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Douglas Gregor7edfb692009-11-23 12:27:39 +00003879 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003880 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003881 Constructor, Elidable, Exprs, NumExprs,
3882 RequiresZeroInit));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003883}
3884
Anders Carlssone7624a72009-08-27 05:08:22 +00003885Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003886Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3887 QualType Ty,
3888 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003889 MultiExprArg Args,
3890 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003891 unsigned NumExprs = Args.size();
3892 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003893
Douglas Gregor7edfb692009-11-23 12:27:39 +00003894 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003895 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3896 TyBeginLoc, Exprs,
3897 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003898}
3899
3900
Mike Stump1eb44332009-09-09 15:08:12 +00003901bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003902 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003903 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003904 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003905 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003906 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003907 if (TempResult.isInvalid())
3908 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003910 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003911 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003912 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor78d15832009-05-26 18:54:04 +00003913 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Anders Carlssonfe2de492009-08-25 05:18:00 +00003915 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003916}
3917
Mike Stump1eb44332009-09-09 15:08:12 +00003918void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003919 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003920 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003921 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003922 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003923 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003924 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003925}
3926
Mike Stump1eb44332009-09-09 15:08:12 +00003927/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003928/// ActOnDeclarator, when a C++ direct initializer is present.
3929/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003930void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3931 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003932 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003933 SourceLocation *CommaLocs,
3934 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00003935 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003936 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003937
3938 // If there is no declaration, there was an error parsing it. Just ignore
3939 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003940 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003941 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003942
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003943 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3944 if (!VDecl) {
3945 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3946 RealDecl->setInvalidDecl();
3947 return;
3948 }
3949
Douglas Gregor83ddad32009-08-26 21:14:46 +00003950 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003951 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003952 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3953 //
3954 // Clients that want to distinguish between the two forms, can check for
3955 // direct initializer using VarDecl::hasCXXDirectInitializer().
3956 // A major benefit is that clients that don't particularly care about which
3957 // exactly form was it (like the CodeGen) can handle both cases without
3958 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003959
Douglas Gregor83ddad32009-08-26 21:14:46 +00003960 // If either the declaration has a dependent type or if any of the expressions
3961 // is type-dependent, we represent the initialization via a ParenListExpr for
3962 // later use during template instantiation.
3963 if (VDecl->getType()->isDependentType() ||
3964 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3965 // Let clients know that initialization was done with a direct initializer.
3966 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Douglas Gregor83ddad32009-08-26 21:14:46 +00003968 // Store the initialization expressions as a ParenListExpr.
3969 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003970 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003971 new (Context) ParenListExpr(Context, LParenLoc,
3972 (Expr **)Exprs.release(),
3973 NumExprs, RParenLoc));
3974 return;
3975 }
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Douglas Gregor83ddad32009-08-26 21:14:46 +00003977
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003978 // C++ 8.5p11:
3979 // The form of initialization (using parentheses or '=') is generally
3980 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003981 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003982 QualType DeclInitType = VDecl->getType();
3983 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003984 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003985
Douglas Gregor615c5d42009-03-24 16:43:20 +00003986 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3987 diag::err_typecheck_decl_incomplete_type)) {
3988 VDecl->setInvalidDecl();
3989 return;
3990 }
3991
Douglas Gregor90f93822009-12-22 22:17:25 +00003992 // The variable can not have an abstract class type.
3993 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3994 diag::err_abstract_type_in_decl,
3995 AbstractVariableType))
3996 VDecl->setInvalidDecl();
3997
3998 const VarDecl *Def = 0;
3999 if (VDecl->getDefinition(Def)) {
4000 Diag(VDecl->getLocation(), diag::err_redefinition)
4001 << VDecl->getDeclName();
4002 Diag(Def->getLocation(), diag::note_previous_definition);
4003 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004004 return;
4005 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004006
4007 // Capture the variable that is being initialized and the style of
4008 // initialization.
4009 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4010
4011 // FIXME: Poor source location information.
4012 InitializationKind Kind
4013 = InitializationKind::CreateDirect(VDecl->getLocation(),
4014 LParenLoc, RParenLoc);
4015
4016 InitializationSequence InitSeq(*this, Entity, Kind,
4017 (Expr**)Exprs.get(), Exprs.size());
4018 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4019 if (Result.isInvalid()) {
4020 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004021 return;
4022 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004023
4024 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4025 VDecl->setInit(Context, Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004026 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004027
Douglas Gregor90f93822009-12-22 22:17:25 +00004028 if (VDecl->getType()->getAs<RecordType>())
4029 FinalizeVarWithDestructor(VDecl, DeclInitType);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004030}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004031
Douglas Gregor19aeac62009-11-14 03:27:21 +00004032/// \brief Add the applicable constructor candidates for an initialization
4033/// by constructor.
4034static void AddConstructorInitializationCandidates(Sema &SemaRef,
4035 QualType ClassType,
4036 Expr **Args,
4037 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004038 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004039 OverloadCandidateSet &CandidateSet) {
4040 // C++ [dcl.init]p14:
4041 // If the initialization is direct-initialization, or if it is
4042 // copy-initialization where the cv-unqualified version of the
4043 // source type is the same class as, or a derived class of, the
4044 // class of the destination, constructors are considered. The
4045 // applicable constructors are enumerated (13.3.1.3), and the
4046 // best one is chosen through overload resolution (13.3). The
4047 // constructor so selected is called to initialize the object,
4048 // with the initializer expression(s) as its argument(s). If no
4049 // constructor applies, or the overload resolution is ambiguous,
4050 // the initialization is ill-formed.
4051 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4052 assert(ClassRec && "Can only initialize a class type here");
4053
4054 // FIXME: When we decide not to synthesize the implicitly-declared
4055 // constructors, we'll need to make them appear here.
4056
4057 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4058 DeclarationName ConstructorName
4059 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4060 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4061 DeclContext::lookup_const_iterator Con, ConEnd;
4062 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4063 Con != ConEnd; ++Con) {
4064 // Find the constructor (which may be a template).
4065 CXXConstructorDecl *Constructor = 0;
4066 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4067 if (ConstructorTmpl)
4068 Constructor
4069 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4070 else
4071 Constructor = cast<CXXConstructorDecl>(*Con);
4072
Douglas Gregor20093b42009-12-09 23:02:17 +00004073 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4074 (Kind.getKind() == InitializationKind::IK_Value) ||
4075 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004076 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 ((Kind.getKind() == InitializationKind::IK_Default) &&
4078 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004079 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004080 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4081 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004082 Args, NumArgs, CandidateSet);
4083 else
4084 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
4085 }
4086 }
4087}
4088
4089/// \brief Attempt to perform initialization by constructor
4090/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4091/// copy-initialization.
4092///
4093/// This routine determines whether initialization by constructor is possible,
4094/// but it does not emit any diagnostics in the case where the initialization
4095/// is ill-formed.
4096///
4097/// \param ClassType the type of the object being initialized, which must have
4098/// class type.
4099///
4100/// \param Args the arguments provided to initialize the object
4101///
4102/// \param NumArgs the number of arguments provided to initialize the object
4103///
4104/// \param Kind the type of initialization being performed
4105///
4106/// \returns the constructor used to initialize the object, if successful.
4107/// Otherwise, emits a diagnostic and returns NULL.
4108CXXConstructorDecl *
4109Sema::TryInitializationByConstructor(QualType ClassType,
4110 Expr **Args, unsigned NumArgs,
4111 SourceLocation Loc,
4112 InitializationKind Kind) {
4113 // Build the overload candidate set
4114 OverloadCandidateSet CandidateSet;
4115 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4116 CandidateSet);
4117
4118 // Determine whether we found a constructor we can use.
4119 OverloadCandidateSet::iterator Best;
4120 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4121 case OR_Success:
4122 case OR_Deleted:
4123 // We found a constructor. Return it.
4124 return cast<CXXConstructorDecl>(Best->Function);
4125
4126 case OR_No_Viable_Function:
4127 case OR_Ambiguous:
4128 // Overload resolution failed. Return nothing.
4129 return 0;
4130 }
4131
4132 // Silence GCC warning
4133 return 0;
4134}
4135
Douglas Gregor39da0b82009-09-09 23:08:42 +00004136/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4137/// may occur as part of direct-initialization or copy-initialization.
4138///
4139/// \param ClassType the type of the object being initialized, which must have
4140/// class type.
4141///
4142/// \param ArgsPtr the arguments provided to initialize the object
4143///
4144/// \param Loc the source location where the initialization occurs
4145///
4146/// \param Range the source range that covers the entire initialization
4147///
4148/// \param InitEntity the name of the entity being initialized, if known
4149///
4150/// \param Kind the type of initialization being performed
4151///
4152/// \param ConvertedArgs a vector that will be filled in with the
4153/// appropriately-converted arguments to the constructor (if initialization
4154/// succeeded).
4155///
4156/// \returns the constructor used to initialize the object, if successful.
4157/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004158CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004159Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004160 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004161 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004162 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004163 InitializationKind Kind,
4164 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004165
4166 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004167 Expr **Args = (Expr **)ArgsPtr.get();
4168 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004169 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004170 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4171 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004172
Douglas Gregor18fe5682008-11-03 20:45:27 +00004173 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004174 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004175 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004176 // We found a constructor. Break out so that we can convert the arguments
4177 // appropriately.
4178 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004179
Douglas Gregor18fe5682008-11-03 20:45:27 +00004180 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004181 if (InitEntity)
4182 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004183 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004184 else
4185 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004186 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00004187 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004188 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004189
Douglas Gregor18fe5682008-11-03 20:45:27 +00004190 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004191 if (InitEntity)
4192 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4193 else
4194 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004195 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4196 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004197
4198 case OR_Deleted:
4199 if (InitEntity)
4200 Diag(Loc, diag::err_ovl_deleted_init)
4201 << Best->Function->isDeleted()
4202 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004203 else {
4204 const CXXRecordDecl *RD =
4205 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004206 Diag(Loc, diag::err_ovl_deleted_init)
4207 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004208 << RD->getDeclName() << Range;
4209 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004210 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4211 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004212 }
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Douglas Gregor39da0b82009-09-09 23:08:42 +00004214 // Convert the arguments, fill in default arguments, etc.
4215 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4216 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4217 return 0;
4218
4219 return Constructor;
4220}
4221
4222/// \brief Given a constructor and the set of arguments provided for the
4223/// constructor, convert the arguments and add any required default arguments
4224/// to form a proper call to this constructor.
4225///
4226/// \returns true if an error occurred, false otherwise.
4227bool
4228Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4229 MultiExprArg ArgsPtr,
4230 SourceLocation Loc,
4231 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4232 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4233 unsigned NumArgs = ArgsPtr.size();
4234 Expr **Args = (Expr **)ArgsPtr.get();
4235
4236 const FunctionProtoType *Proto
4237 = Constructor->getType()->getAs<FunctionProtoType>();
4238 assert(Proto && "Constructor without a prototype?");
4239 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004240
4241 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004242 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004243 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004244 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004245 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004246
4247 VariadicCallType CallType =
4248 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4249 llvm::SmallVector<Expr *, 8> AllArgs;
4250 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4251 Proto, 0, Args, NumArgs, AllArgs,
4252 CallType);
4253 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4254 ConvertedArgs.push_back(AllArgs[i]);
4255 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004256}
4257
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004258/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4259/// determine whether they are reference-related,
4260/// reference-compatible, reference-compatible with added
4261/// qualification, or incompatible, for use in C++ initialization by
4262/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4263/// type, and the first type (T1) is the pointee type of the reference
4264/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004265Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004266Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004267 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004268 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004269 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004270 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004271 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004272
Douglas Gregor393896f2009-11-05 13:06:35 +00004273 QualType T1 = Context.getCanonicalType(OrigT1);
4274 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004275 Qualifiers T1Quals, T2Quals;
4276 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4277 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004278
4279 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004280 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004281 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004282 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004283 if (UnqualT1 == UnqualT2)
4284 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004285 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4286 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4287 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004288 DerivedToBase = true;
4289 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004290 return Ref_Incompatible;
4291
4292 // At this point, we know that T1 and T2 are reference-related (at
4293 // least).
4294
Chandler Carruth28e318c2009-12-29 07:16:59 +00004295 // If the type is an array type, promote the element qualifiers to the type
4296 // for comparison.
4297 if (isa<ArrayType>(T1) && T1Quals)
4298 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4299 if (isa<ArrayType>(T2) && T2Quals)
4300 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4301
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004302 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004303 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004304 // reference-related to T2 and cv1 is the same cv-qualification
4305 // as, or greater cv-qualification than, cv2. For purposes of
4306 // overload resolution, cases for which cv1 is greater
4307 // cv-qualification than cv2 are identified as
4308 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004309 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004310 return Ref_Compatible;
4311 else if (T1.isMoreQualifiedThan(T2))
4312 return Ref_Compatible_With_Added_Qualification;
4313 else
4314 return Ref_Related;
4315}
4316
4317/// CheckReferenceInit - Check the initialization of a reference
4318/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4319/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004320/// list), and DeclType is the type of the declaration. When ICS is
4321/// non-null, this routine will compute the implicit conversion
4322/// sequence according to C++ [over.ics.ref] and will not produce any
4323/// diagnostics; when ICS is null, it will emit diagnostics when any
4324/// errors are found. Either way, a return value of true indicates
4325/// that there was a failure, a return value of false indicates that
4326/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004327///
4328/// When @p SuppressUserConversions, user-defined conversions are
4329/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004330/// When @p AllowExplicit, we also permit explicit user-defined
4331/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004332/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004333/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4334/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004335bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004336Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004337 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004338 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004339 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004340 ImplicitConversionSequence *ICS,
4341 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004342 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4343
Ted Kremenek6217b802009-07-29 21:53:49 +00004344 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004345 QualType T2 = Init->getType();
4346
Douglas Gregor904eed32008-11-10 20:40:00 +00004347 // If the initializer is the address of an overloaded function, try
4348 // to resolve the overloaded function. If all goes well, T2 is the
4349 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004350 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004351 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004352 ICS != 0);
4353 if (Fn) {
4354 // Since we're performing this reference-initialization for
4355 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004356 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004357 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004358 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004359
Anders Carlsson96ad5332009-10-21 17:16:23 +00004360 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004361 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004362
4363 T2 = Fn->getType();
4364 }
4365 }
4366
Douglas Gregor15da57e2008-10-29 02:00:59 +00004367 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004368 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004369 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004370 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4371 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004372 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004373 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004374
4375 // Most paths end in a failed conversion.
4376 if (ICS)
4377 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004378
4379 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004380 // A reference to type "cv1 T1" is initialized by an expression
4381 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004382
4383 // -- If the initializer expression
4384
Sebastian Redla9845802009-03-29 15:27:50 +00004385 // Rvalue references cannot bind to lvalues (N2812).
4386 // There is absolutely no situation where they can. In particular, note that
4387 // this is ill-formed, even if B has a user-defined conversion to A&&:
4388 // B b;
4389 // A&& r = b;
4390 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4391 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004392 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004393 << Init->getSourceRange();
4394 return true;
4395 }
4396
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004397 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004398 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4399 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004400 //
4401 // Note that the bit-field check is skipped if we are just computing
4402 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004403 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004404 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004405 BindsDirectly = true;
4406
Douglas Gregor15da57e2008-10-29 02:00:59 +00004407 if (ICS) {
4408 // C++ [over.ics.ref]p1:
4409 // When a parameter of reference type binds directly (8.5.3)
4410 // to an argument expression, the implicit conversion sequence
4411 // is the identity conversion, unless the argument expression
4412 // has a type that is a derived class of the parameter type,
4413 // in which case the implicit conversion sequence is a
4414 // derived-to-base Conversion (13.3.3.1).
4415 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4416 ICS->Standard.First = ICK_Identity;
4417 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4418 ICS->Standard.Third = ICK_Identity;
4419 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4420 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004421 ICS->Standard.ReferenceBinding = true;
4422 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004423 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004424 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004425
4426 // Nothing more to do: the inaccessibility/ambiguity check for
4427 // derived-to-base conversions is suppressed when we're
4428 // computing the implicit conversion sequence (C++
4429 // [over.best.ics]p2).
4430 return false;
4431 } else {
4432 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004433 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4434 if (DerivedToBase)
4435 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004436 else if(CheckExceptionSpecCompatibility(Init, T1))
4437 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004438 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004439 }
4440 }
4441
4442 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004443 // implicitly converted to an lvalue of type "cv3 T3,"
4444 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004445 // 92) (this conversion is selected by enumerating the
4446 // applicable conversion functions (13.3.1.6) and choosing
4447 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004448 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004449 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004450 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004451 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004452
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004453 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00004454 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004455 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00004456 for (UnresolvedSet::iterator I = Conversions->begin(),
4457 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004458 NamedDecl *D = *I;
4459 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4460 if (isa<UsingShadowDecl>(D))
4461 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4462
Mike Stump1eb44332009-09-09 15:08:12 +00004463 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004464 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004465 CXXConversionDecl *Conv;
4466 if (ConvTemplate)
4467 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4468 else
John McCall701c89e2009-12-03 04:06:58 +00004469 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004470
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004471 // If the conversion function doesn't return a reference type,
4472 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004473 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004474 (AllowExplicit || !Conv->isExplicit())) {
4475 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00004476 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4477 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004478 else
John McCall701c89e2009-12-03 04:06:58 +00004479 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004480 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004481 }
4482
4483 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004484 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004485 case OR_Success:
4486 // This is a direct binding.
4487 BindsDirectly = true;
4488
4489 if (ICS) {
4490 // C++ [over.ics.ref]p1:
4491 //
4492 // [...] If the parameter binds directly to the result of
4493 // applying a conversion function to the argument
4494 // expression, the implicit conversion sequence is a
4495 // user-defined conversion sequence (13.3.3.1.2), with the
4496 // second standard conversion sequence either an identity
4497 // conversion or, if the conversion function returns an
4498 // entity of a type that is a derived class of the parameter
4499 // type, a derived-to-base Conversion.
4500 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4501 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4502 ICS->UserDefined.After = Best->FinalConversion;
4503 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004504 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004505 assert(ICS->UserDefined.After.ReferenceBinding &&
4506 ICS->UserDefined.After.DirectBinding &&
4507 "Expected a direct reference binding!");
4508 return false;
4509 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004510 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004511 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004512 CastExpr::CK_UserDefinedConversion,
4513 cast<CXXMethodDecl>(Best->Function),
4514 Owned(Init));
4515 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004516
4517 if (CheckExceptionSpecCompatibility(Init, T1))
4518 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004519 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4520 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004521 }
4522 break;
4523
4524 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004525 if (ICS) {
4526 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4527 Cand != CandidateSet.end(); ++Cand)
4528 if (Cand->Viable)
4529 ICS->ConversionFunctionSet.push_back(Cand->Function);
4530 break;
4531 }
4532 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4533 << Init->getSourceRange();
4534 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004535 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004537 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004538 case OR_Deleted:
4539 // There was no suitable conversion, or we found a deleted
4540 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004541 break;
4542 }
4543 }
Mike Stump1eb44332009-09-09 15:08:12 +00004544
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004545 if (BindsDirectly) {
4546 // C++ [dcl.init.ref]p4:
4547 // [...] In all cases where the reference-related or
4548 // reference-compatible relationship of two types is used to
4549 // establish the validity of a reference binding, and T1 is a
4550 // base class of T2, a program that necessitates such a binding
4551 // is ill-formed if T1 is an inaccessible (clause 11) or
4552 // ambiguous (10.2) base class of T2.
4553 //
4554 // Note that we only check this condition when we're allowed to
4555 // complain about errors, because we should not be checking for
4556 // ambiguity (or inaccessibility) unless the reference binding
4557 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004558 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004559 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004560 Init->getSourceRange(),
4561 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004562 else
4563 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004564 }
4565
4566 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004567 // type (i.e., cv1 shall be const), or the reference shall be an
4568 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004569 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004570 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004571 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004572 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004573 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004574 return true;
4575 }
4576
4577 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004578 // class type, and "cv1 T1" is reference-compatible with
4579 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004580 // following ways (the choice is implementation-defined):
4581 //
4582 // -- The reference is bound to the object represented by
4583 // the rvalue (see 3.10) or to a sub-object within that
4584 // object.
4585 //
Eli Friedman33a31382009-08-05 19:21:58 +00004586 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004587 // a constructor is called to copy the entire rvalue
4588 // object into the temporary. The reference is bound to
4589 // the temporary or to a sub-object within the
4590 // temporary.
4591 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004592 // The constructor that would be used to make the copy
4593 // shall be callable whether or not the copy is actually
4594 // done.
4595 //
Sebastian Redla9845802009-03-29 15:27:50 +00004596 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004597 // freedom, so we will always take the first option and never build
4598 // a temporary in this case. FIXME: We will, however, have to check
4599 // for the presence of a copy constructor in C++98/03 mode.
4600 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004601 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4602 if (ICS) {
4603 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4604 ICS->Standard.First = ICK_Identity;
4605 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4606 ICS->Standard.Third = ICK_Identity;
4607 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4608 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004609 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004610 ICS->Standard.DirectBinding = false;
4611 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004612 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004613 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004614 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4615 if (DerivedToBase)
4616 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004617 else if(CheckExceptionSpecCompatibility(Init, T1))
4618 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004619 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004620 }
4621 return false;
4622 }
4623
Eli Friedman33a31382009-08-05 19:21:58 +00004624 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004625 // initialized from the initializer expression using the
4626 // rules for a non-reference copy initialization (8.5). The
4627 // reference is then bound to the temporary. If T1 is
4628 // reference-related to T2, cv1 must be the same
4629 // cv-qualification as, or greater cv-qualification than,
4630 // cv2; otherwise, the program is ill-formed.
4631 if (RefRelationship == Ref_Related) {
4632 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4633 // we would be reference-compatible or reference-compatible with
4634 // added qualification. But that wasn't the case, so the reference
4635 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004636 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004637 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004638 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004639 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004640 return true;
4641 }
4642
Douglas Gregor734d9862009-01-30 23:27:23 +00004643 // If at least one of the types is a class type, the types are not
4644 // related, and we aren't allowed any user conversions, the
4645 // reference binding fails. This case is important for breaking
4646 // recursion, since TryImplicitConversion below will attempt to
4647 // create a temporary through the use of a copy constructor.
4648 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4649 (T1->isRecordType() || T2->isRecordType())) {
4650 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004651 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004652 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004653 return true;
4654 }
4655
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004656 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004657 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004658 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004659 //
Sebastian Redla9845802009-03-29 15:27:50 +00004660 // When a parameter of reference type is not bound directly to
4661 // an argument expression, the conversion sequence is the one
4662 // required to convert the argument expression to the
4663 // underlying type of the reference according to
4664 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4665 // to copy-initializing a temporary of the underlying type with
4666 // the argument expression. Any difference in top-level
4667 // cv-qualification is subsumed by the initialization itself
4668 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004669 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4670 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004671 /*ForceRValue=*/false,
4672 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Sebastian Redla9845802009-03-29 15:27:50 +00004674 // Of course, that's still a reference binding.
4675 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4676 ICS->Standard.ReferenceBinding = true;
4677 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004678 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004679 ImplicitConversionSequence::UserDefinedConversion) {
4680 ICS->UserDefined.After.ReferenceBinding = true;
4681 ICS->UserDefined.After.RRefBinding = isRValRef;
4682 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004683 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4684 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004685 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004686 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004687 false, false,
4688 Conversions);
4689 if (badConversion) {
4690 if ((Conversions.ConversionKind ==
4691 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004692 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004693 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004694 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4695 for (int j = Conversions.ConversionFunctionSet.size()-1;
4696 j >= 0; j--) {
4697 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
John McCallb1622a12010-01-06 09:43:14 +00004698 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004699 }
4700 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004701 else {
4702 if (isRValRef)
4703 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4704 << Init->getSourceRange();
4705 else
4706 Diag(DeclLoc, diag::err_invalid_initialization)
4707 << DeclType << Init->getType() << Init->getSourceRange();
4708 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004709 }
4710 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004711 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004712}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004713
Anders Carlsson20d45d22009-12-12 00:32:00 +00004714static inline bool
4715CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4716 const FunctionDecl *FnDecl) {
4717 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4718 if (isa<NamespaceDecl>(DC)) {
4719 return SemaRef.Diag(FnDecl->getLocation(),
4720 diag::err_operator_new_delete_declared_in_namespace)
4721 << FnDecl->getDeclName();
4722 }
4723
4724 if (isa<TranslationUnitDecl>(DC) &&
4725 FnDecl->getStorageClass() == FunctionDecl::Static) {
4726 return SemaRef.Diag(FnDecl->getLocation(),
4727 diag::err_operator_new_delete_declared_static)
4728 << FnDecl->getDeclName();
4729 }
4730
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004731 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004732}
4733
Anders Carlsson156c78e2009-12-13 17:53:43 +00004734static inline bool
4735CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4736 CanQualType ExpectedResultType,
4737 CanQualType ExpectedFirstParamType,
4738 unsigned DependentParamTypeDiag,
4739 unsigned InvalidParamTypeDiag) {
4740 QualType ResultType =
4741 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4742
4743 // Check that the result type is not dependent.
4744 if (ResultType->isDependentType())
4745 return SemaRef.Diag(FnDecl->getLocation(),
4746 diag::err_operator_new_delete_dependent_result_type)
4747 << FnDecl->getDeclName() << ExpectedResultType;
4748
4749 // Check that the result type is what we expect.
4750 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4751 return SemaRef.Diag(FnDecl->getLocation(),
4752 diag::err_operator_new_delete_invalid_result_type)
4753 << FnDecl->getDeclName() << ExpectedResultType;
4754
4755 // A function template must have at least 2 parameters.
4756 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4757 return SemaRef.Diag(FnDecl->getLocation(),
4758 diag::err_operator_new_delete_template_too_few_parameters)
4759 << FnDecl->getDeclName();
4760
4761 // The function decl must have at least 1 parameter.
4762 if (FnDecl->getNumParams() == 0)
4763 return SemaRef.Diag(FnDecl->getLocation(),
4764 diag::err_operator_new_delete_too_few_parameters)
4765 << FnDecl->getDeclName();
4766
4767 // Check the the first parameter type is not dependent.
4768 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4769 if (FirstParamType->isDependentType())
4770 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4771 << FnDecl->getDeclName() << ExpectedFirstParamType;
4772
4773 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004774 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004775 ExpectedFirstParamType)
4776 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4777 << FnDecl->getDeclName() << ExpectedFirstParamType;
4778
4779 return false;
4780}
4781
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004782static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004783CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004784 // C++ [basic.stc.dynamic.allocation]p1:
4785 // A program is ill-formed if an allocation function is declared in a
4786 // namespace scope other than global scope or declared static in global
4787 // scope.
4788 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4789 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004790
4791 CanQualType SizeTy =
4792 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4793
4794 // C++ [basic.stc.dynamic.allocation]p1:
4795 // The return type shall be void*. The first parameter shall have type
4796 // std::size_t.
4797 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4798 SizeTy,
4799 diag::err_operator_new_dependent_param_type,
4800 diag::err_operator_new_param_type))
4801 return true;
4802
4803 // C++ [basic.stc.dynamic.allocation]p1:
4804 // The first parameter shall not have an associated default argument.
4805 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004806 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004807 diag::err_operator_new_default_arg)
4808 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4809
4810 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004811}
4812
4813static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004814CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4815 // C++ [basic.stc.dynamic.deallocation]p1:
4816 // A program is ill-formed if deallocation functions are declared in a
4817 // namespace scope other than global scope or declared static in global
4818 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004819 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4820 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004821
4822 // C++ [basic.stc.dynamic.deallocation]p2:
4823 // Each deallocation function shall return void and its first parameter
4824 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004825 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4826 SemaRef.Context.VoidPtrTy,
4827 diag::err_operator_delete_dependent_param_type,
4828 diag::err_operator_delete_param_type))
4829 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004830
Anders Carlsson46991d62009-12-12 00:16:02 +00004831 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4832 if (FirstParamType->isDependentType())
4833 return SemaRef.Diag(FnDecl->getLocation(),
4834 diag::err_operator_delete_dependent_param_type)
4835 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4836
4837 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4838 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004839 return SemaRef.Diag(FnDecl->getLocation(),
4840 diag::err_operator_delete_param_type)
4841 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004842
4843 return false;
4844}
4845
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004846/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4847/// of this overloaded operator is well-formed. If so, returns false;
4848/// otherwise, emits appropriate diagnostics and returns true.
4849bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004850 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004851 "Expected an overloaded operator declaration");
4852
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004853 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4854
Mike Stump1eb44332009-09-09 15:08:12 +00004855 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004856 // The allocation and deallocation functions, operator new,
4857 // operator new[], operator delete and operator delete[], are
4858 // described completely in 3.7.3. The attributes and restrictions
4859 // found in the rest of this subclause do not apply to them unless
4860 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004861 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004862 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004863
Anders Carlssona3ccda52009-12-12 00:26:23 +00004864 if (Op == OO_New || Op == OO_Array_New)
4865 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004866
4867 // C++ [over.oper]p6:
4868 // An operator function shall either be a non-static member
4869 // function or be a non-member function and have at least one
4870 // parameter whose type is a class, a reference to a class, an
4871 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004872 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4873 if (MethodDecl->isStatic())
4874 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004875 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004876 } else {
4877 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004878 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4879 ParamEnd = FnDecl->param_end();
4880 Param != ParamEnd; ++Param) {
4881 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004882 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4883 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004884 ClassOrEnumParam = true;
4885 break;
4886 }
4887 }
4888
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004889 if (!ClassOrEnumParam)
4890 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004891 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004892 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004893 }
4894
4895 // C++ [over.oper]p8:
4896 // An operator function cannot have default arguments (8.3.6),
4897 // except where explicitly stated below.
4898 //
Mike Stump1eb44332009-09-09 15:08:12 +00004899 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004900 // (C++ [over.call]p1).
4901 if (Op != OO_Call) {
4902 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4903 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004904 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004905 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004906 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004907 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004908 }
4909 }
4910
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004911 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4912 { false, false, false }
4913#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4914 , { Unary, Binary, MemberOnly }
4915#include "clang/Basic/OperatorKinds.def"
4916 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004917
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004918 bool CanBeUnaryOperator = OperatorUses[Op][0];
4919 bool CanBeBinaryOperator = OperatorUses[Op][1];
4920 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004921
4922 // C++ [over.oper]p8:
4923 // [...] Operator functions cannot have more or fewer parameters
4924 // than the number required for the corresponding operator, as
4925 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004926 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004927 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004928 if (Op != OO_Call &&
4929 ((NumParams == 1 && !CanBeUnaryOperator) ||
4930 (NumParams == 2 && !CanBeBinaryOperator) ||
4931 (NumParams < 1) || (NumParams > 2))) {
4932 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004933 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004934 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004935 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004936 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004937 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004938 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004939 assert(CanBeBinaryOperator &&
4940 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004941 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004942 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004943
Chris Lattner416e46f2008-11-21 07:57:12 +00004944 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004945 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004946 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004947
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004948 // Overloaded operators other than operator() cannot be variadic.
4949 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004950 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004951 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004952 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004953 }
4954
4955 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004956 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4957 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004958 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004959 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004960 }
4961
4962 // C++ [over.inc]p1:
4963 // The user-defined function called operator++ implements the
4964 // prefix and postfix ++ operator. If this function is a member
4965 // function with no parameters, or a non-member function with one
4966 // parameter of class or enumeration type, it defines the prefix
4967 // increment operator ++ for objects of that type. If the function
4968 // is a member function with one parameter (which shall be of type
4969 // int) or a non-member function with two parameters (the second
4970 // of which shall be of type int), it defines the postfix
4971 // increment operator ++ for objects of that type.
4972 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4973 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4974 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004975 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004976 ParamIsInt = BT->getKind() == BuiltinType::Int;
4977
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004978 if (!ParamIsInt)
4979 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004980 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004981 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004982 }
4983
Sebastian Redl64b45f72009-01-05 20:52:13 +00004984 // Notify the class if it got an assignment operator.
4985 if (Op == OO_Equal) {
4986 // Would have returned earlier otherwise.
4987 assert(isa<CXXMethodDecl>(FnDecl) &&
4988 "Overloaded = not member, but not filtered.");
4989 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4990 Method->getParent()->addedAssignmentOperator(Context, Method);
4991 }
4992
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004993 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004994}
Chris Lattner5a003a42008-12-17 07:09:26 +00004995
Douglas Gregor074149e2009-01-05 19:45:36 +00004996/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4997/// linkage specification, including the language and (if present)
4998/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4999/// the location of the language string literal, which is provided
5000/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5001/// the '{' brace. Otherwise, this linkage specification does not
5002/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005003Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5004 SourceLocation ExternLoc,
5005 SourceLocation LangLoc,
5006 const char *Lang,
5007 unsigned StrSize,
5008 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005009 LinkageSpecDecl::LanguageIDs Language;
5010 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5011 Language = LinkageSpecDecl::lang_c;
5012 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5013 Language = LinkageSpecDecl::lang_cxx;
5014 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005015 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005016 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005017 }
Mike Stump1eb44332009-09-09 15:08:12 +00005018
Chris Lattnercc98eac2008-12-17 07:13:27 +00005019 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005020
Douglas Gregor074149e2009-01-05 19:45:36 +00005021 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005022 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005023 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005024 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005025 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005026 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005027}
5028
Douglas Gregor074149e2009-01-05 19:45:36 +00005029/// ActOnFinishLinkageSpecification - Completely the definition of
5030/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5031/// valid, it's the position of the closing '}' brace in a linkage
5032/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005033Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5034 DeclPtrTy LinkageSpec,
5035 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005036 if (LinkageSpec)
5037 PopDeclContext();
5038 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005039}
5040
Douglas Gregord308e622009-05-18 20:51:54 +00005041/// \brief Perform semantic analysis for the variable declaration that
5042/// occurs within a C++ catch clause, returning the newly-created
5043/// variable.
5044VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005045 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005046 IdentifierInfo *Name,
5047 SourceLocation Loc,
5048 SourceRange Range) {
5049 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005050
5051 // Arrays and functions decay.
5052 if (ExDeclType->isArrayType())
5053 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5054 else if (ExDeclType->isFunctionType())
5055 ExDeclType = Context.getPointerType(ExDeclType);
5056
5057 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5058 // The exception-declaration shall not denote a pointer or reference to an
5059 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005060 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005061 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005062 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005063 Invalid = true;
5064 }
Douglas Gregord308e622009-05-18 20:51:54 +00005065
Sebastian Redl4b07b292008-12-22 19:15:10 +00005066 QualType BaseType = ExDeclType;
5067 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005068 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005069 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005070 BaseType = Ptr->getPointeeType();
5071 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005072 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005073 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005074 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005075 BaseType = Ref->getPointeeType();
5076 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005077 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005078 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005079 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005080 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005081 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005082
Mike Stump1eb44332009-09-09 15:08:12 +00005083 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005084 RequireNonAbstractType(Loc, ExDeclType,
5085 diag::err_abstract_type_in_decl,
5086 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005087 Invalid = true;
5088
Douglas Gregord308e622009-05-18 20:51:54 +00005089 // FIXME: Need to test for ability to copy-construct and destroy the
5090 // exception variable.
5091
Sebastian Redl8351da02008-12-22 21:35:02 +00005092 // FIXME: Need to check for abstract classes.
5093
Mike Stump1eb44332009-09-09 15:08:12 +00005094 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005095 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005096
5097 if (Invalid)
5098 ExDecl->setInvalidDecl();
5099
5100 return ExDecl;
5101}
5102
5103/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5104/// handler.
5105Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005106 TypeSourceInfo *TInfo = 0;
5107 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005108
5109 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005110 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005111 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005112 // The scope should be freshly made just for us. There is just no way
5113 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005114 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005115 if (PrevDecl->isTemplateParameter()) {
5116 // Maybe we will complain about the shadowed template parameter.
5117 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005118 }
5119 }
5120
Chris Lattnereaaebc72009-04-25 08:06:05 +00005121 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005122 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5123 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005124 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005125 }
5126
John McCalla93c9342009-12-07 02:54:59 +00005127 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005128 D.getIdentifier(),
5129 D.getIdentifierLoc(),
5130 D.getDeclSpec().getSourceRange());
5131
Chris Lattnereaaebc72009-04-25 08:06:05 +00005132 if (Invalid)
5133 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005134
Sebastian Redl4b07b292008-12-22 19:15:10 +00005135 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005136 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005137 PushOnScopeChains(ExDecl, S);
5138 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005139 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005140
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005141 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005142 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005143}
Anders Carlssonfb311762009-03-14 00:25:26 +00005144
Mike Stump1eb44332009-09-09 15:08:12 +00005145Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005146 ExprArg assertexpr,
5147 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005148 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005149 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005150 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5151
Anders Carlssonc3082412009-03-14 00:33:21 +00005152 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5153 llvm::APSInt Value(32);
5154 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5155 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5156 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005157 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005158 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005159
Anders Carlssonc3082412009-03-14 00:33:21 +00005160 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005161 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005162 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005163 }
5164 }
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Anders Carlsson77d81422009-03-15 17:35:16 +00005166 assertexpr.release();
5167 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005168 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005169 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005170
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005171 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005172 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005173}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005174
John McCalldd4a3b02009-09-16 22:47:08 +00005175/// Handle a friend type declaration. This works in tandem with
5176/// ActOnTag.
5177///
5178/// Notes on friend class templates:
5179///
5180/// We generally treat friend class declarations as if they were
5181/// declaring a class. So, for example, the elaborated type specifier
5182/// in a friend declaration is required to obey the restrictions of a
5183/// class-head (i.e. no typedefs in the scope chain), template
5184/// parameters are required to match up with simple template-ids, &c.
5185/// However, unlike when declaring a template specialization, it's
5186/// okay to refer to a template specialization without an empty
5187/// template parameter declaration, e.g.
5188/// friend class A<T>::B<unsigned>;
5189/// We permit this as a special case; if there are any template
5190/// parameters present at all, require proper matching, i.e.
5191/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005192Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005193 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005194 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005195
5196 assert(DS.isFriendSpecified());
5197 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5198
John McCalldd4a3b02009-09-16 22:47:08 +00005199 // Try to convert the decl specifier to a type. This works for
5200 // friend templates because ActOnTag never produces a ClassTemplateDecl
5201 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005202 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005203 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5204 if (TheDeclarator.isInvalidType())
5205 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005206
John McCalldd4a3b02009-09-16 22:47:08 +00005207 // This is definitely an error in C++98. It's probably meant to
5208 // be forbidden in C++0x, too, but the specification is just
5209 // poorly written.
5210 //
5211 // The problem is with declarations like the following:
5212 // template <T> friend A<T>::foo;
5213 // where deciding whether a class C is a friend or not now hinges
5214 // on whether there exists an instantiation of A that causes
5215 // 'foo' to equal C. There are restrictions on class-heads
5216 // (which we declare (by fiat) elaborated friend declarations to
5217 // be) that makes this tractable.
5218 //
5219 // FIXME: handle "template <> friend class A<T>;", which
5220 // is possibly well-formed? Who even knows?
5221 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5222 Diag(Loc, diag::err_tagless_friend_type_template)
5223 << DS.getSourceRange();
5224 return DeclPtrTy();
5225 }
5226
John McCall02cace72009-08-28 07:59:38 +00005227 // C++ [class.friend]p2:
5228 // An elaborated-type-specifier shall be used in a friend declaration
5229 // for a class.*
5230 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005231 // This is one of the rare places in Clang where it's legitimate to
5232 // ask about the "spelling" of the type.
5233 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5234 // If we evaluated the type to a record type, suggest putting
5235 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005236 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005237 RecordDecl *RD = RT->getDecl();
5238
5239 std::string InsertionText = std::string(" ") + RD->getKindName();
5240
John McCalle3af0232009-10-07 23:34:25 +00005241 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5242 << (unsigned) RD->getTagKind()
5243 << T
5244 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005245 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5246 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005247 return DeclPtrTy();
5248 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005249 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5250 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005251 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005252 }
5253 }
5254
John McCalle3af0232009-10-07 23:34:25 +00005255 // Enum types cannot be friends.
5256 if (T->getAs<EnumType>()) {
5257 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5258 << SourceRange(DS.getFriendSpecLoc());
5259 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005260 }
John McCall02cace72009-08-28 07:59:38 +00005261
John McCall02cace72009-08-28 07:59:38 +00005262 // C++98 [class.friend]p1: A friend of a class is a function
5263 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005264 // This is fixed in DR77, which just barely didn't make the C++03
5265 // deadline. It's also a very silly restriction that seriously
5266 // affects inner classes and which nobody else seems to implement;
5267 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005268
John McCalldd4a3b02009-09-16 22:47:08 +00005269 Decl *D;
5270 if (TempParams.size())
5271 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5272 TempParams.size(),
5273 (TemplateParameterList**) TempParams.release(),
5274 T.getTypePtr(),
5275 DS.getFriendSpecLoc());
5276 else
5277 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5278 DS.getFriendSpecLoc());
5279 D->setAccess(AS_public);
5280 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005281
John McCalldd4a3b02009-09-16 22:47:08 +00005282 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005283}
5284
John McCallbbbcdd92009-09-11 21:02:39 +00005285Sema::DeclPtrTy
5286Sema::ActOnFriendFunctionDecl(Scope *S,
5287 Declarator &D,
5288 bool IsDefinition,
5289 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005290 const DeclSpec &DS = D.getDeclSpec();
5291
5292 assert(DS.isFriendSpecified());
5293 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5294
5295 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005296 TypeSourceInfo *TInfo = 0;
5297 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005298
5299 // C++ [class.friend]p1
5300 // A friend of a class is a function or class....
5301 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005302 // It *doesn't* see through dependent types, which is correct
5303 // according to [temp.arg.type]p3:
5304 // If a declaration acquires a function type through a
5305 // type dependent on a template-parameter and this causes
5306 // a declaration that does not use the syntactic form of a
5307 // function declarator to have a function type, the program
5308 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005309 if (!T->isFunctionType()) {
5310 Diag(Loc, diag::err_unexpected_friend);
5311
5312 // It might be worthwhile to try to recover by creating an
5313 // appropriate declaration.
5314 return DeclPtrTy();
5315 }
5316
5317 // C++ [namespace.memdef]p3
5318 // - If a friend declaration in a non-local class first declares a
5319 // class or function, the friend class or function is a member
5320 // of the innermost enclosing namespace.
5321 // - The name of the friend is not found by simple name lookup
5322 // until a matching declaration is provided in that namespace
5323 // scope (either before or after the class declaration granting
5324 // friendship).
5325 // - If a friend function is called, its name may be found by the
5326 // name lookup that considers functions from namespaces and
5327 // classes associated with the types of the function arguments.
5328 // - When looking for a prior declaration of a class or a function
5329 // declared as a friend, scopes outside the innermost enclosing
5330 // namespace scope are not considered.
5331
John McCall02cace72009-08-28 07:59:38 +00005332 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5333 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005334 assert(Name);
5335
John McCall67d1a672009-08-06 02:15:43 +00005336 // The context we found the declaration in, or in which we should
5337 // create the declaration.
5338 DeclContext *DC;
5339
5340 // FIXME: handle local classes
5341
5342 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005343 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5344 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005345 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005346 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005347 DC = computeDeclContext(ScopeQual);
5348
5349 // FIXME: handle dependent contexts
5350 if (!DC) return DeclPtrTy();
5351
John McCall68263142009-11-18 22:49:29 +00005352 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005353
5354 // If searching in that context implicitly found a declaration in
5355 // a different context, treat it like it wasn't found at all.
5356 // TODO: better diagnostics for this case. Suggesting the right
5357 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005358 // FIXME: getRepresentativeDecl() is not right here at all
5359 if (Previous.empty() ||
5360 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005361 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005362 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5363 return DeclPtrTy();
5364 }
5365
5366 // C++ [class.friend]p1: A friend of a class is a function or
5367 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005368 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005369 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5370
John McCall67d1a672009-08-06 02:15:43 +00005371 // Otherwise walk out to the nearest namespace scope looking for matches.
5372 } else {
5373 // TODO: handle local class contexts.
5374
5375 DC = CurContext;
5376 while (true) {
5377 // Skip class contexts. If someone can cite chapter and verse
5378 // for this behavior, that would be nice --- it's what GCC and
5379 // EDG do, and it seems like a reasonable intent, but the spec
5380 // really only says that checks for unqualified existing
5381 // declarations should stop at the nearest enclosing namespace,
5382 // not that they should only consider the nearest enclosing
5383 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005384 while (DC->isRecord())
5385 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005386
John McCall68263142009-11-18 22:49:29 +00005387 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005388
5389 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005390 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005391 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005392
John McCall67d1a672009-08-06 02:15:43 +00005393 if (DC->isFileContext()) break;
5394 DC = DC->getParent();
5395 }
5396
5397 // C++ [class.friend]p1: A friend of a class is a function or
5398 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005399 // C++0x changes this for both friend types and functions.
5400 // Most C++ 98 compilers do seem to give an error here, so
5401 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005402 if (!Previous.empty() && DC->Equals(CurContext)
5403 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005404 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5405 }
5406
Douglas Gregor182ddf02009-09-28 00:08:27 +00005407 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005408 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005409 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5410 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5411 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005412 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005413 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5414 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005415 return DeclPtrTy();
5416 }
John McCall67d1a672009-08-06 02:15:43 +00005417 }
5418
Douglas Gregor182ddf02009-09-28 00:08:27 +00005419 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005420 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005421 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005422 IsDefinition,
5423 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005424 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005425
Douglas Gregor182ddf02009-09-28 00:08:27 +00005426 assert(ND->getDeclContext() == DC);
5427 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005428
John McCallab88d972009-08-31 22:39:49 +00005429 // Add the function declaration to the appropriate lookup tables,
5430 // adjusting the redeclarations list as necessary. We don't
5431 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005432 //
John McCallab88d972009-08-31 22:39:49 +00005433 // Also update the scope-based lookup if the target context's
5434 // lookup context is in lexical scope.
5435 if (!CurContext->isDependentContext()) {
5436 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005437 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005438 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005439 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005440 }
John McCall02cace72009-08-28 07:59:38 +00005441
5442 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005443 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005444 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005445 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005446 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005447
Douglas Gregor7557a132009-12-24 20:56:24 +00005448 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5449 FrD->setSpecialization(true);
5450
Douglas Gregor182ddf02009-09-28 00:08:27 +00005451 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005452}
5453
Chris Lattnerb28317a2009-03-28 19:18:32 +00005454void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005455 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005456
Chris Lattnerb28317a2009-03-28 19:18:32 +00005457 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005458 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5459 if (!Fn) {
5460 Diag(DelLoc, diag::err_deleted_non_function);
5461 return;
5462 }
5463 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5464 Diag(DelLoc, diag::err_deleted_decl_not_first);
5465 Diag(Prev->getLocation(), diag::note_previous_declaration);
5466 // If the declaration wasn't the first, we delete the function anyway for
5467 // recovery.
5468 }
5469 Fn->setDeleted();
5470}
Sebastian Redl13e88542009-04-27 21:33:24 +00005471
5472static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5473 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5474 ++CI) {
5475 Stmt *SubStmt = *CI;
5476 if (!SubStmt)
5477 continue;
5478 if (isa<ReturnStmt>(SubStmt))
5479 Self.Diag(SubStmt->getSourceRange().getBegin(),
5480 diag::err_return_in_constructor_handler);
5481 if (!isa<Expr>(SubStmt))
5482 SearchForReturnInStmt(Self, SubStmt);
5483 }
5484}
5485
5486void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5487 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5488 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5489 SearchForReturnInStmt(*this, Handler);
5490 }
5491}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005492
Mike Stump1eb44332009-09-09 15:08:12 +00005493bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005494 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005495 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5496 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005497
5498 QualType CNewTy = Context.getCanonicalType(NewTy);
5499 QualType COldTy = Context.getCanonicalType(OldTy);
5500
Mike Stump1eb44332009-09-09 15:08:12 +00005501 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00005502 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005503 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005504
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005505 // Check if the return types are covariant
5506 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005507
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005508 /// Both types must be pointers or references to classes.
5509 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5510 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5511 NewClassTy = NewPT->getPointeeType();
5512 OldClassTy = OldPT->getPointeeType();
5513 }
5514 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5515 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5516 NewClassTy = NewRT->getPointeeType();
5517 OldClassTy = OldRT->getPointeeType();
5518 }
5519 }
Mike Stump1eb44332009-09-09 15:08:12 +00005520
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005521 // The return types aren't either both pointers or references to a class type.
5522 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005523 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005524 diag::err_different_return_type_for_overriding_virtual_function)
5525 << New->getDeclName() << NewTy << OldTy;
5526 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005528 return true;
5529 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005530
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005531 // C++ [class.virtual]p6:
5532 // If the return type of D::f differs from the return type of B::f, the
5533 // class type in the return type of D::f shall be complete at the point of
5534 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005535 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5536 if (!RT->isBeingDefined() &&
5537 RequireCompleteType(New->getLocation(), NewClassTy,
5538 PDiag(diag::err_covariant_return_incomplete)
5539 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005540 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005541 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005542
Douglas Gregora4923eb2009-11-16 21:35:15 +00005543 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005544 // Check if the new class derives from the old class.
5545 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5546 Diag(New->getLocation(),
5547 diag::err_covariant_return_not_derived)
5548 << New->getDeclName() << NewTy << OldTy;
5549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5550 return true;
5551 }
Mike Stump1eb44332009-09-09 15:08:12 +00005552
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005553 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005554 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005555 diag::err_covariant_return_inaccessible_base,
5556 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5557 // FIXME: Should this point to the return type?
5558 New->getLocation(), SourceRange(), New->getDeclName())) {
5559 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5560 return true;
5561 }
5562 }
Mike Stump1eb44332009-09-09 15:08:12 +00005563
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005564 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005565 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005566 Diag(New->getLocation(),
5567 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005568 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005569 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5570 return true;
5571 };
Mike Stump1eb44332009-09-09 15:08:12 +00005572
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005573
5574 // The new class type must have the same or less qualifiers as the old type.
5575 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5576 Diag(New->getLocation(),
5577 diag::err_covariant_return_type_class_type_more_qualified)
5578 << New->getDeclName() << NewTy << OldTy;
5579 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5580 return true;
5581 };
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005583 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005584}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005585
Sean Huntbbd37c62009-11-21 08:43:09 +00005586bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5587 const CXXMethodDecl *Old)
5588{
5589 if (Old->hasAttr<FinalAttr>()) {
5590 Diag(New->getLocation(), diag::err_final_function_overridden)
5591 << New->getDeclName();
5592 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5593 return true;
5594 }
5595
5596 return false;
5597}
5598
Douglas Gregor4ba31362009-12-01 17:24:26 +00005599/// \brief Mark the given method pure.
5600///
5601/// \param Method the method to be marked pure.
5602///
5603/// \param InitRange the source range that covers the "0" initializer.
5604bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5605 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5606 Method->setPure();
5607
5608 // A class is abstract if at least one function is pure virtual.
5609 Method->getParent()->setAbstract(true);
5610 return false;
5611 }
5612
5613 if (!Method->isInvalidDecl())
5614 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5615 << Method->getDeclName() << InitRange;
5616 return true;
5617}
5618
John McCall731ad842009-12-19 09:28:58 +00005619/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5620/// an initializer for the out-of-line declaration 'Dcl'. The scope
5621/// is a fresh scope pushed for just this purpose.
5622///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005623/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5624/// static data member of class X, names should be looked up in the scope of
5625/// class X.
5626void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005627 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005628 Decl *D = Dcl.getAs<Decl>();
5629 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005630
John McCall731ad842009-12-19 09:28:58 +00005631 // We should only get called for declarations with scope specifiers, like:
5632 // int foo::bar;
5633 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005634 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005635}
5636
5637/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005638/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005639void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005640 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005641 Decl *D = Dcl.getAs<Decl>();
5642 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005643
John McCall731ad842009-12-19 09:28:58 +00005644 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005645 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005646}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005647
5648/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5649/// C++ if/switch/while/for statement.
5650/// e.g: "if (int x = f()) {...}"
5651Action::DeclResult
5652Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5653 // C++ 6.4p2:
5654 // The declarator shall not specify a function or an array.
5655 // The type-specifier-seq shall not contain typedef and shall not declare a
5656 // new class or enumeration.
5657 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5658 "Parser allowed 'typedef' as storage class of condition decl.");
5659
John McCalla93c9342009-12-07 02:54:59 +00005660 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005661 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005662 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005663
5664 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5665 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5666 // would be created and CXXConditionDeclExpr wants a VarDecl.
5667 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5668 << D.getSourceRange();
5669 return DeclResult();
5670 } else if (OwnedTag && OwnedTag->isDefinition()) {
5671 // The type-specifier-seq shall not declare a new class or enumeration.
5672 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5673 }
5674
5675 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5676 if (!Dcl)
5677 return DeclResult();
5678
5679 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5680 VD->setDeclaredInCondition(true);
5681 return Dcl;
5682}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005683
Anders Carlssond6a637f2009-12-07 08:24:59 +00005684void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5685 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005686 // Ignore dependent types.
5687 if (MD->isDependentContext())
5688 return;
5689
5690 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005691
5692 // Ignore classes without a vtable.
5693 if (!RD->isDynamicClass())
5694 return;
5695
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005696 // Only out-of-line definitions matter.
5697 if (!MD->isOutOfLine())
Anders Carlssond6a637f2009-12-07 08:24:59 +00005698 return;
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005699
5700 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5701 if (!KeyFunction || KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5702 return;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005703
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005704 // We will need to mark all of the virtual members as referenced to build the
5705 // vtable.
5706 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlssond6a637f2009-12-07 08:24:59 +00005707}
5708
5709bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5710 if (ClassesWithUnmarkedVirtualMembers.empty())
5711 return false;
5712
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005713 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5714 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5715 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5716 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005717 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005718 }
5719
Anders Carlssond6a637f2009-12-07 08:24:59 +00005720 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005721}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005722
5723void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5724 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5725 e = RD->method_end(); i != e; ++i) {
5726 CXXMethodDecl *MD = *i;
5727
5728 // C++ [basic.def.odr]p2:
5729 // [...] A virtual member function is used if it is not pure. [...]
5730 if (MD->isVirtual() && !MD->isPure())
5731 MarkDeclarationReferenced(Loc, MD);
5732 }
5733}
5734