blob: ad2dba7ce4b8c687ad98cc812be56fbe0d7dced2 [file] [log] [blame]
Chris Lattnerac7b83a2008-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 Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000108 ExprArg defarg) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000109 ParmVarDecl *Param = (ParmVarDecl *)param;
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg.release());
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner97316c02008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000144 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000145 }
Chris Lattner97316c02008-04-10 02:22:51 +0000146
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor605de8d2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 bool Invalid = false;
208
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000209 // C++ [dcl.fct.default]p4:
210 //
211 // For non-template functions, default arguments can be added in
212 // later declarations of a function in the same
213 // scope. Declarations in different scopes have completely
214 // distinct sets of default arguments. That is, declarations in
215 // inner scopes do not acquire default arguments from
216 // declarations in outer scopes, and vice versa. In a given
217 // function declaration, all parameters subsequent to a
218 // parameter with a default argument shall have default
219 // arguments supplied in this or previous declarations. A
220 // default argument shall not be redefined by a later
221 // declaration (not even to the same value).
222 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223 ParmVarDecl *OldParam = Old->getParamDecl(p);
224 ParmVarDecl *NewParam = New->getParamDecl(p);
225
226 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000228 diag::err_param_default_argument_redefinition)
229 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000230 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000231 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000232 } else if (OldParam->getDefaultArg()) {
233 // Merge the old default argument into the new parameter
234 NewParam->setDefaultArg(OldParam->getDefaultArg());
235 }
236 }
237
Douglas Gregor083c23e2009-02-16 17:45:42 +0000238 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245 unsigned NumParams = FD->getNumParams();
246 unsigned p;
247
248 // Find first parameter with a default argument
249 for (p = 0; p < NumParams; ++p) {
250 ParmVarDecl *Param = FD->getParamDecl(p);
251 if (Param->getDefaultArg())
252 break;
253 }
254
255 // C++ [dcl.fct.default]p4:
256 // In a given function declaration, all parameters
257 // subsequent to a parameter with a default argument shall
258 // have default arguments supplied in this or previous
259 // declarations. A default argument shall not be redefined
260 // by a later declaration (not even to the same value).
261 unsigned LastMissingDefaultArg = 0;
262 for(; p < NumParams; ++p) {
263 ParmVarDecl *Param = FD->getParamDecl(p);
264 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000265 if (Param->isInvalidDecl())
266 /* We already complained about this parameter. */;
267 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000268 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000269 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000270 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000271 else
272 Diag(Param->getLocation(),
273 diag::err_param_default_argument_missing);
274
275 LastMissingDefaultArg = p;
276 }
277 }
278
279 if (LastMissingDefaultArg > 0) {
280 // Some default arguments were missing. Clear out all of the
281 // default arguments up to (and including) the last missing
282 // default argument, so that we leave the function parameters
283 // in a semantically valid state.
284 for (p = 0; p <= LastMissingDefaultArg; ++p) {
285 ParmVarDecl *Param = FD->getParamDecl(p);
286 if (Param->getDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000287 if (!Param->hasUnparsedDefaultArg())
288 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000289 Param->setDefaultArg(0);
290 }
291 }
292 }
293}
Douglas Gregorec93f442008-04-13 21:30:24 +0000294
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000301 CXXRecordDecl *CurDecl;
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000302 if (SS && SS->isSet() && !SS->isInvalid()) {
303 DeclContext *DC = computeDeclContext(*SS);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305 } else
306 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000309 return &II == CurDecl->getIdentifier();
310 else
311 return false;
312}
313
Douglas Gregored3a3982009-03-03 04:44:36 +0000314/// \brief Check the validity of a C++ base class specifier.
315///
316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
317/// and returns NULL otherwise.
318CXXBaseSpecifier *
319Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
320 SourceRange SpecifierRange,
321 bool Virtual, AccessSpecifier Access,
322 QualType BaseType,
323 SourceLocation BaseLoc) {
324 // C++ [class.union]p1:
325 // A union shall not have base classes.
326 if (Class->isUnion()) {
327 Diag(Class->getLocation(), diag::err_base_clause_on_union)
328 << SpecifierRange;
329 return 0;
330 }
331
332 if (BaseType->isDependentType())
333 return new CXXBaseSpecifier(SpecifierRange, Virtual,
334 Class->getTagKind() == RecordDecl::TK_class,
335 Access, BaseType);
336
337 // Base specifiers must be record types.
338 if (!BaseType->isRecordType()) {
339 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
340 return 0;
341 }
342
343 // C++ [class.union]p1:
344 // A union shall not be used as a base class.
345 if (BaseType->isUnionType()) {
346 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
347 return 0;
348 }
349
350 // C++ [class.derived]p2:
351 // The class-name in a base-specifier shall not be an incompletely
352 // defined class.
Douglas Gregorc84d8932009-03-09 16:13:40 +0000353 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor375733c2009-03-10 00:06:19 +0000354 SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000355 return 0;
356
357 // If the base class is polymorphic, the new one is, too.
358 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359 assert(BaseDecl && "Record type has no declaration");
360 BaseDecl = BaseDecl->getDefinition(Context);
361 assert(BaseDecl && "Base type is not incomplete, but has no definition");
362 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363 Class->setPolymorphic(true);
364
365 // C++ [dcl.init.aggr]p1:
366 // An aggregate is [...] a class with [...] no base classes [...].
367 Class->setAggregate(false);
368 Class->setPOD(false);
369
370 // Create the base specifier.
371 // FIXME: Allocate via ASTContext?
372 return new CXXBaseSpecifier(SpecifierRange, Virtual,
373 Class->getTagKind() == RecordDecl::TK_class,
374 Access, BaseType);
375}
376
Douglas Gregorec93f442008-04-13 21:30:24 +0000377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
378/// one entry in the base class list of a class specifier, for
379/// example:
380/// class foo : public bar, virtual private baz {
381/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384 bool Virtual, AccessSpecifier Access,
385 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000386 AdjustDeclIfTemplate(classdecl);
387 CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
Douglas Gregora60c62e2009-02-09 15:09:02 +0000388 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000389 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
390 Virtual, Access,
391 BaseType, BaseLoc))
392 return BaseSpec;
393
394 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000395}
Douglas Gregorec93f442008-04-13 21:30:24 +0000396
Douglas Gregored3a3982009-03-03 04:44:36 +0000397/// \brief Performs the actual work of attaching the given base class
398/// specifiers to a C++ class.
399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
400 unsigned NumBases) {
401 if (NumBases == 0)
402 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000403
404 // Used to keep track of which base types we have already seen, so
405 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000406 // that the key is always the unqualified canonical type of the base
407 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000408 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
409
410 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000411 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000412 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000413 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000414 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000415 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000416 NewBaseType = NewBaseType.getUnqualifiedType();
417
Douglas Gregorabed2172008-10-22 17:49:05 +0000418 if (KnownBaseTypes[NewBaseType]) {
419 // C++ [class.mi]p3:
420 // A class shall not be specified as a direct base class of a
421 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000422 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000423 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000424 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000425 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000426
427 // Delete the duplicate base class specifier; we're going to
428 // overwrite its pointer later.
Douglas Gregored3a3982009-03-03 04:44:36 +0000429 delete Bases[idx];
430
431 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000432 } else {
433 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000434 KnownBaseTypes[NewBaseType] = Bases[idx];
435 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000436 }
437 }
438
439 // Attach the remaining base class specifiers to the derived class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000440 Class->setBases(Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000441
442 // Delete the remaining (good) base class specifiers, since their
443 // data has been copied into the CXXRecordDecl.
444 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregored3a3982009-03-03 04:44:36 +0000445 delete Bases[idx];
446
447 return Invalid;
448}
449
450/// ActOnBaseSpecifiers - Attach the given base specifiers to the
451/// class, after checking whether there are any duplicate base
452/// classes.
453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
454 unsigned NumBases) {
455 if (!ClassDecl || !Bases || !NumBases)
456 return;
457
458 AdjustDeclIfTemplate(ClassDecl);
459 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
460 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000461}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000462
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000463//===----------------------------------------------------------------------===//
464// C++ class member Handling
465//===----------------------------------------------------------------------===//
466
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
469/// bitfield width if there is one and 'InitExpr' specifies the initializer if
470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
471/// declarators on it.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000472Sema::DeclTy *
473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
474 ExprTy *BW, ExprTy *InitExpr,
475 DeclTy *LastInGroup) {
476 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000477 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000478 Expr *BitWidth = static_cast<Expr*>(BW);
479 Expr *Init = static_cast<Expr*>(InitExpr);
480 SourceLocation Loc = D.getIdentifierLoc();
481
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000482 bool isFunc = D.isFunctionDeclarator();
483
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000484 // C++ 9.2p6: A member shall not be declared to have automatic storage
485 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
487 // data members and cannot be applied to names declared const or static,
488 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000489 switch (DS.getStorageClassSpec()) {
490 case DeclSpec::SCS_unspecified:
491 case DeclSpec::SCS_typedef:
492 case DeclSpec::SCS_static:
493 // FALL THROUGH.
494 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000495 case DeclSpec::SCS_mutable:
496 if (isFunc) {
497 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000499 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
501
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000502 // FIXME: It would be nicer if the keyword was ignored only for this
503 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000504 D.getMutableDeclSpec().ClearStorageClassSpecs();
505 } else {
506 QualType T = GetTypeForDeclarator(D, S);
507 diag::kind err = static_cast<diag::kind>(0);
508 if (T->isReferenceType())
509 err = diag::err_mutable_reference;
510 else if (T.isConstQualified())
511 err = diag::err_mutable_const;
512 if (err != 0) {
513 if (DS.getStorageClassSpecLoc().isValid())
514 Diag(DS.getStorageClassSpecLoc(), err);
515 else
516 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000517 // FIXME: It would be nicer if the keyword was ignored only for this
518 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000519 D.getMutableDeclSpec().ClearStorageClassSpecs();
520 }
521 }
522 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000523 default:
524 if (DS.getStorageClassSpecLoc().isValid())
525 Diag(DS.getStorageClassSpecLoc(),
526 diag::err_storageclass_invalid_for_member);
527 else
528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
529 D.getMutableDeclSpec().ClearStorageClassSpecs();
530 }
531
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000532 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000533 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000534 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000535 // Check also for this case:
536 //
537 // typedef int f();
538 // f a;
539 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000540 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
541 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000542 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000543
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000544 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
545 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000546 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000547
548 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000549 if (isInstField) {
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
551 AS);
Chris Lattnere384c182009-03-05 23:03:49 +0000552 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000553 } else {
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000554 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Chris Lattnere384c182009-03-05 23:03:49 +0000555 if (!Member) {
556 if (BitWidth) DeleteExpr(BitWidth);
557 return LastInGroup;
558 }
Chris Lattner432780c2009-03-05 23:01:03 +0000559
560 // Non-instance-fields can't have a bitfield.
561 if (BitWidth) {
562 if (Member->isInvalidDecl()) {
563 // don't emit another diagnostic.
Douglas Gregor00660582009-03-11 20:22:50 +0000564 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-03-05 23:01:03 +0000565 // C++ 9.6p3: A bit-field shall not be a static member.
566 // "static member 'A' cannot be a bit-field"
567 Diag(Loc, diag::err_static_not_bitfield)
568 << Name << BitWidth->getSourceRange();
569 } else if (isa<TypedefDecl>(Member)) {
570 // "typedef member 'x' cannot be a bit-field"
571 Diag(Loc, diag::err_typedef_not_bitfield)
572 << Name << BitWidth->getSourceRange();
573 } else {
574 // A function typedef ("typedef int f(); f a;").
575 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
576 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor0e518af2009-03-11 18:59:21 +0000577 << Name << cast<ValueDecl>(Member)->getType()
578 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000579 }
580
581 DeleteExpr(BitWidth);
582 BitWidth = 0;
583 Member->setInvalidDecl();
584 }
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000585
586 Member->setAccess(AS);
Chris Lattner9cffefc2009-03-05 22:45:59 +0000587 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000588
Douglas Gregor6704b312008-11-17 22:58:34 +0000589 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000590
Douglas Gregor8f53bb72009-03-11 23:00:04 +0000591 if (Init)
592 AddInitializerToDecl(Member, ExprArg(*this, Init), false);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000593
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000594 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000595 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000596 return LastInGroup;
597 }
598 return Member;
599}
600
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000601/// ActOnMemInitializer - Handle a C++ member initializer.
602Sema::MemInitResult
603Sema::ActOnMemInitializer(DeclTy *ConstructorD,
604 Scope *S,
605 IdentifierInfo *MemberOrBase,
606 SourceLocation IdLoc,
607 SourceLocation LParenLoc,
608 ExprTy **Args, unsigned NumArgs,
609 SourceLocation *CommaLocs,
610 SourceLocation RParenLoc) {
611 CXXConstructorDecl *Constructor
612 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
613 if (!Constructor) {
614 // The user wrote a constructor initializer on a function that is
615 // not a C++ constructor. Ignore the error for now, because we may
616 // have more member initializers coming; we'll diagnose it just
617 // once in ActOnMemInitializers.
618 return true;
619 }
620
621 CXXRecordDecl *ClassDecl = Constructor->getParent();
622
623 // C++ [class.base.init]p2:
624 // Names in a mem-initializer-id are looked up in the scope of the
625 // constructor’s class and, if not found in that scope, are looked
626 // up in the scope containing the constructor’s
627 // definition. [Note: if the constructor’s class contains a member
628 // with the same name as a direct or virtual base class of the
629 // class, a mem-initializer-id naming the member or base class and
630 // composed of a single identifier refers to the class member. A
631 // mem-initializer-id for the hidden base class may be specified
632 // using a qualified name. ]
633 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000634 FieldDecl *Member = 0;
Steve Naroffab63fd62009-01-08 17:28:14 +0000635 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000636 if (Result.first != Result.second)
637 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000638
639 // FIXME: Handle members of an anonymous union.
640
641 if (Member) {
642 // FIXME: Perform direct initialization of the member.
643 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
644 }
645
646 // It didn't name a member, so see if it names a class.
Douglas Gregor1075a162009-02-04 17:00:24 +0000647 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000648 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000649 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
650 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000651
Douglas Gregora60c62e2009-02-09 15:09:02 +0000652 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000653 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000654 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000655 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000656
657 // C++ [class.base.init]p2:
658 // [...] Unless the mem-initializer-id names a nonstatic data
659 // member of the constructor’s class or a direct or virtual base
660 // of that class, the mem-initializer is ill-formed. A
661 // mem-initializer-list can initialize a base class using any
662 // name that denotes that base class type.
663
664 // First, check for a direct base class.
665 const CXXBaseSpecifier *DirectBaseSpec = 0;
666 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
667 Base != ClassDecl->bases_end(); ++Base) {
668 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
669 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
670 // We found a direct base of this type. That's what we're
671 // initializing.
672 DirectBaseSpec = &*Base;
673 break;
674 }
675 }
676
677 // Check for a virtual base class.
678 // FIXME: We might be able to short-circuit this if we know in
679 // advance that there are no virtual bases.
680 const CXXBaseSpecifier *VirtualBaseSpec = 0;
681 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
682 // We haven't found a base yet; search the class hierarchy for a
683 // virtual base class.
684 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
685 /*DetectVirtual=*/false);
686 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
687 for (BasePaths::paths_iterator Path = Paths.begin();
688 Path != Paths.end(); ++Path) {
689 if (Path->back().Base->isVirtual()) {
690 VirtualBaseSpec = Path->back().Base;
691 break;
692 }
693 }
694 }
695 }
696
697 // C++ [base.class.init]p2:
698 // If a mem-initializer-id is ambiguous because it designates both
699 // a direct non-virtual base class and an inherited virtual base
700 // class, the mem-initializer is ill-formed.
701 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000702 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
703 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000704
705 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
706}
707
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000708namespace {
709 /// PureVirtualMethodCollector - traverses a class and its superclasses
710 /// and determines if it has any pure virtual methods.
711 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
712 ASTContext &Context;
713
Sebastian Redl16ac38f2009-03-22 21:28:55 +0000714 public:
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000715 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redl16ac38f2009-03-22 21:28:55 +0000716
717 private:
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000718 MethodList Methods;
719
720 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
721
722 public:
723 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
724 : Context(Ctx) {
725
726 MethodList List;
727 Collect(RD, List);
728
729 // Copy the temporary list to methods, and make sure to ignore any
730 // null entries.
731 for (size_t i = 0, e = List.size(); i != e; ++i) {
732 if (List[i])
733 Methods.push_back(List[i]);
734 }
735 }
736
Anders Carlssone1299b32009-03-22 20:18:17 +0000737 bool empty() const { return Methods.empty(); }
738
739 MethodList::const_iterator methods_begin() { return Methods.begin(); }
740 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000741 };
742
743 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
744 MethodList& Methods) {
745 // First, collect the pure virtual methods for the base classes.
746 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
747 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
748 if (const RecordType *RT = Base->getType()->getAsRecordType()) {
749 const CXXRecordDecl *BaseDecl
750 = cast<CXXRecordDecl>(RT->getDecl());
751 if (BaseDecl && BaseDecl->isAbstract())
752 Collect(BaseDecl, Methods);
753 }
754 }
755
756 // Next, zero out any pure virtual methods that this class overrides.
757 for (size_t i = 0, e = Methods.size(); i != e; ++i) {
758 const CXXMethodDecl *VMD = dyn_cast_or_null<CXXMethodDecl>(Methods[i]);
759 if (!VMD)
760 continue;
761
762 DeclContext::lookup_const_iterator I, E;
763 for (llvm::tie(I, E) = RD->lookup(VMD->getDeclName()); I != E; ++I) {
764 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I)) {
765 if (Context.getCanonicalType(MD->getType()) ==
766 Context.getCanonicalType(VMD->getType())) {
767 // We did find a matching method, which means that this is not a
768 // pure virtual method in the current class. Zero it out.
769 Methods[i] = 0;
770 }
771 }
772 }
773 }
774
775 // Finally, add pure virtual methods from this class.
776 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
777 i != e; ++i) {
778 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
779 if (MD->isPure())
780 Methods.push_back(MD);
781 }
782 }
783 }
784}
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000785
Anders Carlssone1299b32009-03-22 20:18:17 +0000786bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssond5a94982009-03-23 17:49:10 +0000787 unsigned DiagID, unsigned SelID) {
Anders Carlssone1299b32009-03-22 20:18:17 +0000788
789 if (!getLangOptions().CPlusPlus)
790 return false;
791
792 const RecordType *RT = T->getAsRecordType();
793 if (!RT)
794 return false;
795
796 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
797 if (!RD)
798 return false;
799
800 if (!RD->isAbstract())
801 return false;
802
Anders Carlssond5a94982009-03-23 17:49:10 +0000803 Diag(Loc, DiagID) << RD->getDeclName() << SelID;
Anders Carlssone1299b32009-03-22 20:18:17 +0000804
805 // Check if we've already emitted the list of pure virtual functions for this
806 // class.
807 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
808 return true;
809
810 PureVirtualMethodCollector Collector(Context, RD);
811
812 for (PureVirtualMethodCollector::MethodList::const_iterator I =
813 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
814 const CXXMethodDecl *MD = *I;
815
816 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
817 MD->getDeclName();
818 }
819
820 if (!PureVirtualClassDiagSet)
821 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
822 PureVirtualClassDiagSet->insert(RD);
823
824 return true;
825}
826
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000827void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
828 DeclTy *TagDecl,
829 SourceLocation LBrac,
830 SourceLocation RBrac) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000831 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000832 ActOnFields(S, RLoc, TagDecl,
833 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000834 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +0000835
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000836 CXXRecordDecl *RD = cast<CXXRecordDecl>((Decl*)TagDecl);
837 if (!RD->isAbstract()) {
838 // Collect all the pure virtual methods and see if this is an abstract
839 // class after all.
840 PureVirtualMethodCollector Collector(Context, RD);
841 if (!Collector.empty())
842 RD->setAbstract(true);
843 }
844
Douglas Gregored3a3982009-03-03 04:44:36 +0000845 if (!Template)
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000846 AddImplicitlyDeclaredMembersToClass(RD);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000847}
848
Douglas Gregore640ab62008-11-03 17:51:48 +0000849/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
850/// special functions, such as the default constructor, copy
851/// constructor, or destructor, to the given C++ class (C++
852/// [special]p1). This routine can only be executed just before the
853/// definition of the class is complete.
854void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000855 QualType ClassType = Context.getTypeDeclType(ClassDecl);
856 ClassType = Context.getCanonicalType(ClassType);
857
Douglas Gregore640ab62008-11-03 17:51:48 +0000858 if (!ClassDecl->hasUserDeclaredConstructor()) {
859 // C++ [class.ctor]p5:
860 // A default constructor for a class X is a constructor of class X
861 // that can be called without an argument. If there is no
862 // user-declared constructor for class X, a default constructor is
863 // implicitly declared. An implicitly-declared default constructor
864 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000865 DeclarationName Name
866 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000867 CXXConstructorDecl *DefaultCon =
868 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000869 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000870 Context.getFunctionType(Context.VoidTy,
871 0, 0, false, 0),
872 /*isExplicit=*/false,
873 /*isInline=*/true,
874 /*isImplicitlyDeclared=*/true);
875 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000876 DefaultCon->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000877 ClassDecl->addDecl(DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +0000878
879 // Notify the class that we've added a constructor.
880 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000881 }
882
883 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
884 // C++ [class.copy]p4:
885 // If the class definition does not explicitly declare a copy
886 // constructor, one is declared implicitly.
887
888 // C++ [class.copy]p5:
889 // The implicitly-declared copy constructor for a class X will
890 // have the form
891 //
892 // X::X(const X&)
893 //
894 // if
895 bool HasConstCopyConstructor = true;
896
897 // -- each direct or virtual base class B of X has a copy
898 // constructor whose first parameter is of type const B& or
899 // const volatile B&, and
900 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
901 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
902 const CXXRecordDecl *BaseClassDecl
903 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
904 HasConstCopyConstructor
905 = BaseClassDecl->hasConstCopyConstructor(Context);
906 }
907
908 // -- for all the nonstatic data members of X that are of a
909 // class type M (or array thereof), each such class type
910 // has a copy constructor whose first parameter is of type
911 // const M& or const volatile M&.
912 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
913 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
914 QualType FieldType = (*Field)->getType();
915 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
916 FieldType = Array->getElementType();
917 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
918 const CXXRecordDecl *FieldClassDecl
919 = cast<CXXRecordDecl>(FieldClassType->getDecl());
920 HasConstCopyConstructor
921 = FieldClassDecl->hasConstCopyConstructor(Context);
922 }
923 }
924
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000925 // Otherwise, the implicitly declared copy constructor will have
926 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +0000927 //
928 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000929 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +0000930 if (HasConstCopyConstructor)
931 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000932 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000933
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000934 // An implicitly-declared copy constructor is an inline public
935 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000936 DeclarationName Name
937 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000938 CXXConstructorDecl *CopyConstructor
939 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000940 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000941 Context.getFunctionType(Context.VoidTy,
942 &ArgType, 1,
943 false, 0),
944 /*isExplicit=*/false,
945 /*isInline=*/true,
946 /*isImplicitlyDeclared=*/true);
947 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000948 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +0000949
950 // Add the parameter to the constructor.
951 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
952 ClassDecl->getLocation(),
953 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000954 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000955 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +0000956
Douglas Gregorb9213832008-12-15 21:24:18 +0000957 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000958 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000959 }
960
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000961 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
962 // Note: The following rules are largely analoguous to the copy
963 // constructor rules. Note that virtual bases are not taken into account
964 // for determining the argument type of the operator. Note also that
965 // operators taking an object instead of a reference are allowed.
966 //
967 // C++ [class.copy]p10:
968 // If the class definition does not explicitly declare a copy
969 // assignment operator, one is declared implicitly.
970 // The implicitly-defined copy assignment operator for a class X
971 // will have the form
972 //
973 // X& X::operator=(const X&)
974 //
975 // if
976 bool HasConstCopyAssignment = true;
977
978 // -- each direct base class B of X has a copy assignment operator
979 // whose parameter is of type const B&, const volatile B& or B,
980 // and
981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
982 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
983 const CXXRecordDecl *BaseClassDecl
984 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
985 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
986 }
987
988 // -- for all the nonstatic data members of X that are of a class
989 // type M (or array thereof), each such class type has a copy
990 // assignment operator whose parameter is of type const M&,
991 // const volatile M& or M.
992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
993 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
994 QualType FieldType = (*Field)->getType();
995 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
996 FieldType = Array->getElementType();
997 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
998 const CXXRecordDecl *FieldClassDecl
999 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1000 HasConstCopyAssignment
1001 = FieldClassDecl->hasConstCopyAssignment(Context);
1002 }
1003 }
1004
1005 // Otherwise, the implicitly declared copy assignment operator will
1006 // have the form
1007 //
1008 // X& X::operator=(X&)
1009 QualType ArgType = ClassType;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001010 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001011 if (HasConstCopyAssignment)
1012 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001013 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001014
1015 // An implicitly-declared copy assignment operator is an inline public
1016 // member of its class.
1017 DeclarationName Name =
1018 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1019 CXXMethodDecl *CopyAssignment =
1020 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1021 Context.getFunctionType(RetType, &ArgType, 1,
1022 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001023 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001024 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001025 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001026
1027 // Add the parameter to the operator.
1028 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1029 ClassDecl->getLocation(),
1030 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001031 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001032 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001033
1034 // Don't call addedAssignmentOperator. There is no way to distinguish an
1035 // implicit from an explicit assignment operator.
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001036 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001037 }
1038
Douglas Gregorb9213832008-12-15 21:24:18 +00001039 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001040 // C++ [class.dtor]p2:
1041 // If a class has no user-declared destructor, a destructor is
1042 // declared implicitly. An implicitly-declared destructor is an
1043 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001044 DeclarationName Name
1045 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001046 CXXDestructorDecl *Destructor
1047 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001048 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001049 Context.getFunctionType(Context.VoidTy,
1050 0, 0, false, 0),
1051 /*isInline=*/true,
1052 /*isImplicitlyDeclared=*/true);
1053 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001054 Destructor->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001055 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001056 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001057}
1058
Douglas Gregor605de8d2008-12-16 21:30:33 +00001059/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1060/// parsing a top-level (non-nested) C++ class, and we are now
1061/// parsing those parts of the given Method declaration that could
1062/// not be parsed earlier (C++ [class.mem]p2), such as default
1063/// arguments. This action should enter the scope of the given
1064/// Method declaration as if we had just parsed the qualified method
1065/// name. However, it should not bring the parameters into scope;
1066/// that will be performed by ActOnDelayedCXXMethodParameter.
1067void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1068 CXXScopeSpec SS;
1069 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1070 ActOnCXXEnterDeclaratorScope(S, SS);
1071}
1072
1073/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1074/// C++ method declaration. We're (re-)introducing the given
1075/// function parameter into scope for use in parsing later parts of
1076/// the method declaration. For example, we could see an
1077/// ActOnParamDefaultArgument event for this parameter.
1078void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1079 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001080
1081 // If this parameter has an unparsed default argument, clear it out
1082 // to make way for the parsed default argument.
1083 if (Param->hasUnparsedDefaultArg())
1084 Param->setDefaultArg(0);
1085
Douglas Gregor605de8d2008-12-16 21:30:33 +00001086 S->AddDecl(Param);
1087 if (Param->getDeclName())
1088 IdResolver.AddDecl(Param);
1089}
1090
1091/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1092/// processing the delayed method declaration for Method. The method
1093/// declaration is now considered finished. There may be a separate
1094/// ActOnStartOfFunctionDef action later (not necessarily
1095/// immediately!) for this method, if it was also defined inside the
1096/// class body.
1097void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1098 FunctionDecl *Method = (FunctionDecl*)MethodD;
1099 CXXScopeSpec SS;
1100 SS.setScopeRep(Method->getDeclContext());
1101 ActOnCXXExitDeclaratorScope(S, SS);
1102
1103 // Now that we have our default arguments, check the constructor
1104 // again. It could produce additional diagnostics or affect whether
1105 // the class has implicitly-declared destructors, among other
1106 // things.
1107 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1108 if (CheckConstructor(Constructor))
1109 Constructor->setInvalidDecl();
1110 }
1111
1112 // Check the default arguments, which we may have added.
1113 if (!Method->isInvalidDecl())
1114 CheckCXXDefaultArguments(Method);
1115}
1116
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001117/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001118/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001119/// R. If there are any errors in the declarator, this routine will
1120/// emit diagnostics and return true. Otherwise, it will return
1121/// false. Either way, the type @p R will be updated to reflect a
1122/// well-formed type for the constructor.
1123bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1124 FunctionDecl::StorageClass& SC) {
1125 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1126 bool isInvalid = false;
1127
1128 // C++ [class.ctor]p3:
1129 // A constructor shall not be virtual (10.3) or static (9.4). A
1130 // constructor can be invoked for a const, volatile or const
1131 // volatile object. A constructor shall not be declared const,
1132 // volatile, or const volatile (9.3.2).
1133 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001134 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1135 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1136 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001137 isInvalid = true;
1138 }
1139 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001140 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1141 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1142 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001143 isInvalid = true;
1144 SC = FunctionDecl::None;
1145 }
1146 if (D.getDeclSpec().hasTypeSpecifier()) {
1147 // Constructors don't have return types, but the parser will
1148 // happily parse something like:
1149 //
1150 // class X {
1151 // float X(float);
1152 // };
1153 //
1154 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001155 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1156 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1157 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001158 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001159 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001160 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1161 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001162 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1163 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001164 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001165 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1166 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001167 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001168 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1169 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001170 }
1171
1172 // Rebuild the function type "R" without any type qualifiers (in
1173 // case any of the errors above fired) and with "void" as the
1174 // return type, since constructors don't have return types. We
1175 // *always* have to do this, because GetTypeForDeclarator will
1176 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001177 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001178 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1179 Proto->getNumArgs(),
1180 Proto->isVariadic(),
1181 0);
1182
1183 return isInvalid;
1184}
1185
Douglas Gregor605de8d2008-12-16 21:30:33 +00001186/// CheckConstructor - Checks a fully-formed constructor for
1187/// well-formedness, issuing any diagnostics required. Returns true if
1188/// the constructor declarator is invalid.
1189bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1190 if (Constructor->isInvalidDecl())
1191 return true;
1192
1193 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1194 bool Invalid = false;
1195
1196 // C++ [class.copy]p3:
1197 // A declaration of a constructor for a class X is ill-formed if
1198 // its first parameter is of type (optionally cv-qualified) X and
1199 // either there are no other parameters or else all other
1200 // parameters have default arguments.
1201 if ((Constructor->getNumParams() == 1) ||
1202 (Constructor->getNumParams() > 1 &&
1203 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1204 QualType ParamType = Constructor->getParamDecl(0)->getType();
1205 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1206 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1207 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1208 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1209 Invalid = true;
1210 }
1211 }
1212
1213 // Notify the class that we've added a constructor.
1214 ClassDecl->addedConstructor(Context, Constructor);
1215
1216 return Invalid;
1217}
1218
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001219/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1220/// the well-formednes of the destructor declarator @p D with type @p
1221/// R. If there are any errors in the declarator, this routine will
1222/// emit diagnostics and return true. Otherwise, it will return
1223/// false. Either way, the type @p R will be updated to reflect a
1224/// well-formed type for the destructor.
1225bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1226 FunctionDecl::StorageClass& SC) {
1227 bool isInvalid = false;
1228
1229 // C++ [class.dtor]p1:
1230 // [...] A typedef-name that names a class is a class-name
1231 // (7.1.3); however, a typedef-name that names a class shall not
1232 // be used as the identifier in the declarator for a destructor
1233 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001234 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1235 if (DeclaratorType->getAsTypedefType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001236 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001237 << DeclaratorType;
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001238 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001239 }
1240
1241 // C++ [class.dtor]p2:
1242 // A destructor is used to destroy objects of its class type. A
1243 // destructor takes no parameters, and no return type can be
1244 // specified for it (not even void). The address of a destructor
1245 // shall not be taken. A destructor shall not be static. A
1246 // destructor can be invoked for a const, volatile or const
1247 // volatile object. A destructor shall not be declared const,
1248 // volatile or const volatile (9.3.2).
1249 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001250 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1251 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1252 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001253 isInvalid = true;
1254 SC = FunctionDecl::None;
1255 }
1256 if (D.getDeclSpec().hasTypeSpecifier()) {
1257 // Destructors don't have return types, but the parser will
1258 // happily parse something like:
1259 //
1260 // class X {
1261 // float ~X();
1262 // };
1263 //
1264 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001265 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1266 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1267 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001268 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001269 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001270 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1271 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001272 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1273 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001274 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001275 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1276 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001277 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001278 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1279 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001280 }
1281
1282 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001283 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001284 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1285
1286 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001287 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001288 }
1289
1290 // Make sure the destructor isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001291 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001292 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1293
1294 // Rebuild the function type "R" without any type qualifiers or
1295 // parameters (in case any of the errors above fired) and with
1296 // "void" as the return type, since destructors don't have return
1297 // types. We *always* have to do this, because GetTypeForDeclarator
1298 // will put in a result type of "int" when none was specified.
1299 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1300
1301 return isInvalid;
1302}
1303
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001304/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1305/// well-formednes of the conversion function declarator @p D with
1306/// type @p R. If there are any errors in the declarator, this routine
1307/// will emit diagnostics and return true. Otherwise, it will return
1308/// false. Either way, the type @p R will be updated to reflect a
1309/// well-formed type for the conversion operator.
1310bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1311 FunctionDecl::StorageClass& SC) {
1312 bool isInvalid = false;
1313
1314 // C++ [class.conv.fct]p1:
1315 // Neither parameter types nor return type can be specified. The
1316 // type of a conversion function (8.3.5) is “function taking no
1317 // parameter returning conversion-type-id.”
1318 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001319 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1320 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1321 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001322 isInvalid = true;
1323 SC = FunctionDecl::None;
1324 }
1325 if (D.getDeclSpec().hasTypeSpecifier()) {
1326 // Conversion functions don't have return types, but the parser will
1327 // happily parse something like:
1328 //
1329 // class X {
1330 // float operator bool();
1331 // };
1332 //
1333 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001334 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1335 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1336 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001337 }
1338
1339 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001340 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001341 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1342
1343 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001344 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001345 }
1346
1347 // Make sure the conversion function isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001348 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001349 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1350
1351 // C++ [class.conv.fct]p4:
1352 // The conversion-type-id shall not represent a function type nor
1353 // an array type.
1354 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1355 if (ConvType->isArrayType()) {
1356 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1357 ConvType = Context.getPointerType(ConvType);
1358 } else if (ConvType->isFunctionType()) {
1359 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1360 ConvType = Context.getPointerType(ConvType);
1361 }
1362
1363 // Rebuild the function type "R" without any parameters (in case any
1364 // of the errors above fired) and with the conversion type as the
1365 // return type.
1366 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001367 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001368
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001369 // C++0x explicit conversion operators.
1370 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1371 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1372 diag::warn_explicit_conversion_functions)
1373 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1374
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001375 return isInvalid;
1376}
1377
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001378/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1379/// the declaration of the given C++ conversion function. This routine
1380/// is responsible for recording the conversion function in the C++
1381/// class, if possible.
1382Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1383 assert(Conversion && "Expected to receive a conversion function declaration");
1384
Douglas Gregor98341042008-12-12 08:25:50 +00001385 // Set the lexical context of this conversion function
1386 Conversion->setLexicalDeclContext(CurContext);
1387
1388 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001389
1390 // Make sure we aren't redeclaring the conversion function.
1391 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001392
1393 // C++ [class.conv.fct]p1:
1394 // [...] A conversion function is never used to convert a
1395 // (possibly cv-qualified) object to the (possibly cv-qualified)
1396 // same object type (or a reference to it), to a (possibly
1397 // cv-qualified) base class of that type (or a reference to it),
1398 // or to (possibly cv-qualified) void.
1399 // FIXME: Suppress this warning if the conversion function ends up
1400 // being a virtual function that overrides a virtual function in a
1401 // base class.
1402 QualType ClassType
1403 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1404 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1405 ConvType = ConvTypeRef->getPointeeType();
1406 if (ConvType->isRecordType()) {
1407 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1408 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001409 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001410 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001411 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001412 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001413 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001414 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001415 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001416 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001417 }
1418
Douglas Gregor853dd392008-12-26 15:00:45 +00001419 if (Conversion->getPreviousDeclaration()) {
1420 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1421 for (OverloadedFunctionDecl::function_iterator
1422 Conv = Conversions->function_begin(),
1423 ConvEnd = Conversions->function_end();
1424 Conv != ConvEnd; ++Conv) {
1425 if (*Conv == Conversion->getPreviousDeclaration()) {
1426 *Conv = Conversion;
1427 return (DeclTy *)Conversion;
1428 }
1429 }
1430 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1431 } else
1432 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001433
1434 return (DeclTy *)Conversion;
1435}
1436
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001437//===----------------------------------------------------------------------===//
1438// Namespace Handling
1439//===----------------------------------------------------------------------===//
1440
1441/// ActOnStartNamespaceDef - This is called at the start of a namespace
1442/// definition.
1443Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1444 SourceLocation IdentLoc,
1445 IdentifierInfo *II,
1446 SourceLocation LBrace) {
1447 NamespaceDecl *Namespc =
1448 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1449 Namespc->setLBracLoc(LBrace);
1450
1451 Scope *DeclRegionScope = NamespcScope->getParent();
1452
1453 if (II) {
1454 // C++ [namespace.def]p2:
1455 // The identifier in an original-namespace-definition shall not have been
1456 // previously defined in the declarative region in which the
1457 // original-namespace-definition appears. The identifier in an
1458 // original-namespace-definition is the name of the namespace. Subsequently
1459 // in that declarative region, it is treated as an original-namespace-name.
1460
Douglas Gregor09be81b2009-02-04 17:27:36 +00001461 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1462 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001463
1464 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1465 // This is an extended namespace definition.
1466 // Attach this namespace decl to the chain of extended namespace
1467 // definitions.
1468 OrigNS->setNextNamespace(Namespc);
1469 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001470
Douglas Gregor8acb7272008-12-11 16:49:14 +00001471 // Remove the previous declaration from the scope.
1472 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001473 IdResolver.RemoveDecl(OrigNS);
1474 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001475 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001476 } else if (PrevDecl) {
1477 // This is an invalid name redefinition.
1478 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1479 << Namespc->getDeclName();
1480 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1481 Namespc->setInvalidDecl();
1482 // Continue on to push Namespc as current DeclContext and return it.
1483 }
1484
1485 PushOnScopeChains(Namespc, DeclRegionScope);
1486 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001487 // FIXME: Handle anonymous namespaces
1488 }
1489
1490 // Although we could have an invalid decl (i.e. the namespace name is a
1491 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001492 // FIXME: We should be able to push Namespc here, so that the
1493 // each DeclContext for the namespace has the declarations
1494 // that showed up in that particular namespace definition.
1495 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001496 return Namespc;
1497}
1498
1499/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1500/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1501void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1502 Decl *Dcl = static_cast<Decl *>(D);
1503 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1504 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1505 Namespc->setRBracLoc(RBrace);
1506 PopDeclContext();
1507}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001508
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001509Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1510 SourceLocation UsingLoc,
1511 SourceLocation NamespcLoc,
1512 const CXXScopeSpec &SS,
1513 SourceLocation IdentLoc,
1514 IdentifierInfo *NamespcName,
1515 AttributeList *AttrList) {
1516 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1517 assert(NamespcName && "Invalid NamespcName.");
1518 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001519 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001520
Douglas Gregor7a7be652009-02-03 19:21:40 +00001521 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001522
Douglas Gregor78d70132009-01-14 22:20:51 +00001523 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001524 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1525 LookupNamespaceName, false);
1526 if (R.isAmbiguous()) {
1527 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1528 return 0;
1529 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001530 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001531 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001532 // C++ [namespace.udir]p1:
1533 // A using-directive specifies that the names in the nominated
1534 // namespace can be used in the scope in which the
1535 // using-directive appears after the using-directive. During
1536 // unqualified name lookup (3.4.1), the names appear as if they
1537 // were declared in the nearest enclosing namespace which
1538 // contains both the using-directive and the nominated
1539 // namespace. [Note: in this context, “contains” means “contains
1540 // directly or indirectly”. ]
1541
1542 // Find enclosing context containing both using-directive and
1543 // nominated namespace.
1544 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1545 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1546 CommonAncestor = CommonAncestor->getParent();
1547
1548 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1549 NamespcLoc, IdentLoc,
1550 cast<NamespaceDecl>(NS),
1551 CommonAncestor);
1552 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001553 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001554 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001555 }
1556
Douglas Gregor7a7be652009-02-03 19:21:40 +00001557 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001558 delete AttrList;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001559 return UDir;
1560}
1561
1562void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1563 // If scope has associated entity, then using directive is at namespace
1564 // or translation unit scope. We add UsingDirectiveDecls, into
1565 // it's lookup structure.
1566 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1567 Ctx->addDecl(UDir);
1568 else
1569 // Otherwise it is block-sope. using-directives will affect lookup
1570 // only to the end of scope.
1571 S->PushUsingDirective(UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001572}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001573
1574/// AddCXXDirectInitializerToDecl - This action is called immediately after
1575/// ActOnDeclarator, when a C++ direct initializer is present.
1576/// e.g: "int x(1);"
1577void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001578 MultiExprArg Exprs,
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001579 SourceLocation *CommaLocs,
1580 SourceLocation RParenLoc) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001581 unsigned NumExprs = Exprs.size();
1582 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001583 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001584
1585 // If there is no declaration, there was an error parsing it. Just ignore
1586 // the initializer.
1587 if (RealDecl == 0) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001588 return;
1589 }
1590
1591 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1592 if (!VDecl) {
1593 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1594 RealDecl->setInvalidDecl();
1595 return;
1596 }
1597
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001598 // We will treat direct-initialization as a copy-initialization:
1599 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001600 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1601 //
1602 // Clients that want to distinguish between the two forms, can check for
1603 // direct initializer using VarDecl::hasCXXDirectInitializer().
1604 // A major benefit is that clients that don't particularly care about which
1605 // exactly form was it (like the CodeGen) can handle both cases without
1606 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001607
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001608 // C++ 8.5p11:
1609 // The form of initialization (using parentheses or '=') is generally
1610 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001611 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001612 QualType DeclInitType = VDecl->getType();
1613 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1614 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001615
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001616 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001617 CXXConstructorDecl *Constructor
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001618 = PerformInitializationByConstructor(DeclInitType,
1619 (Expr **)Exprs.get(), NumExprs,
Douglas Gregor6428e762008-11-05 15:29:30 +00001620 VDecl->getLocation(),
1621 SourceRange(VDecl->getLocation(),
1622 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001623 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001624 IK_Direct);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001625 if (!Constructor)
Douglas Gregor5870a952008-11-03 20:45:27 +00001626 RealDecl->setInvalidDecl();
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001627 else
1628 Exprs.release();
Douglas Gregor6428e762008-11-05 15:29:30 +00001629
1630 // Let clients know that initialization was done with a direct
1631 // initializer.
1632 VDecl->setCXXDirectInitializer(true);
1633
1634 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1635 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001636 return;
1637 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001638
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001639 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001640 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1641 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001642 RealDecl->setInvalidDecl();
1643 return;
1644 }
1645
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001646 // Let clients know that initialization was done with a direct initializer.
1647 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001648
1649 assert(NumExprs == 1 && "Expected 1 expression");
1650 // Set the init expression, handles conversions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001651 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
1652 /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001653}
Douglas Gregor81c29152008-10-29 00:13:59 +00001654
Douglas Gregor6428e762008-11-05 15:29:30 +00001655/// PerformInitializationByConstructor - Perform initialization by
1656/// constructor (C++ [dcl.init]p14), which may occur as part of
1657/// direct-initialization or copy-initialization. We are initializing
1658/// an object of type @p ClassType with the given arguments @p
1659/// Args. @p Loc is the location in the source code where the
1660/// initializer occurs (e.g., a declaration, member initializer,
1661/// functional cast, etc.) while @p Range covers the whole
1662/// initialization. @p InitEntity is the entity being initialized,
1663/// which may by the name of a declaration or a type. @p Kind is the
1664/// kind of initialization we're performing, which affects whether
1665/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001666/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001667/// when the initialization fails, emits a diagnostic and returns
1668/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001669CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001670Sema::PerformInitializationByConstructor(QualType ClassType,
1671 Expr **Args, unsigned NumArgs,
1672 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001673 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001674 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001675 const RecordType *ClassRec = ClassType->getAsRecordType();
1676 assert(ClassRec && "Can only initialize a class type here");
1677
1678 // C++ [dcl.init]p14:
1679 //
1680 // If the initialization is direct-initialization, or if it is
1681 // copy-initialization where the cv-unqualified version of the
1682 // source type is the same class as, or a derived class of, the
1683 // class of the destination, constructors are considered. The
1684 // applicable constructors are enumerated (13.3.1.3), and the
1685 // best one is chosen through overload resolution (13.3). The
1686 // constructor so selected is called to initialize the object,
1687 // with the initializer expression(s) as its argument(s). If no
1688 // constructor applies, or the overload resolution is ambiguous,
1689 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001690 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1691 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001692
1693 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001694 DeclarationName ConstructorName
1695 = Context.DeclarationNames.getCXXConstructorName(
1696 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001697 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001698 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001699 Con != ConEnd; ++Con) {
1700 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001701 if ((Kind == IK_Direct) ||
1702 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1703 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1704 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1705 }
1706
Douglas Gregorb9213832008-12-15 21:24:18 +00001707 // FIXME: When we decide not to synthesize the implicitly-declared
1708 // constructors, we'll need to make them appear here.
1709
Douglas Gregor5870a952008-11-03 20:45:27 +00001710 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001711 switch (BestViableFunction(CandidateSet, Best)) {
1712 case OR_Success:
1713 // We found a constructor. Return it.
1714 return cast<CXXConstructorDecl>(Best->Function);
1715
1716 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001717 if (InitEntity)
1718 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001719 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00001720 else
1721 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001722 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001723 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001724 return 0;
1725
1726 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001727 if (InitEntity)
1728 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1729 else
1730 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001731 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1732 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001733
1734 case OR_Deleted:
1735 if (InitEntity)
1736 Diag(Loc, diag::err_ovl_deleted_init)
1737 << Best->Function->isDeleted()
1738 << InitEntity << Range;
1739 else
1740 Diag(Loc, diag::err_ovl_deleted_init)
1741 << Best->Function->isDeleted()
1742 << InitEntity << Range;
1743 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1744 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00001745 }
1746
1747 return 0;
1748}
1749
Douglas Gregor81c29152008-10-29 00:13:59 +00001750/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1751/// determine whether they are reference-related,
1752/// reference-compatible, reference-compatible with added
1753/// qualification, or incompatible, for use in C++ initialization by
1754/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1755/// type, and the first type (T1) is the pointee type of the reference
1756/// type being initialized.
1757Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001758Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1759 bool& DerivedToBase) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00001760 assert(!T1->isReferenceType() &&
1761 "T1 must be the pointee type of the reference type");
Douglas Gregor81c29152008-10-29 00:13:59 +00001762 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1763
1764 T1 = Context.getCanonicalType(T1);
1765 T2 = Context.getCanonicalType(T2);
1766 QualType UnqualT1 = T1.getUnqualifiedType();
1767 QualType UnqualT2 = T2.getUnqualifiedType();
1768
1769 // C++ [dcl.init.ref]p4:
1770 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1771 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1772 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001773 if (UnqualT1 == UnqualT2)
1774 DerivedToBase = false;
1775 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1776 DerivedToBase = true;
1777 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001778 return Ref_Incompatible;
1779
1780 // At this point, we know that T1 and T2 are reference-related (at
1781 // least).
1782
1783 // C++ [dcl.init.ref]p4:
1784 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1785 // reference-related to T2 and cv1 is the same cv-qualification
1786 // as, or greater cv-qualification than, cv2. For purposes of
1787 // overload resolution, cases for which cv1 is greater
1788 // cv-qualification than cv2 are identified as
1789 // reference-compatible with added qualification (see 13.3.3.2).
1790 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1791 return Ref_Compatible;
1792 else if (T1.isMoreQualifiedThan(T2))
1793 return Ref_Compatible_With_Added_Qualification;
1794 else
1795 return Ref_Related;
1796}
1797
1798/// CheckReferenceInit - Check the initialization of a reference
1799/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1800/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001801/// list), and DeclType is the type of the declaration. When ICS is
1802/// non-null, this routine will compute the implicit conversion
1803/// sequence according to C++ [over.ics.ref] and will not produce any
1804/// diagnostics; when ICS is null, it will emit diagnostics when any
1805/// errors are found. Either way, a return value of true indicates
1806/// that there was a failure, a return value of false indicates that
1807/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001808///
1809/// When @p SuppressUserConversions, user-defined conversions are
1810/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001811/// When @p AllowExplicit, we also permit explicit user-defined
1812/// conversion functions.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001813bool
1814Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001815 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001816 bool SuppressUserConversions,
1817 bool AllowExplicit) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001818 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1819
1820 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1821 QualType T2 = Init->getType();
1822
Douglas Gregor45014fd2008-11-10 20:40:00 +00001823 // If the initializer is the address of an overloaded function, try
1824 // to resolve the overloaded function. If all goes well, T2 is the
1825 // type of the resulting function.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001826 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00001827 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1828 ICS != 0);
1829 if (Fn) {
1830 // Since we're performing this reference-initialization for
1831 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00001832 if (!ICS) {
1833 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1834 return true;
1835
Douglas Gregor45014fd2008-11-10 20:40:00 +00001836 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00001837 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00001838
1839 T2 = Fn->getType();
1840 }
1841 }
1842
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001843 // Compute some basic properties of the types and the initializer.
Sebastian Redlce6fff02009-03-16 23:22:08 +00001844 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001845 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001846 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001847 ReferenceCompareResult RefRelationship
1848 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1849
1850 // Most paths end in a failed conversion.
1851 if (ICS)
1852 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001853
1854 // C++ [dcl.init.ref]p5:
1855 // A reference to type “cv1 T1” is initialized by an expression
1856 // of type “cv2 T2” as follows:
1857
1858 // -- If the initializer expression
1859
1860 bool BindsDirectly = false;
1861 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1862 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001863 //
1864 // Note that the bit-field check is skipped if we are just computing
1865 // the implicit conversion sequence (C++ [over.best.ics]p2).
1866 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1867 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001868 BindsDirectly = true;
1869
Sebastian Redlce6fff02009-03-16 23:22:08 +00001870 // Rvalue references cannot bind to lvalues (N2812).
Sebastian Redlce6fff02009-03-16 23:22:08 +00001871 if (isRValRef) {
1872 if (!ICS)
1873 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
1874 << Init->getSourceRange();
1875 return true;
1876 }
1877
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001878 if (ICS) {
1879 // C++ [over.ics.ref]p1:
1880 // When a parameter of reference type binds directly (8.5.3)
1881 // to an argument expression, the implicit conversion sequence
1882 // is the identity conversion, unless the argument expression
1883 // has a type that is a derived class of the parameter type,
1884 // in which case the implicit conversion sequence is a
1885 // derived-to-base Conversion (13.3.3.1).
1886 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1887 ICS->Standard.First = ICK_Identity;
1888 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1889 ICS->Standard.Third = ICK_Identity;
1890 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1891 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001892 ICS->Standard.ReferenceBinding = true;
1893 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001894
1895 // Nothing more to do: the inaccessibility/ambiguity check for
1896 // derived-to-base conversions is suppressed when we're
1897 // computing the implicit conversion sequence (C++
1898 // [over.best.ics]p2).
1899 return false;
1900 } else {
1901 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001902 // FIXME: Binding to a subobject of the lvalue is going to require
1903 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001904 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001905 }
1906 }
1907
1908 // -- has a class type (i.e., T2 is a class type) and can be
1909 // implicitly converted to an lvalue of type “cv3 T3,”
1910 // where “cv1 T1” is reference-compatible with “cv3 T3”
1911 // 92) (this conversion is selected by enumerating the
1912 // applicable conversion functions (13.3.1.6) and choosing
1913 // the best one through overload resolution (13.3)),
Sebastian Redlce6fff02009-03-16 23:22:08 +00001914 if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00001915 // FIXME: Look for conversions in base classes!
1916 CXXRecordDecl *T2RecordDecl
1917 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001918
Douglas Gregore6985fe2008-11-10 16:14:15 +00001919 OverloadCandidateSet CandidateSet;
1920 OverloadedFunctionDecl *Conversions
1921 = T2RecordDecl->getConversionFunctions();
1922 for (OverloadedFunctionDecl::function_iterator Func
1923 = Conversions->function_begin();
1924 Func != Conversions->function_end(); ++Func) {
1925 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001926
Douglas Gregore6985fe2008-11-10 16:14:15 +00001927 // If the conversion function doesn't return a reference type,
1928 // it can't be considered for this conversion.
Sebastian Redlce6fff02009-03-16 23:22:08 +00001929 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001930 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00001931 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1932 }
1933
1934 OverloadCandidateSet::iterator Best;
1935 switch (BestViableFunction(CandidateSet, Best)) {
1936 case OR_Success:
1937 // This is a direct binding.
1938 BindsDirectly = true;
1939
1940 if (ICS) {
1941 // C++ [over.ics.ref]p1:
1942 //
1943 // [...] If the parameter binds directly to the result of
1944 // applying a conversion function to the argument
1945 // expression, the implicit conversion sequence is a
1946 // user-defined conversion sequence (13.3.3.1.2), with the
1947 // second standard conversion sequence either an identity
1948 // conversion or, if the conversion function returns an
1949 // entity of a type that is a derived class of the parameter
1950 // type, a derived-to-base Conversion.
1951 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1952 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1953 ICS->UserDefined.After = Best->FinalConversion;
1954 ICS->UserDefined.ConversionFunction = Best->Function;
1955 assert(ICS->UserDefined.After.ReferenceBinding &&
1956 ICS->UserDefined.After.DirectBinding &&
1957 "Expected a direct reference binding!");
1958 return false;
1959 } else {
1960 // Perform the conversion.
1961 // FIXME: Binding to a subobject of the lvalue is going to require
1962 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001963 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001964 }
1965 break;
1966
1967 case OR_Ambiguous:
1968 assert(false && "Ambiguous reference binding conversions not implemented.");
1969 return true;
1970
1971 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001972 case OR_Deleted:
1973 // There was no suitable conversion, or we found a deleted
1974 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00001975 break;
1976 }
1977 }
1978
Douglas Gregor81c29152008-10-29 00:13:59 +00001979 if (BindsDirectly) {
1980 // C++ [dcl.init.ref]p4:
1981 // [...] In all cases where the reference-related or
1982 // reference-compatible relationship of two types is used to
1983 // establish the validity of a reference binding, and T1 is a
1984 // base class of T2, a program that necessitates such a binding
1985 // is ill-formed if T1 is an inaccessible (clause 11) or
1986 // ambiguous (10.2) base class of T2.
1987 //
1988 // Note that we only check this condition when we're allowed to
1989 // complain about errors, because we should not be checking for
1990 // ambiguity (or inaccessibility) unless the reference binding
1991 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001992 if (DerivedToBase)
1993 return CheckDerivedToBaseConversion(T2, T1,
1994 Init->getSourceRange().getBegin(),
1995 Init->getSourceRange());
1996 else
1997 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001998 }
1999
2000 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redlce6fff02009-03-16 23:22:08 +00002001 // type (i.e., cv1 shall be const), or shall be an rvalue reference.
2002 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002003 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002004 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002005 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002006 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2007 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002008 return true;
2009 }
2010
2011 // -- If the initializer expression is an rvalue, with T2 a
2012 // class type, and “cv1 T1” is reference-compatible with
2013 // “cv2 T2,” the reference is bound in one of the
2014 // following ways (the choice is implementation-defined):
2015 //
2016 // -- The reference is bound to the object represented by
2017 // the rvalue (see 3.10) or to a sub-object within that
2018 // object.
2019 //
2020 // -- A temporary of type “cv1 T2” [sic] is created, and
2021 // a constructor is called to copy the entire rvalue
2022 // object into the temporary. The reference is bound to
2023 // the temporary or to a sub-object within the
2024 // temporary.
2025 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002026 // The constructor that would be used to make the copy
2027 // shall be callable whether or not the copy is actually
2028 // done.
2029 //
2030 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
2031 // freedom, so we will always take the first option and never build
2032 // a temporary in this case. FIXME: We will, however, have to check
2033 // for the presence of a copy constructor in C++98/03 mode.
2034 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002035 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2036 if (ICS) {
2037 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2038 ICS->Standard.First = ICK_Identity;
2039 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2040 ICS->Standard.Third = ICK_Identity;
2041 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2042 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002043 ICS->Standard.ReferenceBinding = true;
2044 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002045 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00002046 // FIXME: Binding to a subobject of the rvalue is going to require
2047 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00002048 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00002049 }
2050 return false;
2051 }
2052
2053 // -- Otherwise, a temporary of type “cv1 T1” is created and
2054 // initialized from the initializer expression using the
2055 // rules for a non-reference copy initialization (8.5). The
2056 // reference is then bound to the temporary. If T1 is
2057 // reference-related to T2, cv1 must be the same
2058 // cv-qualification as, or greater cv-qualification than,
2059 // cv2; otherwise, the program is ill-formed.
2060 if (RefRelationship == Ref_Related) {
2061 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2062 // we would be reference-compatible or reference-compatible with
2063 // added qualification. But that wasn't the case, so the reference
2064 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002065 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002066 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002067 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002068 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2069 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002070 return true;
2071 }
2072
Douglas Gregorb206cc42009-01-30 23:27:23 +00002073 // If at least one of the types is a class type, the types are not
2074 // related, and we aren't allowed any user conversions, the
2075 // reference binding fails. This case is important for breaking
2076 // recursion, since TryImplicitConversion below will attempt to
2077 // create a temporary through the use of a copy constructor.
2078 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2079 (T1->isRecordType() || T2->isRecordType())) {
2080 if (!ICS)
2081 Diag(Init->getSourceRange().getBegin(),
2082 diag::err_typecheck_convert_incompatible)
2083 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2084 return true;
2085 }
2086
Douglas Gregor81c29152008-10-29 00:13:59 +00002087 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002088 if (ICS) {
2089 /// C++ [over.ics.ref]p2:
2090 ///
2091 /// When a parameter of reference type is not bound directly to
2092 /// an argument expression, the conversion sequence is the one
2093 /// required to convert the argument expression to the
2094 /// underlying type of the reference according to
2095 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2096 /// to copy-initializing a temporary of the underlying type with
2097 /// the argument expression. Any difference in top-level
2098 /// cv-qualification is subsumed by the initialization itself
2099 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002100 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002101 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2102 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002103 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002104 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002105}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002106
2107/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2108/// of this overloaded operator is well-formed. If so, returns false;
2109/// otherwise, emits appropriate diagnostics and returns true.
2110bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002111 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002112 "Expected an overloaded operator declaration");
2113
Douglas Gregore60e5d32008-11-06 22:13:31 +00002114 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2115
2116 // C++ [over.oper]p5:
2117 // The allocation and deallocation functions, operator new,
2118 // operator new[], operator delete and operator delete[], are
2119 // described completely in 3.7.3. The attributes and restrictions
2120 // found in the rest of this subclause do not apply to them unless
2121 // explicitly stated in 3.7.3.
2122 // FIXME: Write a separate routine for checking this. For now, just
2123 // allow it.
2124 if (Op == OO_New || Op == OO_Array_New ||
2125 Op == OO_Delete || Op == OO_Array_Delete)
2126 return false;
2127
2128 // C++ [over.oper]p6:
2129 // An operator function shall either be a non-static member
2130 // function or be a non-member function and have at least one
2131 // parameter whose type is a class, a reference to a class, an
2132 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002133 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2134 if (MethodDecl->isStatic())
2135 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002136 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002137 } else {
2138 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002139 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2140 ParamEnd = FnDecl->param_end();
2141 Param != ParamEnd; ++Param) {
2142 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002143 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2144 ClassOrEnumParam = true;
2145 break;
2146 }
2147 }
2148
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002149 if (!ClassOrEnumParam)
2150 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002151 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002152 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002153 }
2154
2155 // C++ [over.oper]p8:
2156 // An operator function cannot have default arguments (8.3.6),
2157 // except where explicitly stated below.
2158 //
2159 // Only the function-call operator allows default arguments
2160 // (C++ [over.call]p1).
2161 if (Op != OO_Call) {
2162 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2163 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002164 if ((*Param)->hasUnparsedDefaultArg())
2165 return Diag((*Param)->getLocation(),
2166 diag::err_operator_overload_default_arg)
2167 << FnDecl->getDeclName();
2168 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002169 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002170 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002171 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002172 }
2173 }
2174
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002175 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2176 { false, false, false }
2177#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2178 , { Unary, Binary, MemberOnly }
2179#include "clang/Basic/OperatorKinds.def"
2180 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002181
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002182 bool CanBeUnaryOperator = OperatorUses[Op][0];
2183 bool CanBeBinaryOperator = OperatorUses[Op][1];
2184 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002185
2186 // C++ [over.oper]p8:
2187 // [...] Operator functions cannot have more or fewer parameters
2188 // than the number required for the corresponding operator, as
2189 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002190 unsigned NumParams = FnDecl->getNumParams()
2191 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002192 if (Op != OO_Call &&
2193 ((NumParams == 1 && !CanBeUnaryOperator) ||
2194 (NumParams == 2 && !CanBeBinaryOperator) ||
2195 (NumParams < 1) || (NumParams > 2))) {
2196 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002197 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002198 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002199 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002200 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002201 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002202 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002203 assert(CanBeBinaryOperator &&
2204 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002205 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002206 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002207
Chris Lattnerbb002332008-11-21 07:57:12 +00002208 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002209 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002210 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002211
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002212 // Overloaded operators other than operator() cannot be variadic.
2213 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002214 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002215 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002216 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002217 }
2218
2219 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002220 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2221 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002222 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002223 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002224 }
2225
2226 // C++ [over.inc]p1:
2227 // The user-defined function called operator++ implements the
2228 // prefix and postfix ++ operator. If this function is a member
2229 // function with no parameters, or a non-member function with one
2230 // parameter of class or enumeration type, it defines the prefix
2231 // increment operator ++ for objects of that type. If the function
2232 // is a member function with one parameter (which shall be of type
2233 // int) or a non-member function with two parameters (the second
2234 // of which shall be of type int), it defines the postfix
2235 // increment operator ++ for objects of that type.
2236 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2237 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2238 bool ParamIsInt = false;
2239 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2240 ParamIsInt = BT->getKind() == BuiltinType::Int;
2241
Chris Lattnera7021ee2008-11-21 07:50:02 +00002242 if (!ParamIsInt)
2243 return Diag(LastParam->getLocation(),
2244 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002245 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002246 }
2247
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002248 // Notify the class if it got an assignment operator.
2249 if (Op == OO_Equal) {
2250 // Would have returned earlier otherwise.
2251 assert(isa<CXXMethodDecl>(FnDecl) &&
2252 "Overloaded = not member, but not filtered.");
2253 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2254 Method->getParent()->addedAssignmentOperator(Context, Method);
2255 }
2256
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002257 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002258}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002259
Douglas Gregord8028382009-01-05 19:45:36 +00002260/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2261/// linkage specification, including the language and (if present)
2262/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2263/// the location of the language string literal, which is provided
2264/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2265/// the '{' brace. Otherwise, this linkage specification does not
2266/// have any braces.
2267Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2268 SourceLocation ExternLoc,
2269 SourceLocation LangLoc,
2270 const char *Lang,
2271 unsigned StrSize,
2272 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002273 LinkageSpecDecl::LanguageIDs Language;
2274 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2275 Language = LinkageSpecDecl::lang_c;
2276 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2277 Language = LinkageSpecDecl::lang_cxx;
2278 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002279 Diag(LangLoc, diag::err_bad_language);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002280 return 0;
2281 }
2282
2283 // FIXME: Add all the various semantics of linkage specifications
2284
Douglas Gregord8028382009-01-05 19:45:36 +00002285 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2286 LangLoc, Language,
2287 LBraceLoc.isValid());
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002288 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002289 PushDeclContext(S, D);
2290 return D;
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002291}
2292
Douglas Gregord8028382009-01-05 19:45:36 +00002293/// ActOnFinishLinkageSpecification - Completely the definition of
2294/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2295/// valid, it's the position of the closing '}' brace in a linkage
2296/// specification that uses braces.
2297Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2298 DeclTy *LinkageSpec,
2299 SourceLocation RBraceLoc) {
2300 if (LinkageSpec)
2301 PopDeclContext();
2302 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002303}
2304
Sebastian Redl743c8162008-12-22 19:15:10 +00002305/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2306/// handler.
2307Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2308{
2309 QualType ExDeclType = GetTypeForDeclarator(D, S);
2310 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2311
2312 bool Invalid = false;
2313
2314 // Arrays and functions decay.
2315 if (ExDeclType->isArrayType())
2316 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2317 else if (ExDeclType->isFunctionType())
2318 ExDeclType = Context.getPointerType(ExDeclType);
2319
2320 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2321 // The exception-declaration shall not denote a pointer or reference to an
2322 // incomplete type, other than [cv] void*.
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002323 // N2844 forbids rvalue references.
2324 if(ExDeclType->isRValueReferenceType()) {
2325 Diag(Begin, diag::err_catch_rvalue_ref) << D.getSourceRange();
2326 Invalid = true;
2327 }
Sebastian Redl743c8162008-12-22 19:15:10 +00002328 QualType BaseType = ExDeclType;
2329 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002330 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002331 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2332 BaseType = Ptr->getPointeeType();
2333 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002334 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002335 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002336 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl743c8162008-12-22 19:15:10 +00002337 BaseType = Ref->getPointeeType();
2338 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002339 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002340 }
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002341 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorc84d8932009-03-09 16:13:40 +00002342 RequireCompleteType(Begin, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002343 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002344
Sebastian Redl237116b2008-12-22 21:35:02 +00002345 // FIXME: Need to test for ability to copy-construct and destroy the
2346 // exception variable.
2347 // FIXME: Need to check for abstract classes.
2348
Sebastian Redl743c8162008-12-22 19:15:10 +00002349 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00002350 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002351 // The scope should be freshly made just for us. There is just no way
2352 // it contains any previous declaration.
2353 assert(!S->isDeclScope(PrevDecl));
2354 if (PrevDecl->isTemplateParameter()) {
2355 // Maybe we will complain about the shadowed template parameter.
2356 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2357
2358 }
2359 }
2360
2361 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002362 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl743c8162008-12-22 19:15:10 +00002363 if (D.getInvalidType() || Invalid)
2364 ExDecl->setInvalidDecl();
2365
2366 if (D.getCXXScopeSpec().isSet()) {
2367 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2368 << D.getCXXScopeSpec().getRange();
2369 ExDecl->setInvalidDecl();
2370 }
2371
2372 // Add the exception declaration into this scope.
2373 S->AddDecl(ExDecl);
2374 if (II)
2375 IdResolver.AddDecl(ExDecl);
2376
2377 ProcessDeclAttributes(ExDecl, D);
2378 return ExDecl;
2379}
Anders Carlssoned691562009-03-14 00:25:26 +00002380
2381Sema::DeclTy *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2382 ExprArg assertexpr,
Anders Carlssonc45057a2009-03-15 18:44:04 +00002383 ExprArg assertmessageexpr) {
Anders Carlssoned691562009-03-14 00:25:26 +00002384 Expr *AssertExpr = (Expr *)assertexpr.get();
2385 StringLiteral *AssertMessage =
2386 cast<StringLiteral>((Expr *)assertmessageexpr.get());
2387
Anders Carlsson8b842c52009-03-14 00:33:21 +00002388 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
2389 llvm::APSInt Value(32);
2390 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
2391 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
2392 AssertExpr->getSourceRange();
2393 return 0;
2394 }
Anders Carlssoned691562009-03-14 00:25:26 +00002395
Anders Carlsson8b842c52009-03-14 00:33:21 +00002396 if (Value == 0) {
2397 std::string str(AssertMessage->getStrData(),
2398 AssertMessage->getByteLength());
Anders Carlssonc45057a2009-03-15 18:44:04 +00002399 Diag(AssertLoc, diag::err_static_assert_failed)
2400 << str << AssertExpr->getSourceRange();
Anders Carlsson8b842c52009-03-14 00:33:21 +00002401 }
2402 }
2403
Anders Carlsson0f4942b2009-03-15 17:35:16 +00002404 assertexpr.release();
2405 assertmessageexpr.release();
Anders Carlssoned691562009-03-14 00:25:26 +00002406 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
2407 AssertExpr, AssertMessage);
Anders Carlssoned691562009-03-14 00:25:26 +00002408
2409 CurContext->addDecl(Decl);
2410 return Decl;
2411}