1 //===------ 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 "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/CXXFieldCollector.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTMutationListener.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include <map>
37 #include <set>
38
39 using namespace clang;
40
41 //===----------------------------------------------------------------------===//
42 // CheckDefaultArgumentVisitor
43 //===----------------------------------------------------------------------===//
44
45 namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
51 class CheckDefaultArgumentVisitor
52 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
53 Expr *DefaultArg;
54 Sema *S;
55
56 public:
CheckDefaultArgumentVisitor(Expr * defarg,Sema * s)57 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58 : DefaultArg(defarg), S(s) {}
59
60 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
62 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
63 };
64
65 /// VisitExpr - Visit all of the children of this expression.
VisitExpr(Expr * Node)66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
68 for (Stmt::child_range I = Node->children(); I; ++I)
69 IsInvalid |= Visit(*I);
70 return IsInvalid;
71 }
72
73 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
VisitDeclRefExpr(DeclRefExpr * DRE)76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77 NamedDecl *Decl = DRE->getDecl();
78 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
87 return S->Diag(DRE->getSourceRange().getBegin(),
88 diag::err_param_default_argument_references_param)
89 << Param->getDeclName() << DefaultArg->getSourceRange();
90 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
94 if (VDecl->isLocalVarDecl())
95 return S->Diag(DRE->getSourceRange().getBegin(),
96 diag::err_param_default_argument_references_local)
97 << VDecl->getDeclName() << DefaultArg->getSourceRange();
98 }
99
100 return false;
101 }
102
103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
VisitCXXThisExpr(CXXThisExpr * ThisE)104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
111 }
112 }
113
CalledDecl(CXXMethodDecl * Method)114 void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178 Exceptions.push_back(*E);
179 }
180
CalledExpr(Expr * E)181 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208 }
209
210 bool
SetParamDefaultArgument(ParmVarDecl * Param,Expr * Arg,SourceLocation EqualLoc)211 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
212 SourceLocation EqualLoc) {
213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
231 MultiExprArg(*this, &Arg, 1));
232 if (Result.isInvalid())
233 return true;
234 Arg = Result.takeAs<Expr>();
235
236 CheckImplicitConversions(Arg, EqualLoc);
237 Arg = MaybeCreateExprWithCleanups(Arg);
238
239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
241
242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
254 return false;
255 }
256
257 /// ActOnParamDefaultArgument - Check whether the default argument
258 /// provided for a function parameter is well-formed. If so, attach it
259 /// to the parameter declaration.
260 void
ActOnParamDefaultArgument(Decl * param,SourceLocation EqualLoc,Expr * DefaultArg)261 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
264 return;
265
266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
267 UnparsedDefaultArgLocs.erase(Param);
268
269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
273 Param->setInvalidDecl();
274 return;
275 }
276
277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
283 // Check that the default argument is well-formed
284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
286 Param->setInvalidDecl();
287 return;
288 }
289
290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
291 }
292
293 /// ActOnParamUnparsedDefaultArgument - We've seen a default
294 /// argument for a function parameter, but we can't parse it yet
295 /// because we're inside a class definition. Note that this default
296 /// argument will be parsed later.
ActOnParamUnparsedDefaultArgument(Decl * param,SourceLocation EqualLoc,SourceLocation ArgLoc)297 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
300 if (!param)
301 return;
302
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
304 if (Param)
305 Param->setUnparsedDefaultArg();
306
307 UnparsedDefaultArgLocs[Param] = ArgLoc;
308 }
309
310 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311 /// the default argument for the parameter param failed.
ActOnParamDefaultArgumentError(Decl * param)312 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
313 if (!param)
314 return;
315
316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
317
318 Param->setInvalidDecl();
319
320 UnparsedDefaultArgLocs.erase(Param);
321 }
322
323 /// CheckExtraCXXDefaultArguments - Check for any extra default
324 /// arguments in the declarator, which is not a function declaration
325 /// or definition and therefore is not permitted to have default
326 /// arguments. This routine should be invoked for every declarator
327 /// that is not a function declaration or definition.
CheckExtraCXXDefaultArguments(Declarator & D)328 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
352 }
353 }
354 }
355 }
356 }
357
358 // MergeCXXFunctionDecl - Merge two declarations of the same C++
359 // function, once we already know that they have the same
360 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
361 // error, false otherwise.
MergeCXXFunctionDecl(FunctionDecl * New,FunctionDecl * Old)362 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
365 // C++ [dcl.fct.default]p4:
366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
388
389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
395 if (getLangOptions().Microsoft) {
396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
406 Invalid = false;
407 }
408 }
409
410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
418 Diag(NewParam->getLocation(), DiagDefaultParamID)
419 << NewParam->getDefaultArgRange();
420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
433 } else if (OldParam->hasDefaultArg()) {
434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
436 // strips off any top-level ExprWithCleanups.
437 NewParam->setHasInheritedDefaultArg();
438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
442 NewParam->setDefaultArg(OldParam->getInit());
443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
501 }
502 }
503 }
504
505 if (CheckEquivalentExceptionSpec(Old, New))
506 Invalid = true;
507
508 return Invalid;
509 }
510
511 /// \brief Merge the exception specifications of two variable declarations.
512 ///
513 /// This is called when there's a redeclaration of a VarDecl. The function
514 /// checks if the redeclaration might have an exception specification and
515 /// validates compatibility and merges the specs if necessary.
MergeVarDeclExceptionSpecs(VarDecl * New,VarDecl * Old)516 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551 }
552
553 /// CheckCXXDefaultArguments - Verify that the default arguments for a
554 /// function declaration are well-formed according to C++
555 /// [dcl.fct.default].
CheckCXXDefaultArguments(FunctionDecl * FD)556 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
563 if (Param->hasDefaultArg())
564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
574 for (; p < NumParams; ++p) {
575 ParmVarDecl *Param = FD->getParamDecl(p);
576 if (!Param->hasDefaultArg()) {
577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
580 Diag(Param->getLocation(),
581 diag::err_param_default_argument_missing_name)
582 << Param->getIdentifier();
583 else
584 Diag(Param->getLocation(),
585 diag::err_param_default_argument_missing);
586
587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
598 if (Param->hasDefaultArg()) {
599 Param->setDefaultArg(0);
600 }
601 }
602 }
603 }
604
605 /// isCurrentClassName - Determine whether the identifier II is the
606 /// name of the class type currently being defined. In the case of
607 /// nested classes, this will only return true if II is the name of
608 /// the innermost class.
isCurrentClassName(const IdentifierInfo & II,Scope *,const CXXScopeSpec * SS)609 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
613 CXXRecordDecl *CurDecl;
614 if (SS && SS->isSet() && !SS->isInvalid()) {
615 DeclContext *DC = computeDeclContext(*SS, true);
616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
620 if (CurDecl && CurDecl->getIdentifier())
621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624 }
625
626 /// \brief Check the validity of a C++ base class specifier.
627 ///
628 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629 /// and returns NULL otherwise.
630 CXXBaseSpecifier *
CheckBaseSpecifier(CXXRecordDecl * Class,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,TypeSourceInfo * TInfo,SourceLocation EllipsisLoc)631 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
636 QualType BaseType = TInfo->getType();
637
638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
653 if (BaseType->isDependentType())
654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
655 Class->getTagKind() == TTK_Class,
656 Access, TInfo, EllipsisLoc);
657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
676 if (RequireCompleteType(BaseLoc, BaseType,
677 PDiag(diag::err_incomplete_base_class)
678 << SpecifierRange)) {
679 Class->setInvalidDecl();
680 return 0;
681 }
682
683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
685 assert(BaseDecl && "Record type has no declaration");
686 BaseDecl = BaseDecl->getDefinition();
687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
690
691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
704
705 // Create the base specifier.
706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
707 Class->getTagKind() == TTK_Class,
708 Access, TInfo, EllipsisLoc);
709 }
710
711 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712 /// one entry in the base class list of a class specifier, for
713 /// example:
714 /// class foo : public bar, virtual private baz {
715 /// 'public bar' and 'virtual private baz' are each base-specifiers.
716 BaseResult
ActOnBaseSpecifier(Decl * classdecl,SourceRange SpecifierRange,bool Virtual,AccessSpecifier Access,ParsedType basetype,SourceLocation BaseLoc,SourceLocation EllipsisLoc)717 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
718 bool Virtual, AccessSpecifier Access,
719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
721 if (!classdecl)
722 return true;
723
724 AdjustDeclIfTemplate(classdecl);
725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
726 if (!Class)
727 return true;
728
729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
731
732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
734 UPPC_BaseType))
735 return true;
736
737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
738 Virtual, Access, TInfo,
739 EllipsisLoc))
740 return BaseSpec;
741
742 return true;
743 }
744
745 /// \brief Performs the actual work of attaching the given base class
746 /// specifiers to a C++ class.
AttachBaseSpecifiers(CXXRecordDecl * Class,CXXBaseSpecifier ** Bases,unsigned NumBases)747 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
754 // that the key is always the unqualified canonical type of the base
755 // class.
756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
759 unsigned NumGoodBases = 0;
760 bool Invalid = false;
761 for (unsigned idx = 0; idx < NumBases; ++idx) {
762 QualType NewBaseType
763 = Context.getCanonicalType(Bases[idx]->getType());
764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
769 Diag(Bases[idx]->getSourceRange().getBegin(),
770 diag::err_duplicate_base_class)
771 << KnownBaseTypes[NewBaseType]->getType()
772 << Bases[idx]->getSourceRange();
773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
776 Context.Deallocate(Bases[idx]);
777
778 Invalid = true;
779 } else {
780 // Okay, add this new base class.
781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
787 Class->setBases(Bases, NumGoodBases);
788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
792 Context.Deallocate(Bases[idx]);
793
794 return Invalid;
795 }
796
797 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
798 /// class, after checking whether there are any duplicate base
799 /// classes.
ActOnBaseSpecifiers(Decl * ClassDecl,BaseTy ** Bases,unsigned NumBases)800 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
807 (CXXBaseSpecifier**)(Bases), NumBases);
808 }
809
GetClassForType(QualType T)810 static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817 }
818
819 /// \brief Determine whether the type \p Derived is a C++ class that is
820 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base)821 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
827 return false;
828
829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
831 return false;
832
833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
835 }
836
837 /// \brief Determine whether the type \p Derived is a C++ class that is
838 /// derived from the type \p Base.
IsDerivedFrom(QualType Derived,QualType Base,CXXBasePaths & Paths)839 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
845 return false;
846
847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
849 return false;
850
851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852 }
853
BuildBasePathArray(const CXXBasePaths & Paths,CXXCastPath & BasePathArray)854 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
855 CXXCastPath &BasePathArray) {
856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
875 }
876
877 /// \brief Determine whether the given base path includes a virtual
878 /// base class.
BasePathInvolvesVirtualBase(const CXXCastPath & BasePath)879 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887 }
888
889 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890 /// conversion (where Derived and Base are class types) is
891 /// well-formed, meaning that the conversion is unambiguous (and
892 /// that all of the base classes are accessible). Returns true
893 /// and emits a diagnostic if the code is ill-formed, returns false
894 /// otherwise. Loc is the location where this routine should point to
895 /// if there is an error, and Range is the source range to highlight
896 /// if there is an error.
897 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,unsigned InaccessibleBaseID,unsigned AmbigiousBaseConvID,SourceLocation Loc,SourceRange Range,DeclarationName Name,CXXCastPath * BasePath)898 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
899 unsigned InaccessibleBaseID,
900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
902 DeclarationName Name,
903 CXXCastPath *BasePath) {
904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
926 }
927 }
928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956 }
957
958 bool
CheckDerivedToBaseConversion(QualType Derived,QualType Base,SourceLocation Loc,SourceRange Range,CXXCastPath * BasePath,bool IgnoreAccess)959 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
960 SourceLocation Loc, SourceRange Range,
961 CXXCastPath *BasePath,
962 bool IgnoreAccess) {
963 return CheckDerivedToBaseConversion(Derived, Base,
964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
966 diag::err_ambiguous_derived_to_base_conv,
967 Loc, Range, DeclarationName(),
968 BasePath);
969 }
970
971
972 /// @brief Builds a string representing ambiguous paths from a
973 /// specific derived class to different subobjects of the same base
974 /// class.
975 ///
976 /// This function builds a string that can be used in error messages
977 /// to show the different paths that one can take through the
978 /// inheritance hierarchy to go from the derived class to different
979 /// subobjects of a base class. The result looks something like this:
980 /// @code
981 /// struct D -> struct B -> struct A
982 /// struct D -> struct C -> struct A
983 /// @endcode
getAmbiguousPathsDisplayString(CXXBasePaths & Paths)984 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001 }
1002
1003 //===----------------------------------------------------------------------===//
1004 // C++ class member Handling
1005 //===----------------------------------------------------------------------===//
1006
1007 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
ActOnAccessSpecifier(AccessSpecifier Access,SourceLocation ASLoc,SourceLocation ColonLoc)1008 Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
1011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
1015 return ASDecl;
1016 }
1017
1018 /// CheckOverrideControl - Check C++0x override control semantics.
CheckOverrideControl(const Decl * D)1019 void Sema::CheckOverrideControl(const Decl *D) {
1020 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1021 if (!MD || !MD->isVirtual())
1022 return;
1023
1024 if (MD->isDependentContext())
1025 return;
1026
1027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
1033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1034 Diag(MD->getLocation(),
1035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039 }
1040
1041 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042 /// function overrides a virtual member function marked 'final', according to
1043 /// C++0x [class.virtual]p3.
CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl * New,const CXXMethodDecl * Old)1044 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
1046 if (!Old->hasAttr<FinalAttr>())
1047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
1053 }
1054
1055 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1057 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058 /// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059 /// present but parsing it has been deferred.
1060 Decl *
ActOnCXXMemberDeclarator(Scope * S,AccessSpecifier AS,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,ExprTy * BW,const VirtSpecifiers & VS,ExprTy * InitExpr,bool HasDeferredInit,bool IsDefinition)1061 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1062 MultiTemplateParamsArg TemplateParameterLists,
1063 ExprTy *BW, const VirtSpecifiers &VS,
1064 ExprTy *InitExpr, bool HasDeferredInit,
1065 bool IsDefinition) {
1066 const DeclSpec &DS = D.getDeclSpec();
1067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
1070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
1075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
1077
1078 assert(isa<CXXRecordDecl>(CurContext));
1079 assert(!DS.isFriendSpecified());
1080 assert(!Init || !HasDeferredInit);
1081
1082 bool isFunc = D.isDeclarationOfFunction();
1083
1084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
1086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
1089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
1095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
1098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1099 else
1100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1101
1102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
1104 D.getMutableDeclSpec().ClearStorageClassSpecs();
1105 }
1106 break;
1107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
1116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1118 !isFunc);
1119
1120 Decl *Member;
1121 if (isInstField) {
1122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
1124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
1142 // FIXME: Check for template parameters!
1143 // FIXME: Check that the name is an identifier!
1144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1145 HasDeferredInit, AS);
1146 assert(Member && "HandleField never returns null");
1147 } else {
1148 assert(!HasDeferredInit);
1149
1150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
1151 if (!Member) {
1152 return 0;
1153 }
1154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
1159 } else if (isa<VarDecl>(Member)) {
1160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
1172 << Name << cast<ValueDecl>(Member)->getType()
1173 << BitWidth->getSourceRange();
1174 }
1175
1176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
1179
1180 Member->setAccess(AS);
1181
1182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
1186 }
1187
1188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1194 } else
1195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1203 } else
1204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1205 }
1206
1207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
1213 CheckOverrideControl(Member);
1214
1215 assert((Name || isInstField) && "No identifier for non-field ?");
1216
1217 if (Init)
1218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
1220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
1228
1229 FinalizeDeclaration(Member);
1230
1231 if (isInstField)
1232 FieldCollector->Add(cast<FieldDecl>(Member));
1233 return Member;
1234 }
1235
1236 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1237 /// in-class initializer for a non-static C++ class member, and after
1238 /// instantiating an in-class initializer in a class template. Such actions
1239 /// are deferred until the class is complete.
1240 void
ActOnCXXInClassMemberInitializer(Decl * D,SourceLocation EqualLoc,Expr * InitExpr)1241 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242 Expr *InitExpr) {
1243 FieldDecl *FD = cast<FieldDecl>(D);
1244
1245 if (!InitExpr) {
1246 FD->setInvalidDecl();
1247 FD->removeInClassInitializer();
1248 return;
1249 }
1250
1251 ExprResult Init = InitExpr;
1252 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253 // FIXME: if there is no EqualLoc, this is list-initialization.
1254 Init = PerformCopyInitialization(
1255 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256 if (Init.isInvalid()) {
1257 FD->setInvalidDecl();
1258 return;
1259 }
1260
1261 CheckImplicitConversions(Init.get(), EqualLoc);
1262 }
1263
1264 // C++0x [class.base.init]p7:
1265 // The initialization of each base and member constitutes a
1266 // full-expression.
1267 Init = MaybeCreateExprWithCleanups(Init);
1268 if (Init.isInvalid()) {
1269 FD->setInvalidDecl();
1270 return;
1271 }
1272
1273 InitExpr = Init.release();
1274
1275 FD->setInClassInitializer(InitExpr);
1276 }
1277
1278 /// \brief Find the direct and/or virtual base specifiers that
1279 /// correspond to the given base type, for use in base initialization
1280 /// within a constructor.
FindBaseInitializer(Sema & SemaRef,CXXRecordDecl * ClassDecl,QualType BaseType,const CXXBaseSpecifier * & DirectBaseSpec,const CXXBaseSpecifier * & VirtualBaseSpec)1281 static bool FindBaseInitializer(Sema &SemaRef,
1282 CXXRecordDecl *ClassDecl,
1283 QualType BaseType,
1284 const CXXBaseSpecifier *&DirectBaseSpec,
1285 const CXXBaseSpecifier *&VirtualBaseSpec) {
1286 // First, check for a direct base class.
1287 DirectBaseSpec = 0;
1288 for (CXXRecordDecl::base_class_const_iterator Base
1289 = ClassDecl->bases_begin();
1290 Base != ClassDecl->bases_end(); ++Base) {
1291 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292 // We found a direct base of this type. That's what we're
1293 // initializing.
1294 DirectBaseSpec = &*Base;
1295 break;
1296 }
1297 }
1298
1299 // Check for a virtual base class.
1300 // FIXME: We might be able to short-circuit this if we know in advance that
1301 // there are no virtual bases.
1302 VirtualBaseSpec = 0;
1303 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304 // We haven't found a base yet; search the class hierarchy for a
1305 // virtual base class.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309 BaseType, Paths)) {
1310 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311 Path != Paths.end(); ++Path) {
1312 if (Path->back().Base->isVirtual()) {
1313 VirtualBaseSpec = Path->back().Base;
1314 break;
1315 }
1316 }
1317 }
1318 }
1319
1320 return DirectBaseSpec || VirtualBaseSpec;
1321 }
1322
1323 /// ActOnMemInitializer - Handle a C++ member initializer.
1324 MemInitResult
ActOnMemInitializer(Decl * ConstructorD,Scope * S,CXXScopeSpec & SS,IdentifierInfo * MemberOrBase,ParsedType TemplateTypeTy,SourceLocation IdLoc,SourceLocation LParenLoc,ExprTy ** Args,unsigned NumArgs,SourceLocation RParenLoc,SourceLocation EllipsisLoc)1325 Sema::ActOnMemInitializer(Decl *ConstructorD,
1326 Scope *S,
1327 CXXScopeSpec &SS,
1328 IdentifierInfo *MemberOrBase,
1329 ParsedType TemplateTypeTy,
1330 SourceLocation IdLoc,
1331 SourceLocation LParenLoc,
1332 ExprTy **Args, unsigned NumArgs,
1333 SourceLocation RParenLoc,
1334 SourceLocation EllipsisLoc) {
1335 if (!ConstructorD)
1336 return true;
1337
1338 AdjustDeclIfTemplate(ConstructorD);
1339
1340 CXXConstructorDecl *Constructor
1341 = dyn_cast<CXXConstructorDecl>(ConstructorD);
1342 if (!Constructor) {
1343 // The user wrote a constructor initializer on a function that is
1344 // not a C++ constructor. Ignore the error for now, because we may
1345 // have more member initializers coming; we'll diagnose it just
1346 // once in ActOnMemInitializers.
1347 return true;
1348 }
1349
1350 CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352 // C++ [class.base.init]p2:
1353 // Names in a mem-initializer-id are looked up in the scope of the
1354 // constructor's class and, if not found in that scope, are looked
1355 // up in the scope containing the constructor's definition.
1356 // [Note: if the constructor's class contains a member with the
1357 // same name as a direct or virtual base class of the class, a
1358 // mem-initializer-id naming the member or base class and composed
1359 // of a single identifier refers to the class member. A
1360 // mem-initializer-id for the hidden base class may be specified
1361 // using a qualified name. ]
1362 if (!SS.getScopeRep() && !TemplateTypeTy) {
1363 // Look for a member, first.
1364 FieldDecl *Member = 0;
1365 DeclContext::lookup_result Result
1366 = ClassDecl->lookup(MemberOrBase);
1367 if (Result.first != Result.second) {
1368 Member = dyn_cast<FieldDecl>(*Result.first);
1369
1370 if (Member) {
1371 if (EllipsisLoc.isValid())
1372 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
1375 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1376 LParenLoc, RParenLoc);
1377 }
1378
1379 // Handle anonymous union case.
1380 if (IndirectFieldDecl* IndirectField
1381 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382 if (EllipsisLoc.isValid())
1383 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
1386 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387 NumArgs, IdLoc,
1388 LParenLoc, RParenLoc);
1389 }
1390 }
1391 }
1392 // It didn't name a member, so see if it names a class.
1393 QualType BaseType;
1394 TypeSourceInfo *TInfo = 0;
1395
1396 if (TemplateTypeTy) {
1397 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1398 } else {
1399 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400 LookupParsedName(R, S, &SS);
1401
1402 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403 if (!TyD) {
1404 if (R.isAmbiguous()) return true;
1405
1406 // We don't want access-control diagnostics here.
1407 R.suppressDiagnostics();
1408
1409 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410 bool NotUnknownSpecialization = false;
1411 DeclContext *DC = computeDeclContext(SS, false);
1412 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415 if (!NotUnknownSpecialization) {
1416 // When the scope specifier can refer to a member of an unknown
1417 // specialization, we take it as a type name.
1418 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419 SS.getWithLocInContext(Context),
1420 *MemberOrBase, IdLoc);
1421 if (BaseType.isNull())
1422 return true;
1423
1424 R.clear();
1425 R.setLookupName(MemberOrBase);
1426 }
1427 }
1428
1429 // If no results were found, try to correct typos.
1430 TypoCorrection Corr;
1431 if (R.empty() && BaseType.isNull() &&
1432 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433 ClassDecl, false, CTC_NoKeywords))) {
1434 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1437 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1438 // We have found a non-static data member with a similar
1439 // name to what was typed; complain and initialize that
1440 // member.
1441 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1442 << MemberOrBase << true << CorrectedQuotedStr
1443 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1444 Diag(Member->getLocation(), diag::note_previous_decl)
1445 << CorrectedQuotedStr;
1446
1447 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448 LParenLoc, RParenLoc);
1449 }
1450 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1451 const CXXBaseSpecifier *DirectBaseSpec;
1452 const CXXBaseSpecifier *VirtualBaseSpec;
1453 if (FindBaseInitializer(*this, ClassDecl,
1454 Context.getTypeDeclType(Type),
1455 DirectBaseSpec, VirtualBaseSpec)) {
1456 // We have found a direct or virtual base class with a
1457 // similar name to what was typed; complain and initialize
1458 // that base class.
1459 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1460 << MemberOrBase << false << CorrectedQuotedStr
1461 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1462
1463 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464 : VirtualBaseSpec;
1465 Diag(BaseSpec->getSourceRange().getBegin(),
1466 diag::note_base_class_specified_here)
1467 << BaseSpec->getType()
1468 << BaseSpec->getSourceRange();
1469
1470 TyD = Type;
1471 }
1472 }
1473 }
1474
1475 if (!TyD && BaseType.isNull()) {
1476 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478 return true;
1479 }
1480 }
1481
1482 if (BaseType.isNull()) {
1483 BaseType = Context.getTypeDeclType(TyD);
1484 if (SS.isSet()) {
1485 NestedNameSpecifier *Qualifier =
1486 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1487
1488 // FIXME: preserve source range information
1489 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1490 }
1491 }
1492 }
1493
1494 if (!TInfo)
1495 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1496
1497 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1498 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1499 }
1500
1501 /// Checks an initializer expression for use of uninitialized fields, such as
1502 /// containing the field that is being initialized. Returns true if there is an
1503 /// uninitialized field was used an updates the SourceLocation parameter; false
1504 /// otherwise.
InitExprContainsUninitializedFields(const Stmt * S,const ValueDecl * LhsField,SourceLocation * L)1505 static bool InitExprContainsUninitializedFields(const Stmt *S,
1506 const ValueDecl *LhsField,
1507 SourceLocation *L) {
1508 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1509
1510 if (isa<CallExpr>(S)) {
1511 // Do not descend into function calls or constructors, as the use
1512 // of an uninitialized field may be valid. One would have to inspect
1513 // the contents of the function/ctor to determine if it is safe or not.
1514 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1515 // may be safe, depending on what the function/ctor does.
1516 return false;
1517 }
1518 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1519 const NamedDecl *RhsField = ME->getMemberDecl();
1520
1521 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1522 // The member expression points to a static data member.
1523 assert(VD->isStaticDataMember() &&
1524 "Member points to non-static data member!");
1525 (void)VD;
1526 return false;
1527 }
1528
1529 if (isa<EnumConstantDecl>(RhsField)) {
1530 // The member expression points to an enum.
1531 return false;
1532 }
1533
1534 if (RhsField == LhsField) {
1535 // Initializing a field with itself. Throw a warning.
1536 // But wait; there are exceptions!
1537 // Exception #1: The field may not belong to this record.
1538 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1539 const Expr *base = ME->getBase();
1540 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1541 // Even though the field matches, it does not belong to this record.
1542 return false;
1543 }
1544 // None of the exceptions triggered; return true to indicate an
1545 // uninitialized field was used.
1546 *L = ME->getMemberLoc();
1547 return true;
1548 }
1549 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1550 // sizeof/alignof doesn't reference contents, do not warn.
1551 return false;
1552 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1553 // address-of doesn't reference contents (the pointer may be dereferenced
1554 // in the same expression but it would be rare; and weird).
1555 if (UOE->getOpcode() == UO_AddrOf)
1556 return false;
1557 }
1558 for (Stmt::const_child_range it = S->children(); it; ++it) {
1559 if (!*it) {
1560 // An expression such as 'member(arg ?: "")' may trigger this.
1561 continue;
1562 }
1563 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1564 return true;
1565 }
1566 return false;
1567 }
1568
1569 MemInitResult
BuildMemberInitializer(ValueDecl * Member,Expr ** Args,unsigned NumArgs,SourceLocation IdLoc,SourceLocation LParenLoc,SourceLocation RParenLoc)1570 Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1571 unsigned NumArgs, SourceLocation IdLoc,
1572 SourceLocation LParenLoc,
1573 SourceLocation RParenLoc) {
1574 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1575 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1576 assert((DirectMember || IndirectMember) &&
1577 "Member must be a FieldDecl or IndirectFieldDecl");
1578
1579 if (Member->isInvalidDecl())
1580 return true;
1581
1582 // Diagnose value-uses of fields to initialize themselves, e.g.
1583 // foo(foo)
1584 // where foo is not also a parameter to the constructor.
1585 // TODO: implement -Wuninitialized and fold this into that framework.
1586 for (unsigned i = 0; i < NumArgs; ++i) {
1587 SourceLocation L;
1588 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1589 // FIXME: Return true in the case when other fields are used before being
1590 // uninitialized. For example, let this field be the i'th field. When
1591 // initializing the i'th field, throw a warning if any of the >= i'th
1592 // fields are used, as they are not yet initialized.
1593 // Right now we are only handling the case where the i'th field uses
1594 // itself in its initializer.
1595 Diag(L, diag::warn_field_is_uninit);
1596 }
1597 }
1598
1599 bool HasDependentArg = false;
1600 for (unsigned i = 0; i < NumArgs; i++)
1601 HasDependentArg |= Args[i]->isTypeDependent();
1602
1603 Expr *Init;
1604 if (Member->getType()->isDependentType() || HasDependentArg) {
1605 // Can't check initialization for a member of dependent type or when
1606 // any of the arguments are type-dependent expressions.
1607 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1608 RParenLoc,
1609 Member->getType().getNonReferenceType());
1610
1611 DiscardCleanupsInEvaluationContext();
1612 } else {
1613 // Initialize the member.
1614 InitializedEntity MemberEntity =
1615 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1616 : InitializedEntity::InitializeMember(IndirectMember, 0);
1617 InitializationKind Kind =
1618 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1619
1620 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1621
1622 ExprResult MemberInit =
1623 InitSeq.Perform(*this, MemberEntity, Kind,
1624 MultiExprArg(*this, Args, NumArgs), 0);
1625 if (MemberInit.isInvalid())
1626 return true;
1627
1628 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1629
1630 // C++0x [class.base.init]p7:
1631 // The initialization of each base and member constitutes a
1632 // full-expression.
1633 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1634 if (MemberInit.isInvalid())
1635 return true;
1636
1637 // If we are in a dependent context, template instantiation will
1638 // perform this type-checking again. Just save the arguments that we
1639 // received in a ParenListExpr.
1640 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1641 // of the information that we have about the member
1642 // initializer. However, deconstructing the ASTs is a dicey process,
1643 // and this approach is far more likely to get the corner cases right.
1644 if (CurContext->isDependentContext())
1645 Init = new (Context) ParenListExpr(
1646 Context, LParenLoc, Args, NumArgs, RParenLoc,
1647 Member->getType().getNonReferenceType());
1648 else
1649 Init = MemberInit.get();
1650 }
1651
1652 if (DirectMember) {
1653 return new (Context) CXXCtorInitializer(Context, DirectMember,
1654 IdLoc, LParenLoc, Init,
1655 RParenLoc);
1656 } else {
1657 return new (Context) CXXCtorInitializer(Context, IndirectMember,
1658 IdLoc, LParenLoc, Init,
1659 RParenLoc);
1660 }
1661 }
1662
1663 MemInitResult
BuildDelegatingInitializer(TypeSourceInfo * TInfo,Expr ** Args,unsigned NumArgs,SourceLocation NameLoc,SourceLocation LParenLoc,SourceLocation RParenLoc,CXXRecordDecl * ClassDecl)1664 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1665 Expr **Args, unsigned NumArgs,
1666 SourceLocation NameLoc,
1667 SourceLocation LParenLoc,
1668 SourceLocation RParenLoc,
1669 CXXRecordDecl *ClassDecl) {
1670 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1671 if (!LangOpts.CPlusPlus0x)
1672 return Diag(Loc, diag::err_delegation_0x_only)
1673 << TInfo->getTypeLoc().getLocalSourceRange();
1674
1675 // Initialize the object.
1676 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1677 QualType(ClassDecl->getTypeForDecl(), 0));
1678 InitializationKind Kind =
1679 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1680
1681 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1682
1683 ExprResult DelegationInit =
1684 InitSeq.Perform(*this, DelegationEntity, Kind,
1685 MultiExprArg(*this, Args, NumArgs), 0);
1686 if (DelegationInit.isInvalid())
1687 return true;
1688
1689 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1690 CXXConstructorDecl *Constructor
1691 = ConExpr->getConstructor();
1692 assert(Constructor && "Delegating constructor with no target?");
1693
1694 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1695
1696 // C++0x [class.base.init]p7:
1697 // The initialization of each base and member constitutes a
1698 // full-expression.
1699 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1700 if (DelegationInit.isInvalid())
1701 return true;
1702
1703 assert(!CurContext->isDependentContext());
1704 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1705 DelegationInit.takeAs<Expr>(),
1706 RParenLoc);
1707 }
1708
1709 MemInitResult
BuildBaseInitializer(QualType BaseType,TypeSourceInfo * BaseTInfo,Expr ** Args,unsigned NumArgs,SourceLocation LParenLoc,SourceLocation RParenLoc,CXXRecordDecl * ClassDecl,SourceLocation EllipsisLoc)1710 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1711 Expr **Args, unsigned NumArgs,
1712 SourceLocation LParenLoc, SourceLocation RParenLoc,
1713 CXXRecordDecl *ClassDecl,
1714 SourceLocation EllipsisLoc) {
1715 bool HasDependentArg = false;
1716 for (unsigned i = 0; i < NumArgs; i++)
1717 HasDependentArg |= Args[i]->isTypeDependent();
1718
1719 SourceLocation BaseLoc
1720 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1721
1722 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1723 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1724 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1725
1726 // C++ [class.base.init]p2:
1727 // [...] Unless the mem-initializer-id names a nonstatic data
1728 // member of the constructor's class or a direct or virtual base
1729 // of that class, the mem-initializer is ill-formed. A
1730 // mem-initializer-list can initialize a base class using any
1731 // name that denotes that base class type.
1732 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1733
1734 if (EllipsisLoc.isValid()) {
1735 // This is a pack expansion.
1736 if (!BaseType->containsUnexpandedParameterPack()) {
1737 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1738 << SourceRange(BaseLoc, RParenLoc);
1739
1740 EllipsisLoc = SourceLocation();
1741 }
1742 } else {
1743 // Check for any unexpanded parameter packs.
1744 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1745 return true;
1746
1747 for (unsigned I = 0; I != NumArgs; ++I)
1748 if (DiagnoseUnexpandedParameterPack(Args[I]))
1749 return true;
1750 }
1751
1752 // Check for direct and virtual base classes.
1753 const CXXBaseSpecifier *DirectBaseSpec = 0;
1754 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1755 if (!Dependent) {
1756 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1757 BaseType))
1758 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1759 LParenLoc, RParenLoc, ClassDecl);
1760
1761 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1762 VirtualBaseSpec);
1763
1764 // C++ [base.class.init]p2:
1765 // Unless the mem-initializer-id names a nonstatic data member of the
1766 // constructor's class or a direct or virtual base of that class, the
1767 // mem-initializer is ill-formed.
1768 if (!DirectBaseSpec && !VirtualBaseSpec) {
1769 // If the class has any dependent bases, then it's possible that
1770 // one of those types will resolve to the same type as
1771 // BaseType. Therefore, just treat this as a dependent base
1772 // class initialization. FIXME: Should we try to check the
1773 // initialization anyway? It seems odd.
1774 if (ClassDecl->hasAnyDependentBases())
1775 Dependent = true;
1776 else
1777 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1778 << BaseType << Context.getTypeDeclType(ClassDecl)
1779 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1780 }
1781 }
1782
1783 if (Dependent) {
1784 // Can't check initialization for a base of dependent type or when
1785 // any of the arguments are type-dependent expressions.
1786 ExprResult BaseInit
1787 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1788 RParenLoc, BaseType));
1789
1790 DiscardCleanupsInEvaluationContext();
1791
1792 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1793 /*IsVirtual=*/false,
1794 LParenLoc,
1795 BaseInit.takeAs<Expr>(),
1796 RParenLoc,
1797 EllipsisLoc);
1798 }
1799
1800 // C++ [base.class.init]p2:
1801 // If a mem-initializer-id is ambiguous because it designates both
1802 // a direct non-virtual base class and an inherited virtual base
1803 // class, the mem-initializer is ill-formed.
1804 if (DirectBaseSpec && VirtualBaseSpec)
1805 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1806 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1807
1808 CXXBaseSpecifier *BaseSpec
1809 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1810 if (!BaseSpec)
1811 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1812
1813 // Initialize the base.
1814 InitializedEntity BaseEntity =
1815 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1816 InitializationKind Kind =
1817 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1818
1819 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1820
1821 ExprResult BaseInit =
1822 InitSeq.Perform(*this, BaseEntity, Kind,
1823 MultiExprArg(*this, Args, NumArgs), 0);
1824 if (BaseInit.isInvalid())
1825 return true;
1826
1827 CheckImplicitConversions(BaseInit.get(), LParenLoc);
1828
1829 // C++0x [class.base.init]p7:
1830 // The initialization of each base and member constitutes a
1831 // full-expression.
1832 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1833 if (BaseInit.isInvalid())
1834 return true;
1835
1836 // If we are in a dependent context, template instantiation will
1837 // perform this type-checking again. Just save the arguments that we
1838 // received in a ParenListExpr.
1839 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1840 // of the information that we have about the base
1841 // initializer. However, deconstructing the ASTs is a dicey process,
1842 // and this approach is far more likely to get the corner cases right.
1843 if (CurContext->isDependentContext()) {
1844 ExprResult Init
1845 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1846 RParenLoc, BaseType));
1847 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1848 BaseSpec->isVirtual(),
1849 LParenLoc,
1850 Init.takeAs<Expr>(),
1851 RParenLoc,
1852 EllipsisLoc);
1853 }
1854
1855 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1856 BaseSpec->isVirtual(),
1857 LParenLoc,
1858 BaseInit.takeAs<Expr>(),
1859 RParenLoc,
1860 EllipsisLoc);
1861 }
1862
1863 /// ImplicitInitializerKind - How an implicit base or member initializer should
1864 /// initialize its base or member.
1865 enum ImplicitInitializerKind {
1866 IIK_Default,
1867 IIK_Copy,
1868 IIK_Move
1869 };
1870
1871 static bool
BuildImplicitBaseInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,CXXBaseSpecifier * BaseSpec,bool IsInheritedVirtualBase,CXXCtorInitializer * & CXXBaseInit)1872 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1873 ImplicitInitializerKind ImplicitInitKind,
1874 CXXBaseSpecifier *BaseSpec,
1875 bool IsInheritedVirtualBase,
1876 CXXCtorInitializer *&CXXBaseInit) {
1877 InitializedEntity InitEntity
1878 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1879 IsInheritedVirtualBase);
1880
1881 ExprResult BaseInit;
1882
1883 switch (ImplicitInitKind) {
1884 case IIK_Default: {
1885 InitializationKind InitKind
1886 = InitializationKind::CreateDefault(Constructor->getLocation());
1887 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1888 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1889 MultiExprArg(SemaRef, 0, 0));
1890 break;
1891 }
1892
1893 case IIK_Copy: {
1894 ParmVarDecl *Param = Constructor->getParamDecl(0);
1895 QualType ParamType = Param->getType().getNonReferenceType();
1896
1897 Expr *CopyCtorArg =
1898 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1899 Constructor->getLocation(), ParamType,
1900 VK_LValue, 0);
1901
1902 // Cast to the base class to avoid ambiguities.
1903 QualType ArgTy =
1904 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1905 ParamType.getQualifiers());
1906
1907 CXXCastPath BasePath;
1908 BasePath.push_back(BaseSpec);
1909 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1910 CK_UncheckedDerivedToBase,
1911 VK_LValue, &BasePath).take();
1912
1913 InitializationKind InitKind
1914 = InitializationKind::CreateDirect(Constructor->getLocation(),
1915 SourceLocation(), SourceLocation());
1916 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1917 &CopyCtorArg, 1);
1918 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1919 MultiExprArg(&CopyCtorArg, 1));
1920 break;
1921 }
1922
1923 case IIK_Move:
1924 assert(false && "Unhandled initializer kind!");
1925 }
1926
1927 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
1928 if (BaseInit.isInvalid())
1929 return true;
1930
1931 CXXBaseInit =
1932 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
1933 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1934 SourceLocation()),
1935 BaseSpec->isVirtual(),
1936 SourceLocation(),
1937 BaseInit.takeAs<Expr>(),
1938 SourceLocation(),
1939 SourceLocation());
1940
1941 return false;
1942 }
1943
1944 static bool
BuildImplicitMemberInitializer(Sema & SemaRef,CXXConstructorDecl * Constructor,ImplicitInitializerKind ImplicitInitKind,FieldDecl * Field,CXXCtorInitializer * & CXXMemberInit)1945 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1946 ImplicitInitializerKind ImplicitInitKind,
1947 FieldDecl *Field,
1948 CXXCtorInitializer *&CXXMemberInit) {
1949 if (Field->isInvalidDecl())
1950 return true;
1951
1952 SourceLocation Loc = Constructor->getLocation();
1953
1954 if (ImplicitInitKind == IIK_Copy) {
1955 ParmVarDecl *Param = Constructor->getParamDecl(0);
1956 QualType ParamType = Param->getType().getNonReferenceType();
1957
1958 // Suppress copying zero-width bitfields.
1959 if (const Expr *Width = Field->getBitWidth())
1960 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1961 return false;
1962
1963 Expr *MemberExprBase =
1964 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1965 Loc, ParamType, VK_LValue, 0);
1966
1967 // Build a reference to this field within the parameter.
1968 CXXScopeSpec SS;
1969 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1970 Sema::LookupMemberName);
1971 MemberLookup.addDecl(Field, AS_public);
1972 MemberLookup.resolveKind();
1973 ExprResult CopyCtorArg
1974 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
1975 ParamType, Loc,
1976 /*IsArrow=*/false,
1977 SS,
1978 /*FirstQualifierInScope=*/0,
1979 MemberLookup,
1980 /*TemplateArgs=*/0);
1981 if (CopyCtorArg.isInvalid())
1982 return true;
1983
1984 // When the field we are copying is an array, create index variables for
1985 // each dimension of the array. We use these index variables to subscript
1986 // the source array, and other clients (e.g., CodeGen) will perform the
1987 // necessary iteration with these index variables.
1988 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1989 QualType BaseType = Field->getType();
1990 QualType SizeType = SemaRef.Context.getSizeType();
1991 while (const ConstantArrayType *Array
1992 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1993 // Create the iteration variable for this array index.
1994 IdentifierInfo *IterationVarName = 0;
1995 {
1996 llvm::SmallString<8> Str;
1997 llvm::raw_svector_ostream OS(Str);
1998 OS << "__i" << IndexVariables.size();
1999 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2000 }
2001 VarDecl *IterationVar
2002 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2003 IterationVarName, SizeType,
2004 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2005 SC_None, SC_None);
2006 IndexVariables.push_back(IterationVar);
2007
2008 // Create a reference to the iteration variable.
2009 ExprResult IterationVarRef
2010 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2011 assert(!IterationVarRef.isInvalid() &&
2012 "Reference to invented variable cannot fail!");
2013
2014 // Subscript the array with this iteration variable.
2015 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
2016 Loc,
2017 IterationVarRef.take(),
2018 Loc);
2019 if (CopyCtorArg.isInvalid())
2020 return true;
2021
2022 BaseType = Array->getElementType();
2023 }
2024
2025 // Construct the entity that we will be initializing. For an array, this
2026 // will be first element in the array, which may require several levels
2027 // of array-subscript entities.
2028 llvm::SmallVector<InitializedEntity, 4> Entities;
2029 Entities.reserve(1 + IndexVariables.size());
2030 Entities.push_back(InitializedEntity::InitializeMember(Field));
2031 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2032 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2033 0,
2034 Entities.back()));
2035
2036 // Direct-initialize to use the copy constructor.
2037 InitializationKind InitKind =
2038 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2039
2040 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2041 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2042 &CopyCtorArgE, 1);
2043
2044 ExprResult MemberInit
2045 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2046 MultiExprArg(&CopyCtorArgE, 1));
2047 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2048 if (MemberInit.isInvalid())
2049 return true;
2050
2051 CXXMemberInit
2052 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
2053 MemberInit.takeAs<Expr>(), Loc,
2054 IndexVariables.data(),
2055 IndexVariables.size());
2056 return false;
2057 }
2058
2059 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2060
2061 QualType FieldBaseElementType =
2062 SemaRef.Context.getBaseElementType(Field->getType());
2063
2064 if (FieldBaseElementType->isRecordType()) {
2065 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
2066 InitializationKind InitKind =
2067 InitializationKind::CreateDefault(Loc);
2068
2069 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2070 ExprResult MemberInit =
2071 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2072
2073 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2074 if (MemberInit.isInvalid())
2075 return true;
2076
2077 CXXMemberInit =
2078 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2079 Field, Loc, Loc,
2080 MemberInit.get(),
2081 Loc);
2082 return false;
2083 }
2084
2085 if (!Field->getParent()->isUnion()) {
2086 if (FieldBaseElementType->isReferenceType()) {
2087 SemaRef.Diag(Constructor->getLocation(),
2088 diag::err_uninitialized_member_in_ctor)
2089 << (int)Constructor->isImplicit()
2090 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2091 << 0 << Field->getDeclName();
2092 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2093 return true;
2094 }
2095
2096 if (FieldBaseElementType.isConstQualified()) {
2097 SemaRef.Diag(Constructor->getLocation(),
2098 diag::err_uninitialized_member_in_ctor)
2099 << (int)Constructor->isImplicit()
2100 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2101 << 1 << Field->getDeclName();
2102 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2103 return true;
2104 }
2105 }
2106
2107 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2108 FieldBaseElementType->isObjCRetainableType() &&
2109 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2110 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2111 // Instant objects:
2112 // Default-initialize Objective-C pointers to NULL.
2113 CXXMemberInit
2114 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2115 Loc, Loc,
2116 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2117 Loc);
2118 return false;
2119 }
2120
2121 // Nothing to initialize.
2122 CXXMemberInit = 0;
2123 return false;
2124 }
2125
2126 namespace {
2127 struct BaseAndFieldInfo {
2128 Sema &S;
2129 CXXConstructorDecl *Ctor;
2130 bool AnyErrorsInInits;
2131 ImplicitInitializerKind IIK;
2132 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2133 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
2134
BaseAndFieldInfo__anon87ee27050211::BaseAndFieldInfo2135 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2136 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2137 // FIXME: Handle implicit move constructors.
2138 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2139 IIK = IIK_Copy;
2140 else
2141 IIK = IIK_Default;
2142 }
2143 };
2144 }
2145
CollectFieldInitializer(Sema & SemaRef,BaseAndFieldInfo & Info,FieldDecl * Top,FieldDecl * Field)2146 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2147 FieldDecl *Top, FieldDecl *Field) {
2148
2149 // Overwhelmingly common case: we have a direct initializer for this field.
2150 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2151 Info.AllToInit.push_back(Init);
2152 return false;
2153 }
2154
2155 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2156 // has a brace-or-equal-initializer, the entity is initialized as specified
2157 // in [dcl.init].
2158 if (Field->hasInClassInitializer()) {
2159 Info.AllToInit.push_back(
2160 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2161 SourceLocation(),
2162 SourceLocation(), 0,
2163 SourceLocation()));
2164 return false;
2165 }
2166
2167 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2168 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2169 assert(FieldClassType && "anonymous struct/union without record type");
2170 CXXRecordDecl *FieldClassDecl
2171 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2172
2173 // Even though union members never have non-trivial default
2174 // constructions in C++03, we still build member initializers for aggregate
2175 // record types which can be union members, and C++0x allows non-trivial
2176 // default constructors for union members, so we ensure that only one
2177 // member is initialized for these.
2178 if (FieldClassDecl->isUnion()) {
2179 // First check for an explicit initializer for one field.
2180 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2181 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2182 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
2183 Info.AllToInit.push_back(Init);
2184
2185 // Once we've initialized a field of an anonymous union, the union
2186 // field in the class is also initialized, so exit immediately.
2187 return false;
2188 } else if ((*FA)->isAnonymousStructOrUnion()) {
2189 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2190 return true;
2191 }
2192 }
2193
2194 // FIXME: C++0x unrestricted unions might call a default constructor here.
2195 return false;
2196 } else {
2197 // For structs, we simply descend through to initialize all members where
2198 // necessary.
2199 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2200 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2201 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2202 return true;
2203 }
2204 }
2205 }
2206
2207 // Don't try to build an implicit initializer if there were semantic
2208 // errors in any of the initializers (and therefore we might be
2209 // missing some that the user actually wrote).
2210 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2211 return false;
2212
2213 CXXCtorInitializer *Init = 0;
2214 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2215 return true;
2216
2217 if (Init)
2218 Info.AllToInit.push_back(Init);
2219
2220 return false;
2221 }
2222
2223 bool
SetDelegatingInitializer(CXXConstructorDecl * Constructor,CXXCtorInitializer * Initializer)2224 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2225 CXXCtorInitializer *Initializer) {
2226 assert(Initializer->isDelegatingInitializer());
2227 Constructor->setNumCtorInitializers(1);
2228 CXXCtorInitializer **initializer =
2229 new (Context) CXXCtorInitializer*[1];
2230 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2231 Constructor->setCtorInitializers(initializer);
2232
2233 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2234 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2235 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2236 }
2237
2238 DelegatingCtorDecls.push_back(Constructor);
2239
2240 return false;
2241 }
2242
SetCtorInitializers(CXXConstructorDecl * Constructor,CXXCtorInitializer ** Initializers,unsigned NumInitializers,bool AnyErrors)2243 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2244 CXXCtorInitializer **Initializers,
2245 unsigned NumInitializers,
2246 bool AnyErrors) {
2247 if (Constructor->getDeclContext()->isDependentContext()) {
2248 // Just store the initializers as written, they will be checked during
2249 // instantiation.
2250 if (NumInitializers > 0) {
2251 Constructor->setNumCtorInitializers(NumInitializers);
2252 CXXCtorInitializer **baseOrMemberInitializers =
2253 new (Context) CXXCtorInitializer*[NumInitializers];
2254 memcpy(baseOrMemberInitializers, Initializers,
2255 NumInitializers * sizeof(CXXCtorInitializer*));
2256 Constructor->setCtorInitializers(baseOrMemberInitializers);
2257 }
2258
2259 return false;
2260 }
2261
2262 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2263
2264 // We need to build the initializer AST according to order of construction
2265 // and not what user specified in the Initializers list.
2266 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2267 if (!ClassDecl)
2268 return true;
2269
2270 bool HadError = false;
2271
2272 for (unsigned i = 0; i < NumInitializers; i++) {
2273 CXXCtorInitializer *Member = Initializers[i];
2274
2275 if (Member->isBaseInitializer())
2276 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2277 else
2278 Info.AllBaseFields[Member->getAnyMember()] = Member;
2279 }
2280
2281 // Keep track of the direct virtual bases.
2282 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2283 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2284 E = ClassDecl->bases_end(); I != E; ++I) {
2285 if (I->isVirtual())
2286 DirectVBases.insert(I);
2287 }
2288
2289 // Push virtual bases before others.
2290 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2291 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2292
2293 if (CXXCtorInitializer *Value
2294 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2295 Info.AllToInit.push_back(Value);
2296 } else if (!AnyErrors) {
2297 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2298 CXXCtorInitializer *CXXBaseInit;
2299 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2300 VBase, IsInheritedVirtualBase,
2301 CXXBaseInit)) {
2302 HadError = true;
2303 continue;
2304 }
2305
2306 Info.AllToInit.push_back(CXXBaseInit);
2307 }
2308 }
2309
2310 // Non-virtual bases.
2311 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2312 E = ClassDecl->bases_end(); Base != E; ++Base) {
2313 // Virtuals are in the virtual base list and already constructed.
2314 if (Base->isVirtual())
2315 continue;
2316
2317 if (CXXCtorInitializer *Value
2318 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2319 Info.AllToInit.push_back(Value);
2320 } else if (!AnyErrors) {
2321 CXXCtorInitializer *CXXBaseInit;
2322 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2323 Base, /*IsInheritedVirtualBase=*/false,
2324 CXXBaseInit)) {
2325 HadError = true;
2326 continue;
2327 }
2328
2329 Info.AllToInit.push_back(CXXBaseInit);
2330 }
2331 }
2332
2333 // Fields.
2334 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2335 E = ClassDecl->field_end(); Field != E; ++Field) {
2336 if ((*Field)->getType()->isIncompleteArrayType()) {
2337 assert(ClassDecl->hasFlexibleArrayMember() &&
2338 "Incomplete array type is not valid");
2339 continue;
2340 }
2341 if (CollectFieldInitializer(*this, Info, *Field, *Field))
2342 HadError = true;
2343 }
2344
2345 NumInitializers = Info.AllToInit.size();
2346 if (NumInitializers > 0) {
2347 Constructor->setNumCtorInitializers(NumInitializers);
2348 CXXCtorInitializer **baseOrMemberInitializers =
2349 new (Context) CXXCtorInitializer*[NumInitializers];
2350 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2351 NumInitializers * sizeof(CXXCtorInitializer*));
2352 Constructor->setCtorInitializers(baseOrMemberInitializers);
2353
2354 // Constructors implicitly reference the base and member
2355 // destructors.
2356 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2357 Constructor->getParent());
2358 }
2359
2360 return HadError;
2361 }
2362
GetKeyForTopLevelField(FieldDecl * Field)2363 static void *GetKeyForTopLevelField(FieldDecl *Field) {
2364 // For anonymous unions, use the class declaration as the key.
2365 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2366 if (RT->getDecl()->isAnonymousStructOrUnion())
2367 return static_cast<void *>(RT->getDecl());
2368 }
2369 return static_cast<void *>(Field);
2370 }
2371
GetKeyForBase(ASTContext & Context,QualType BaseType)2372 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2373 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2374 }
2375
GetKeyForMember(ASTContext & Context,CXXCtorInitializer * Member)2376 static void *GetKeyForMember(ASTContext &Context,
2377 CXXCtorInitializer *Member) {
2378 if (!Member->isAnyMemberInitializer())
2379 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2380
2381 // For fields injected into the class via declaration of an anonymous union,
2382 // use its anonymous union class declaration as the unique key.
2383 FieldDecl *Field = Member->getAnyMember();
2384
2385 // If the field is a member of an anonymous struct or union, our key
2386 // is the anonymous record decl that's a direct child of the class.
2387 RecordDecl *RD = Field->getParent();
2388 if (RD->isAnonymousStructOrUnion()) {
2389 while (true) {
2390 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2391 if (Parent->isAnonymousStructOrUnion())
2392 RD = Parent;
2393 else
2394 break;
2395 }
2396
2397 return static_cast<void *>(RD);
2398 }
2399
2400 return static_cast<void *>(Field);
2401 }
2402
2403 static void
DiagnoseBaseOrMemInitializerOrder(Sema & SemaRef,const CXXConstructorDecl * Constructor,CXXCtorInitializer ** Inits,unsigned NumInits)2404 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2405 const CXXConstructorDecl *Constructor,
2406 CXXCtorInitializer **Inits,
2407 unsigned NumInits) {
2408 if (Constructor->getDeclContext()->isDependentContext())
2409 return;
2410
2411 // Don't check initializers order unless the warning is enabled at the
2412 // location of at least one initializer.
2413 bool ShouldCheckOrder = false;
2414 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2415 CXXCtorInitializer *Init = Inits[InitIndex];
2416 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2417 Init->getSourceLocation())
2418 != Diagnostic::Ignored) {
2419 ShouldCheckOrder = true;
2420 break;
2421 }
2422 }
2423 if (!ShouldCheckOrder)
2424 return;
2425
2426 // Build the list of bases and members in the order that they'll
2427 // actually be initialized. The explicit initializers should be in
2428 // this same order but may be missing things.
2429 llvm::SmallVector<const void*, 32> IdealInitKeys;
2430
2431 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2432
2433 // 1. Virtual bases.
2434 for (CXXRecordDecl::base_class_const_iterator VBase =
2435 ClassDecl->vbases_begin(),
2436 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2437 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2438
2439 // 2. Non-virtual bases.
2440 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2441 E = ClassDecl->bases_end(); Base != E; ++Base) {
2442 if (Base->isVirtual())
2443 continue;
2444 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2445 }
2446
2447 // 3. Direct fields.
2448 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2449 E = ClassDecl->field_end(); Field != E; ++Field)
2450 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2451
2452 unsigned NumIdealInits = IdealInitKeys.size();
2453 unsigned IdealIndex = 0;
2454
2455 CXXCtorInitializer *PrevInit = 0;
2456 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2457 CXXCtorInitializer *Init = Inits[InitIndex];
2458 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2459
2460 // Scan forward to try to find this initializer in the idealized
2461 // initializers list.
2462 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2463 if (InitKey == IdealInitKeys[IdealIndex])
2464 break;
2465
2466 // If we didn't find this initializer, it must be because we
2467 // scanned past it on a previous iteration. That can only
2468 // happen if we're out of order; emit a warning.
2469 if (IdealIndex == NumIdealInits && PrevInit) {
2470 Sema::SemaDiagnosticBuilder D =
2471 SemaRef.Diag(PrevInit->getSourceLocation(),
2472 diag::warn_initializer_out_of_order);
2473
2474 if (PrevInit->isAnyMemberInitializer())
2475 D << 0 << PrevInit->getAnyMember()->getDeclName();
2476 else
2477 D << 1 << PrevInit->getBaseClassInfo()->getType();
2478
2479 if (Init->isAnyMemberInitializer())
2480 D << 0 << Init->getAnyMember()->getDeclName();
2481 else
2482 D << 1 << Init->getBaseClassInfo()->getType();
2483
2484 // Move back to the initializer's location in the ideal list.
2485 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2486 if (InitKey == IdealInitKeys[IdealIndex])
2487 break;
2488
2489 assert(IdealIndex != NumIdealInits &&
2490 "initializer not found in initializer list");
2491 }
2492
2493 PrevInit = Init;
2494 }
2495 }
2496
2497 namespace {
CheckRedundantInit(Sema & S,CXXCtorInitializer * Init,CXXCtorInitializer * & PrevInit)2498 bool CheckRedundantInit(Sema &S,
2499 CXXCtorInitializer *Init,
2500 CXXCtorInitializer *&PrevInit) {
2501 if (!PrevInit) {
2502 PrevInit = Init;
2503 return false;
2504 }
2505
2506 if (FieldDecl *Field = Init->getMember())
2507 S.Diag(Init->getSourceLocation(),
2508 diag::err_multiple_mem_initialization)
2509 << Field->getDeclName()
2510 << Init->getSourceRange();
2511 else {
2512 const Type *BaseClass = Init->getBaseClass();
2513 assert(BaseClass && "neither field nor base");
2514 S.Diag(Init->getSourceLocation(),
2515 diag::err_multiple_base_initialization)
2516 << QualType(BaseClass, 0)
2517 << Init->getSourceRange();
2518 }
2519 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2520 << 0 << PrevInit->getSourceRange();
2521
2522 return true;
2523 }
2524
2525 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2526 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2527
CheckRedundantUnionInit(Sema & S,CXXCtorInitializer * Init,RedundantUnionMap & Unions)2528 bool CheckRedundantUnionInit(Sema &S,
2529 CXXCtorInitializer *Init,
2530 RedundantUnionMap &Unions) {
2531 FieldDecl *Field = Init->getAnyMember();
2532 RecordDecl *Parent = Field->getParent();
2533 if (!Parent->isAnonymousStructOrUnion())
2534 return false;
2535
2536 NamedDecl *Child = Field;
2537 do {
2538 if (Parent->isUnion()) {
2539 UnionEntry &En = Unions[Parent];
2540 if (En.first && En.first != Child) {
2541 S.Diag(Init->getSourceLocation(),
2542 diag::err_multiple_mem_union_initialization)
2543 << Field->getDeclName()
2544 << Init->getSourceRange();
2545 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2546 << 0 << En.second->getSourceRange();
2547 return true;
2548 } else if (!En.first) {
2549 En.first = Child;
2550 En.second = Init;
2551 }
2552 }
2553
2554 Child = Parent;
2555 Parent = cast<RecordDecl>(Parent->getDeclContext());
2556 } while (Parent->isAnonymousStructOrUnion());
2557
2558 return false;
2559 }
2560 }
2561
2562 /// ActOnMemInitializers - Handle the member initializers for a constructor.
ActOnMemInitializers(Decl * ConstructorDecl,SourceLocation ColonLoc,MemInitTy ** meminits,unsigned NumMemInits,bool AnyErrors)2563 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2564 SourceLocation ColonLoc,
2565 MemInitTy **meminits, unsigned NumMemInits,
2566 bool AnyErrors) {
2567 if (!ConstructorDecl)
2568 return;
2569
2570 AdjustDeclIfTemplate(ConstructorDecl);
2571
2572 CXXConstructorDecl *Constructor
2573 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2574
2575 if (!Constructor) {
2576 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2577 return;
2578 }
2579
2580 CXXCtorInitializer **MemInits =
2581 reinterpret_cast<CXXCtorInitializer **>(meminits);
2582
2583 // Mapping for the duplicate initializers check.
2584 // For member initializers, this is keyed with a FieldDecl*.
2585 // For base initializers, this is keyed with a Type*.
2586 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2587
2588 // Mapping for the inconsistent anonymous-union initializers check.
2589 RedundantUnionMap MemberUnions;
2590
2591 bool HadError = false;
2592 for (unsigned i = 0; i < NumMemInits; i++) {
2593 CXXCtorInitializer *Init = MemInits[i];
2594
2595 // Set the source order index.
2596 Init->setSourceOrder(i);
2597
2598 if (Init->isAnyMemberInitializer()) {
2599 FieldDecl *Field = Init->getAnyMember();
2600 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2601 CheckRedundantUnionInit(*this, Init, MemberUnions))
2602 HadError = true;
2603 } else if (Init->isBaseInitializer()) {
2604 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2605 if (CheckRedundantInit(*this, Init, Members[Key]))
2606 HadError = true;
2607 } else {
2608 assert(Init->isDelegatingInitializer());
2609 // This must be the only initializer
2610 if (i != 0 || NumMemInits > 1) {
2611 Diag(MemInits[0]->getSourceLocation(),
2612 diag::err_delegating_initializer_alone)
2613 << MemInits[0]->getSourceRange();
2614 HadError = true;
2615 // We will treat this as being the only initializer.
2616 }
2617 SetDelegatingInitializer(Constructor, MemInits[i]);
2618 // Return immediately as the initializer is set.
2619 return;
2620 }
2621 }
2622
2623 if (HadError)
2624 return;
2625
2626 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2627
2628 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2629 }
2630
2631 void
MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,CXXRecordDecl * ClassDecl)2632 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2633 CXXRecordDecl *ClassDecl) {
2634 // Ignore dependent contexts.
2635 if (ClassDecl->isDependentContext())
2636 return;
2637
2638 // FIXME: all the access-control diagnostics are positioned on the
2639 // field/base declaration. That's probably good; that said, the
2640 // user might reasonably want to know why the destructor is being
2641 // emitted, and we currently don't say.
2642
2643 // Non-static data members.
2644 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2645 E = ClassDecl->field_end(); I != E; ++I) {
2646 FieldDecl *Field = *I;
2647 if (Field->isInvalidDecl())
2648 continue;
2649 QualType FieldType = Context.getBaseElementType(Field->getType());
2650
2651 const RecordType* RT = FieldType->getAs<RecordType>();
2652 if (!RT)
2653 continue;
2654
2655 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2656 if (FieldClassDecl->isInvalidDecl())
2657 continue;
2658 if (FieldClassDecl->hasTrivialDestructor())
2659 continue;
2660
2661 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2662 assert(Dtor && "No dtor found for FieldClassDecl!");
2663 CheckDestructorAccess(Field->getLocation(), Dtor,
2664 PDiag(diag::err_access_dtor_field)
2665 << Field->getDeclName()
2666 << FieldType);
2667
2668 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2669 }
2670
2671 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2672
2673 // Bases.
2674 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2675 E = ClassDecl->bases_end(); Base != E; ++Base) {
2676 // Bases are always records in a well-formed non-dependent class.
2677 const RecordType *RT = Base->getType()->getAs<RecordType>();
2678
2679 // Remember direct virtual bases.
2680 if (Base->isVirtual())
2681 DirectVirtualBases.insert(RT);
2682
2683 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2684 // If our base class is invalid, we probably can't get its dtor anyway.
2685 if (BaseClassDecl->isInvalidDecl())
2686 continue;
2687 // Ignore trivial destructors.
2688 if (BaseClassDecl->hasTrivialDestructor())
2689 continue;
2690
2691 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2692 assert(Dtor && "No dtor found for BaseClassDecl!");
2693
2694 // FIXME: caret should be on the start of the class name
2695 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2696 PDiag(diag::err_access_dtor_base)
2697 << Base->getType()
2698 << Base->getSourceRange());
2699
2700 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2701 }
2702
2703 // Virtual bases.
2704 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2705 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2706
2707 // Bases are always records in a well-formed non-dependent class.
2708 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2709
2710 // Ignore direct virtual bases.
2711 if (DirectVirtualBases.count(RT))
2712 continue;
2713
2714 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2715 // If our base class is invalid, we probably can't get its dtor anyway.
2716 if (BaseClassDecl->isInvalidDecl())
2717 continue;
2718 // Ignore trivial destructors.
2719 if (BaseClassDecl->hasTrivialDestructor())
2720 continue;
2721
2722 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2723 assert(Dtor && "No dtor found for BaseClassDecl!");
2724 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2725 PDiag(diag::err_access_dtor_vbase)
2726 << VBase->getType());
2727
2728 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2729 }
2730 }
2731
ActOnDefaultCtorInitializers(Decl * CDtorDecl)2732 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2733 if (!CDtorDecl)
2734 return;
2735
2736 if (CXXConstructorDecl *Constructor
2737 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2738 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2739 }
2740
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,AbstractDiagSelID SelID)2741 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2742 unsigned DiagID, AbstractDiagSelID SelID) {
2743 if (SelID == -1)
2744 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2745 else
2746 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2747 }
2748
RequireNonAbstractType(SourceLocation Loc,QualType T,const PartialDiagnostic & PD)2749 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2750 const PartialDiagnostic &PD) {
2751 if (!getLangOptions().CPlusPlus)
2752 return false;
2753
2754 if (const ArrayType *AT = Context.getAsArrayType(T))
2755 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2756
2757 if (const PointerType *PT = T->getAs<PointerType>()) {
2758 // Find the innermost pointer type.
2759 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2760 PT = T;
2761
2762 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2763 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2764 }
2765
2766 const RecordType *RT = T->getAs<RecordType>();
2767 if (!RT)
2768 return false;
2769
2770 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2771
2772 // We can't answer whether something is abstract until it has a
2773 // definition. If it's currently being defined, we'll walk back
2774 // over all the declarations when we have a full definition.
2775 const CXXRecordDecl *Def = RD->getDefinition();
2776 if (!Def || Def->isBeingDefined())
2777 return false;
2778
2779 if (!RD->isAbstract())
2780 return false;
2781
2782 Diag(Loc, PD) << RD->getDeclName();
2783 DiagnoseAbstractType(RD);
2784
2785 return true;
2786 }
2787
DiagnoseAbstractType(const CXXRecordDecl * RD)2788 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2789 // Check if we've already emitted the list of pure virtual functions
2790 // for this class.
2791 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2792 return;
2793
2794 CXXFinalOverriderMap FinalOverriders;
2795 RD->getFinalOverriders(FinalOverriders);
2796
2797 // Keep a set of seen pure methods so we won't diagnose the same method
2798 // more than once.
2799 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2800
2801 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2802 MEnd = FinalOverriders.end();
2803 M != MEnd;
2804 ++M) {
2805 for (OverridingMethods::iterator SO = M->second.begin(),
2806 SOEnd = M->second.end();
2807 SO != SOEnd; ++SO) {
2808 // C++ [class.abstract]p4:
2809 // A class is abstract if it contains or inherits at least one
2810 // pure virtual function for which the final overrider is pure
2811 // virtual.
2812
2813 //
2814 if (SO->second.size() != 1)
2815 continue;
2816
2817 if (!SO->second.front().Method->isPure())
2818 continue;
2819
2820 if (!SeenPureMethods.insert(SO->second.front().Method))
2821 continue;
2822
2823 Diag(SO->second.front().Method->getLocation(),
2824 diag::note_pure_virtual_function)
2825 << SO->second.front().Method->getDeclName() << RD->getDeclName();
2826 }
2827 }
2828
2829 if (!PureVirtualClassDiagSet)
2830 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2831 PureVirtualClassDiagSet->insert(RD);
2832 }
2833
2834 namespace {
2835 struct AbstractUsageInfo {
2836 Sema &S;
2837 CXXRecordDecl *Record;
2838 CanQualType AbstractType;
2839 bool Invalid;
2840
AbstractUsageInfo__anon87ee27050411::AbstractUsageInfo2841 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2842 : S(S), Record(Record),
2843 AbstractType(S.Context.getCanonicalType(
2844 S.Context.getTypeDeclType(Record))),
2845 Invalid(false) {}
2846
DiagnoseAbstractType__anon87ee27050411::AbstractUsageInfo2847 void DiagnoseAbstractType() {
2848 if (Invalid) return;
2849 S.DiagnoseAbstractType(Record);
2850 Invalid = true;
2851 }
2852
2853 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2854 };
2855
2856 struct CheckAbstractUsage {
2857 AbstractUsageInfo &Info;
2858 const NamedDecl *Ctx;
2859
CheckAbstractUsage__anon87ee27050411::CheckAbstractUsage2860 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2861 : Info(Info), Ctx(Ctx) {}
2862
Visit__anon87ee27050411::CheckAbstractUsage2863 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2864 switch (TL.getTypeLocClass()) {
2865 #define ABSTRACT_TYPELOC(CLASS, PARENT)
2866 #define TYPELOC(CLASS, PARENT) \
2867 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2868 #include "clang/AST/TypeLocNodes.def"
2869 }
2870 }
2871
Check__anon87ee27050411::CheckAbstractUsage2872 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2873 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2874 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2875 if (!TL.getArg(I))
2876 continue;
2877
2878 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2879 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
2880 }
2881 }
2882
Check__anon87ee27050411::CheckAbstractUsage2883 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2884 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2885 }
2886
Check__anon87ee27050411::CheckAbstractUsage2887 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2888 // Visit the type parameters from a permissive context.
2889 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2890 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2891 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2892 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2893 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2894 // TODO: other template argument types?
2895 }
2896 }
2897
2898 // Visit pointee types from a permissive context.
2899 #define CheckPolymorphic(Type) \
2900 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2901 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2902 }
2903 CheckPolymorphic(PointerTypeLoc)
CheckPolymorphic__anon87ee27050411::CheckAbstractUsage2904 CheckPolymorphic(ReferenceTypeLoc)
2905 CheckPolymorphic(MemberPointerTypeLoc)
2906 CheckPolymorphic(BlockPointerTypeLoc)
2907
2908 /// Handle all the types we haven't given a more specific
2909 /// implementation for above.
2910 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2911 // Every other kind of type that we haven't called out already
2912 // that has an inner type is either (1) sugar or (2) contains that
2913 // inner type in some way as a subobject.
2914 if (TypeLoc Next = TL.getNextTypeLoc())
2915 return Visit(Next, Sel);
2916
2917 // If there's no inner type and we're in a permissive context,
2918 // don't diagnose.
2919 if (Sel == Sema::AbstractNone) return;
2920
2921 // Check whether the type matches the abstract type.
2922 QualType T = TL.getType();
2923 if (T->isArrayType()) {
2924 Sel = Sema::AbstractArrayType;
2925 T = Info.S.Context.getBaseElementType(T);
2926 }
2927 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2928 if (CT != Info.AbstractType) return;
2929
2930 // It matched; do some magic.
2931 if (Sel == Sema::AbstractArrayType) {
2932 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2933 << T << TL.getSourceRange();
2934 } else {
2935 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2936 << Sel << T << TL.getSourceRange();
2937 }
2938 Info.DiagnoseAbstractType();
2939 }
2940 };
2941
CheckType(const NamedDecl * D,TypeLoc TL,Sema::AbstractDiagSelID Sel)2942 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2943 Sema::AbstractDiagSelID Sel) {
2944 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2945 }
2946
2947 }
2948
2949 /// Check for invalid uses of an abstract type in a method declaration.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXMethodDecl * MD)2950 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2951 CXXMethodDecl *MD) {
2952 // No need to do the check on definitions, which require that
2953 // the return/param types be complete.
2954 if (MD->doesThisDeclarationHaveABody())
2955 return;
2956
2957 // For safety's sake, just ignore it if we don't have type source
2958 // information. This should never happen for non-implicit methods,
2959 // but...
2960 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2961 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2962 }
2963
2964 /// Check for invalid uses of an abstract type within a class definition.
CheckAbstractClassUsage(AbstractUsageInfo & Info,CXXRecordDecl * RD)2965 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2966 CXXRecordDecl *RD) {
2967 for (CXXRecordDecl::decl_iterator
2968 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2969 Decl *D = *I;
2970 if (D->isImplicit()) continue;
2971
2972 // Methods and method templates.
2973 if (isa<CXXMethodDecl>(D)) {
2974 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2975 } else if (isa<FunctionTemplateDecl>(D)) {
2976 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2977 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2978
2979 // Fields and static variables.
2980 } else if (isa<FieldDecl>(D)) {
2981 FieldDecl *FD = cast<FieldDecl>(D);
2982 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2983 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2984 } else if (isa<VarDecl>(D)) {
2985 VarDecl *VD = cast<VarDecl>(D);
2986 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2987 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2988
2989 // Nested classes and class templates.
2990 } else if (isa<CXXRecordDecl>(D)) {
2991 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2992 } else if (isa<ClassTemplateDecl>(D)) {
2993 CheckAbstractClassUsage(Info,
2994 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2995 }
2996 }
2997 }
2998
2999 /// \brief Perform semantic checks on a class definition that has been
3000 /// completing, introducing implicitly-declared members, checking for
3001 /// abstract types, etc.
CheckCompletedCXXClass(CXXRecordDecl * Record)3002 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3003 if (!Record)
3004 return;
3005
3006 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3007 AbstractUsageInfo Info(*this, Record);
3008 CheckAbstractClassUsage(Info, Record);
3009 }
3010
3011 // If this is not an aggregate type and has no user-declared constructor,
3012 // complain about any non-static data members of reference or const scalar
3013 // type, since they will never get initializers.
3014 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3015 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3016 bool Complained = false;
3017 for (RecordDecl::field_iterator F = Record->field_begin(),
3018 FEnd = Record->field_end();
3019 F != FEnd; ++F) {
3020 if (F->hasInClassInitializer())
3021 continue;
3022
3023 if (F->getType()->isReferenceType() ||
3024 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3025 if (!Complained) {
3026 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3027 << Record->getTagKind() << Record;
3028 Complained = true;
3029 }
3030
3031 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3032 << F->getType()->isReferenceType()
3033 << F->getDeclName();
3034 }
3035 }
3036 }
3037
3038 if (Record->isDynamicClass() && !Record->isDependentType())
3039 DynamicClasses.push_back(Record);
3040
3041 if (Record->getIdentifier()) {
3042 // C++ [class.mem]p13:
3043 // If T is the name of a class, then each of the following shall have a
3044 // name different from T:
3045 // - every member of every anonymous union that is a member of class T.
3046 //
3047 // C++ [class.mem]p14:
3048 // In addition, if class T has a user-declared constructor (12.1), every
3049 // non-static data member of class T shall have a name different from T.
3050 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3051 R.first != R.second; ++R.first) {
3052 NamedDecl *D = *R.first;
3053 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3054 isa<IndirectFieldDecl>(D)) {
3055 Diag(D->getLocation(), diag::err_member_name_of_class)
3056 << D->getDeclName();
3057 break;
3058 }
3059 }
3060 }
3061
3062 // Warn if the class has virtual methods but non-virtual public destructor.
3063 if (Record->isPolymorphic() && !Record->isDependentType()) {
3064 CXXDestructorDecl *dtor = Record->getDestructor();
3065 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3066 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3067 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3068 }
3069
3070 // See if a method overloads virtual methods in a base
3071 /// class without overriding any.
3072 if (!Record->isDependentType()) {
3073 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3074 MEnd = Record->method_end();
3075 M != MEnd; ++M) {
3076 if (!(*M)->isStatic())
3077 DiagnoseHiddenVirtualMethods(Record, *M);
3078 }
3079 }
3080
3081 // Declare inherited constructors. We do this eagerly here because:
3082 // - The standard requires an eager diagnostic for conflicting inherited
3083 // constructors from different classes.
3084 // - The lazy declaration of the other implicit constructors is so as to not
3085 // waste space and performance on classes that are not meant to be
3086 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3087 // have inherited constructors.
3088 DeclareInheritedConstructors(Record);
3089
3090 if (!Record->isDependentType())
3091 CheckExplicitlyDefaultedMethods(Record);
3092 }
3093
CheckExplicitlyDefaultedMethods(CXXRecordDecl * Record)3094 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3095 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3096 ME = Record->method_end();
3097 MI != ME; ++MI) {
3098 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3099 switch (getSpecialMember(*MI)) {
3100 case CXXDefaultConstructor:
3101 CheckExplicitlyDefaultedDefaultConstructor(
3102 cast<CXXConstructorDecl>(*MI));
3103 break;
3104
3105 case CXXDestructor:
3106 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3107 break;
3108
3109 case CXXCopyConstructor:
3110 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3111 break;
3112
3113 case CXXCopyAssignment:
3114 CheckExplicitlyDefaultedCopyAssignment(*MI);
3115 break;
3116
3117 case CXXMoveConstructor:
3118 case CXXMoveAssignment:
3119 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3120 break;
3121
3122 default:
3123 // FIXME: Do moves once they exist
3124 llvm_unreachable("non-special member explicitly defaulted!");
3125 }
3126 }
3127 }
3128
3129 }
3130
CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl * CD)3131 void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3132 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3133
3134 // Whether this was the first-declared instance of the constructor.
3135 // This affects whether we implicitly add an exception spec (and, eventually,
3136 // constexpr). It is also ill-formed to explicitly default a constructor such
3137 // that it would be deleted. (C++0x [decl.fct.def.default])
3138 bool First = CD == CD->getCanonicalDecl();
3139
3140 bool HadError = false;
3141 if (CD->getNumParams() != 0) {
3142 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3143 << CD->getSourceRange();
3144 HadError = true;
3145 }
3146
3147 ImplicitExceptionSpecification Spec
3148 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3149 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3150 if (EPI.ExceptionSpecType == EST_Delayed) {
3151 // Exception specification depends on some deferred part of the class. We'll
3152 // try again when the class's definition has been fully processed.
3153 return;
3154 }
3155 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3156 *ExceptionType = Context.getFunctionType(
3157 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3158
3159 if (CtorType->hasExceptionSpec()) {
3160 if (CheckEquivalentExceptionSpec(
3161 PDiag(diag::err_incorrect_defaulted_exception_spec)
3162 << CXXDefaultConstructor,
3163 PDiag(),
3164 ExceptionType, SourceLocation(),
3165 CtorType, CD->getLocation())) {
3166 HadError = true;
3167 }
3168 } else if (First) {
3169 // We set the declaration to have the computed exception spec here.
3170 // We know there are no parameters.
3171 EPI.ExtInfo = CtorType->getExtInfo();
3172 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3173 }
3174
3175 if (HadError) {
3176 CD->setInvalidDecl();
3177 return;
3178 }
3179
3180 if (ShouldDeleteDefaultConstructor(CD)) {
3181 if (First) {
3182 CD->setDeletedAsWritten();
3183 } else {
3184 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3185 << CXXDefaultConstructor;
3186 CD->setInvalidDecl();
3187 }
3188 }
3189 }
3190
CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl * CD)3191 void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3192 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3193
3194 // Whether this was the first-declared instance of the constructor.
3195 bool First = CD == CD->getCanonicalDecl();
3196
3197 bool HadError = false;
3198 if (CD->getNumParams() != 1) {
3199 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3200 << CD->getSourceRange();
3201 HadError = true;
3202 }
3203
3204 ImplicitExceptionSpecification Spec(Context);
3205 bool Const;
3206 llvm::tie(Spec, Const) =
3207 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3208
3209 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3210 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3211 *ExceptionType = Context.getFunctionType(
3212 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3213
3214 // Check for parameter type matching.
3215 // This is a copy ctor so we know it's a cv-qualified reference to T.
3216 QualType ArgType = CtorType->getArgType(0);
3217 if (ArgType->getPointeeType().isVolatileQualified()) {
3218 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3219 HadError = true;
3220 }
3221 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3222 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3223 HadError = true;
3224 }
3225
3226 if (CtorType->hasExceptionSpec()) {
3227 if (CheckEquivalentExceptionSpec(
3228 PDiag(diag::err_incorrect_defaulted_exception_spec)
3229 << CXXCopyConstructor,
3230 PDiag(),
3231 ExceptionType, SourceLocation(),
3232 CtorType, CD->getLocation())) {
3233 HadError = true;
3234 }
3235 } else if (First) {
3236 // We set the declaration to have the computed exception spec here.
3237 // We duplicate the one parameter type.
3238 EPI.ExtInfo = CtorType->getExtInfo();
3239 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3240 }
3241
3242 if (HadError) {
3243 CD->setInvalidDecl();
3244 return;
3245 }
3246
3247 if (ShouldDeleteCopyConstructor(CD)) {
3248 if (First) {
3249 CD->setDeletedAsWritten();
3250 } else {
3251 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3252 << CXXCopyConstructor;
3253 CD->setInvalidDecl();
3254 }
3255 }
3256 }
3257
CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl * MD)3258 void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3259 assert(MD->isExplicitlyDefaulted());
3260
3261 // Whether this was the first-declared instance of the operator
3262 bool First = MD == MD->getCanonicalDecl();
3263
3264 bool HadError = false;
3265 if (MD->getNumParams() != 1) {
3266 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3267 << MD->getSourceRange();
3268 HadError = true;
3269 }
3270
3271 QualType ReturnType =
3272 MD->getType()->getAs<FunctionType>()->getResultType();
3273 if (!ReturnType->isLValueReferenceType() ||
3274 !Context.hasSameType(
3275 Context.getCanonicalType(ReturnType->getPointeeType()),
3276 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3277 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3278 HadError = true;
3279 }
3280
3281 ImplicitExceptionSpecification Spec(Context);
3282 bool Const;
3283 llvm::tie(Spec, Const) =
3284 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3285
3286 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3287 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3288 *ExceptionType = Context.getFunctionType(
3289 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3290
3291 QualType ArgType = OperType->getArgType(0);
3292 if (!ArgType->isReferenceType()) {
3293 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3294 HadError = true;
3295 } else {
3296 if (ArgType->getPointeeType().isVolatileQualified()) {
3297 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3298 HadError = true;
3299 }
3300 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3301 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3302 HadError = true;
3303 }
3304 }
3305
3306 if (OperType->getTypeQuals()) {
3307 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3308 HadError = true;
3309 }
3310
3311 if (OperType->hasExceptionSpec()) {
3312 if (CheckEquivalentExceptionSpec(
3313 PDiag(diag::err_incorrect_defaulted_exception_spec)
3314 << CXXCopyAssignment,
3315 PDiag(),
3316 ExceptionType, SourceLocation(),
3317 OperType, MD->getLocation())) {
3318 HadError = true;
3319 }
3320 } else if (First) {
3321 // We set the declaration to have the computed exception spec here.
3322 // We duplicate the one parameter type.
3323 EPI.RefQualifier = OperType->getRefQualifier();
3324 EPI.ExtInfo = OperType->getExtInfo();
3325 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3326 }
3327
3328 if (HadError) {
3329 MD->setInvalidDecl();
3330 return;
3331 }
3332
3333 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3334 if (First) {
3335 MD->setDeletedAsWritten();
3336 } else {
3337 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3338 << CXXCopyAssignment;
3339 MD->setInvalidDecl();
3340 }
3341 }
3342 }
3343
CheckExplicitlyDefaultedDestructor(CXXDestructorDecl * DD)3344 void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3345 assert(DD->isExplicitlyDefaulted());
3346
3347 // Whether this was the first-declared instance of the destructor.
3348 bool First = DD == DD->getCanonicalDecl();
3349
3350 ImplicitExceptionSpecification Spec
3351 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3352 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3353 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3354 *ExceptionType = Context.getFunctionType(
3355 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3356
3357 if (DtorType->hasExceptionSpec()) {
3358 if (CheckEquivalentExceptionSpec(
3359 PDiag(diag::err_incorrect_defaulted_exception_spec)
3360 << CXXDestructor,
3361 PDiag(),
3362 ExceptionType, SourceLocation(),
3363 DtorType, DD->getLocation())) {
3364 DD->setInvalidDecl();
3365 return;
3366 }
3367 } else if (First) {
3368 // We set the declaration to have the computed exception spec here.
3369 // There are no parameters.
3370 EPI.ExtInfo = DtorType->getExtInfo();
3371 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3372 }
3373
3374 if (ShouldDeleteDestructor(DD)) {
3375 if (First) {
3376 DD->setDeletedAsWritten();
3377 } else {
3378 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3379 << CXXDestructor;
3380 DD->setInvalidDecl();
3381 }
3382 }
3383 }
3384
ShouldDeleteDefaultConstructor(CXXConstructorDecl * CD)3385 bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3386 CXXRecordDecl *RD = CD->getParent();
3387 assert(!RD->isDependentType() && "do deletion after instantiation");
3388 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3389 return false;
3390
3391 SourceLocation Loc = CD->getLocation();
3392
3393 // Do access control from the constructor
3394 ContextRAII CtorContext(*this, CD);
3395
3396 bool Union = RD->isUnion();
3397 bool AllConst = true;
3398
3399 // We do this because we should never actually use an anonymous
3400 // union's constructor.
3401 if (Union && RD->isAnonymousStructOrUnion())
3402 return false;
3403
3404 // FIXME: We should put some diagnostic logic right into this function.
3405
3406 // C++0x [class.ctor]/5
3407 // A defaulted default constructor for class X is defined as deleted if:
3408
3409 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3410 BE = RD->bases_end();
3411 BI != BE; ++BI) {
3412 // We'll handle this one later
3413 if (BI->isVirtual())
3414 continue;
3415
3416 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3417 assert(BaseDecl && "base isn't a CXXRecordDecl");
3418
3419 // -- any [direct base class] has a type with a destructor that is
3420 // deleted or inaccessible from the defaulted default constructor
3421 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3422 if (BaseDtor->isDeleted())
3423 return true;
3424 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3425 AR_accessible)
3426 return true;
3427
3428 // -- any [direct base class either] has no default constructor or
3429 // overload resolution as applied to [its] default constructor
3430 // results in an ambiguity or in a function that is deleted or
3431 // inaccessible from the defaulted default constructor
3432 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3433 if (!BaseDefault || BaseDefault->isDeleted())
3434 return true;
3435
3436 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3437 PDiag()) != AR_accessible)
3438 return true;
3439 }
3440
3441 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3442 BE = RD->vbases_end();
3443 BI != BE; ++BI) {
3444 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3445 assert(BaseDecl && "base isn't a CXXRecordDecl");
3446
3447 // -- any [virtual base class] has a type with a destructor that is
3448 // delete or inaccessible from the defaulted default constructor
3449 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3450 if (BaseDtor->isDeleted())
3451 return true;
3452 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3453 AR_accessible)
3454 return true;
3455
3456 // -- any [virtual base class either] has no default constructor or
3457 // overload resolution as applied to [its] default constructor
3458 // results in an ambiguity or in a function that is deleted or
3459 // inaccessible from the defaulted default constructor
3460 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3461 if (!BaseDefault || BaseDefault->isDeleted())
3462 return true;
3463
3464 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3465 PDiag()) != AR_accessible)
3466 return true;
3467 }
3468
3469 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3470 FE = RD->field_end();
3471 FI != FE; ++FI) {
3472 if (FI->isInvalidDecl())
3473 continue;
3474
3475 QualType FieldType = Context.getBaseElementType(FI->getType());
3476 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3477
3478 // -- any non-static data member with no brace-or-equal-initializer is of
3479 // reference type
3480 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3481 return true;
3482
3483 // -- X is a union and all its variant members are of const-qualified type
3484 // (or array thereof)
3485 if (Union && !FieldType.isConstQualified())
3486 AllConst = false;
3487
3488 if (FieldRecord) {
3489 // -- X is a union-like class that has a variant member with a non-trivial
3490 // default constructor
3491 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3492 return true;
3493
3494 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3495 if (FieldDtor->isDeleted())
3496 return true;
3497 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3498 AR_accessible)
3499 return true;
3500
3501 // -- any non-variant non-static data member of const-qualified type (or
3502 // array thereof) with no brace-or-equal-initializer does not have a
3503 // user-provided default constructor
3504 if (FieldType.isConstQualified() &&
3505 !FI->hasInClassInitializer() &&
3506 !FieldRecord->hasUserProvidedDefaultConstructor())
3507 return true;
3508
3509 if (!Union && FieldRecord->isUnion() &&
3510 FieldRecord->isAnonymousStructOrUnion()) {
3511 // We're okay to reuse AllConst here since we only care about the
3512 // value otherwise if we're in a union.
3513 AllConst = true;
3514
3515 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3516 UE = FieldRecord->field_end();
3517 UI != UE; ++UI) {
3518 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3519 CXXRecordDecl *UnionFieldRecord =
3520 UnionFieldType->getAsCXXRecordDecl();
3521
3522 if (!UnionFieldType.isConstQualified())
3523 AllConst = false;
3524
3525 if (UnionFieldRecord &&
3526 !UnionFieldRecord->hasTrivialDefaultConstructor())
3527 return true;
3528 }
3529
3530 if (AllConst)
3531 return true;
3532
3533 // Don't try to initialize the anonymous union
3534 // This is technically non-conformant, but sanity demands it.
3535 continue;
3536 }
3537
3538 // -- any non-static data member with no brace-or-equal-initializer has
3539 // class type M (or array thereof) and either M has no default
3540 // constructor or overload resolution as applied to M's default
3541 // constructor results in an ambiguity or in a function that is deleted
3542 // or inaccessible from the defaulted default constructor.
3543 if (!FI->hasInClassInitializer()) {
3544 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3545 if (!FieldDefault || FieldDefault->isDeleted())
3546 return true;
3547 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3548 PDiag()) != AR_accessible)
3549 return true;
3550 }
3551 } else if (!Union && FieldType.isConstQualified() &&
3552 !FI->hasInClassInitializer()) {
3553 // -- any non-variant non-static data member of const-qualified type (or
3554 // array thereof) with no brace-or-equal-initializer does not have a
3555 // user-provided default constructor
3556 return true;
3557 }
3558 }
3559
3560 if (Union && AllConst)
3561 return true;
3562
3563 return false;
3564 }
3565
ShouldDeleteCopyConstructor(CXXConstructorDecl * CD)3566 bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3567 CXXRecordDecl *RD = CD->getParent();
3568 assert(!RD->isDependentType() && "do deletion after instantiation");
3569 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3570 return false;
3571
3572 SourceLocation Loc = CD->getLocation();
3573
3574 // Do access control from the constructor
3575 ContextRAII CtorContext(*this, CD);
3576
3577 bool Union = RD->isUnion();
3578
3579 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3580 "copy assignment arg has no pointee type");
3581 unsigned ArgQuals =
3582 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3583 Qualifiers::Const : 0;
3584
3585 // We do this because we should never actually use an anonymous
3586 // union's constructor.
3587 if (Union && RD->isAnonymousStructOrUnion())
3588 return false;
3589
3590 // FIXME: We should put some diagnostic logic right into this function.
3591
3592 // C++0x [class.copy]/11
3593 // A defaulted [copy] constructor for class X is defined as delete if X has:
3594
3595 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3596 BE = RD->bases_end();
3597 BI != BE; ++BI) {
3598 // We'll handle this one later
3599 if (BI->isVirtual())
3600 continue;
3601
3602 QualType BaseType = BI->getType();
3603 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3604 assert(BaseDecl && "base isn't a CXXRecordDecl");
3605
3606 // -- any [direct base class] of a type with a destructor that is deleted or
3607 // inaccessible from the defaulted constructor
3608 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3609 if (BaseDtor->isDeleted())
3610 return true;
3611 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3612 AR_accessible)
3613 return true;
3614
3615 // -- a [direct base class] B that cannot be [copied] because overload
3616 // resolution, as applied to B's [copy] constructor, results in an
3617 // ambiguity or a function that is deleted or inaccessible from the
3618 // defaulted constructor
3619 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3620 if (!BaseCtor || BaseCtor->isDeleted())
3621 return true;
3622 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3623 AR_accessible)
3624 return true;
3625 }
3626
3627 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3628 BE = RD->vbases_end();
3629 BI != BE; ++BI) {
3630 QualType BaseType = BI->getType();
3631 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3632 assert(BaseDecl && "base isn't a CXXRecordDecl");
3633
3634 // -- any [virtual base class] of a type with a destructor that is deleted or
3635 // inaccessible from the defaulted constructor
3636 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3637 if (BaseDtor->isDeleted())
3638 return true;
3639 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3640 AR_accessible)
3641 return true;
3642
3643 // -- a [virtual base class] B that cannot be [copied] because overload
3644 // resolution, as applied to B's [copy] constructor, results in an
3645 // ambiguity or a function that is deleted or inaccessible from the
3646 // defaulted constructor
3647 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3648 if (!BaseCtor || BaseCtor->isDeleted())
3649 return true;
3650 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3651 AR_accessible)
3652 return true;
3653 }
3654
3655 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3656 FE = RD->field_end();
3657 FI != FE; ++FI) {
3658 QualType FieldType = Context.getBaseElementType(FI->getType());
3659
3660 // -- for a copy constructor, a non-static data member of rvalue reference
3661 // type
3662 if (FieldType->isRValueReferenceType())
3663 return true;
3664
3665 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3666
3667 if (FieldRecord) {
3668 // This is an anonymous union
3669 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3670 // Anonymous unions inside unions do not variant members create
3671 if (!Union) {
3672 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3673 UE = FieldRecord->field_end();
3674 UI != UE; ++UI) {
3675 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3676 CXXRecordDecl *UnionFieldRecord =
3677 UnionFieldType->getAsCXXRecordDecl();
3678
3679 // -- a variant member with a non-trivial [copy] constructor and X
3680 // is a union-like class
3681 if (UnionFieldRecord &&
3682 !UnionFieldRecord->hasTrivialCopyConstructor())
3683 return true;
3684 }
3685 }
3686
3687 // Don't try to initalize an anonymous union
3688 continue;
3689 } else {
3690 // -- a variant member with a non-trivial [copy] constructor and X is a
3691 // union-like class
3692 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3693 return true;
3694
3695 // -- any [non-static data member] of a type with a destructor that is
3696 // deleted or inaccessible from the defaulted constructor
3697 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3698 if (FieldDtor->isDeleted())
3699 return true;
3700 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3701 AR_accessible)
3702 return true;
3703 }
3704
3705 // -- a [non-static data member of class type (or array thereof)] B that
3706 // cannot be [copied] because overload resolution, as applied to B's
3707 // [copy] constructor, results in an ambiguity or a function that is
3708 // deleted or inaccessible from the defaulted constructor
3709 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3710 ArgQuals);
3711 if (!FieldCtor || FieldCtor->isDeleted())
3712 return true;
3713 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3714 PDiag()) != AR_accessible)
3715 return true;
3716 }
3717 }
3718
3719 return false;
3720 }
3721
ShouldDeleteCopyAssignmentOperator(CXXMethodDecl * MD)3722 bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3723 CXXRecordDecl *RD = MD->getParent();
3724 assert(!RD->isDependentType() && "do deletion after instantiation");
3725 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3726 return false;
3727
3728 SourceLocation Loc = MD->getLocation();
3729
3730 // Do access control from the constructor
3731 ContextRAII MethodContext(*this, MD);
3732
3733 bool Union = RD->isUnion();
3734
3735 unsigned ArgQuals =
3736 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3737 Qualifiers::Const : 0;
3738
3739 // We do this because we should never actually use an anonymous
3740 // union's constructor.
3741 if (Union && RD->isAnonymousStructOrUnion())
3742 return false;
3743
3744 // FIXME: We should put some diagnostic logic right into this function.
3745
3746 // C++0x [class.copy]/11
3747 // A defaulted [copy] assignment operator for class X is defined as deleted
3748 // if X has:
3749
3750 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3751 BE = RD->bases_end();
3752 BI != BE; ++BI) {
3753 // We'll handle this one later
3754 if (BI->isVirtual())
3755 continue;
3756
3757 QualType BaseType = BI->getType();
3758 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3759 assert(BaseDecl && "base isn't a CXXRecordDecl");
3760
3761 // -- a [direct base class] B that cannot be [copied] because overload
3762 // resolution, as applied to B's [copy] assignment operator, results in
3763 // an ambiguity or a function that is deleted or inaccessible from the
3764 // assignment operator
3765 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3766 0);
3767 if (!CopyOper || CopyOper->isDeleted())
3768 return true;
3769 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3770 return true;
3771 }
3772
3773 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3774 BE = RD->vbases_end();
3775 BI != BE; ++BI) {
3776 QualType BaseType = BI->getType();
3777 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3778 assert(BaseDecl && "base isn't a CXXRecordDecl");
3779
3780 // -- a [virtual base class] B that cannot be [copied] because overload
3781 // resolution, as applied to B's [copy] assignment operator, results in
3782 // an ambiguity or a function that is deleted or inaccessible from the
3783 // assignment operator
3784 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3785 0);
3786 if (!CopyOper || CopyOper->isDeleted())
3787 return true;
3788 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3789 return true;
3790 }
3791
3792 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3793 FE = RD->field_end();
3794 FI != FE; ++FI) {
3795 QualType FieldType = Context.getBaseElementType(FI->getType());
3796
3797 // -- a non-static data member of reference type
3798 if (FieldType->isReferenceType())
3799 return true;
3800
3801 // -- a non-static data member of const non-class type (or array thereof)
3802 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3803 return true;
3804
3805 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3806
3807 if (FieldRecord) {
3808 // This is an anonymous union
3809 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3810 // Anonymous unions inside unions do not variant members create
3811 if (!Union) {
3812 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3813 UE = FieldRecord->field_end();
3814 UI != UE; ++UI) {
3815 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3816 CXXRecordDecl *UnionFieldRecord =
3817 UnionFieldType->getAsCXXRecordDecl();
3818
3819 // -- a variant member with a non-trivial [copy] assignment operator
3820 // and X is a union-like class
3821 if (UnionFieldRecord &&
3822 !UnionFieldRecord->hasTrivialCopyAssignment())
3823 return true;
3824 }
3825 }
3826
3827 // Don't try to initalize an anonymous union
3828 continue;
3829 // -- a variant member with a non-trivial [copy] assignment operator
3830 // and X is a union-like class
3831 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3832 return true;
3833 }
3834
3835 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3836 false, 0);
3837 if (!CopyOper || CopyOper->isDeleted())
3838 return false;
3839 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3840 return false;
3841 }
3842 }
3843
3844 return false;
3845 }
3846
ShouldDeleteDestructor(CXXDestructorDecl * DD)3847 bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3848 CXXRecordDecl *RD = DD->getParent();
3849 assert(!RD->isDependentType() && "do deletion after instantiation");
3850 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3851 return false;
3852
3853 SourceLocation Loc = DD->getLocation();
3854
3855 // Do access control from the destructor
3856 ContextRAII CtorContext(*this, DD);
3857
3858 bool Union = RD->isUnion();
3859
3860 // We do this because we should never actually use an anonymous
3861 // union's destructor.
3862 if (Union && RD->isAnonymousStructOrUnion())
3863 return false;
3864
3865 // C++0x [class.dtor]p5
3866 // A defaulted destructor for a class X is defined as deleted if:
3867 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3868 BE = RD->bases_end();
3869 BI != BE; ++BI) {
3870 // We'll handle this one later
3871 if (BI->isVirtual())
3872 continue;
3873
3874 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3875 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3876 assert(BaseDtor && "base has no destructor");
3877
3878 // -- any direct or virtual base class has a deleted destructor or
3879 // a destructor that is inaccessible from the defaulted destructor
3880 if (BaseDtor->isDeleted())
3881 return true;
3882 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3883 AR_accessible)
3884 return true;
3885 }
3886
3887 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3888 BE = RD->vbases_end();
3889 BI != BE; ++BI) {
3890 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3891 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3892 assert(BaseDtor && "base has no destructor");
3893
3894 // -- any direct or virtual base class has a deleted destructor or
3895 // a destructor that is inaccessible from the defaulted destructor
3896 if (BaseDtor->isDeleted())
3897 return true;
3898 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3899 AR_accessible)
3900 return true;
3901 }
3902
3903 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3904 FE = RD->field_end();
3905 FI != FE; ++FI) {
3906 QualType FieldType = Context.getBaseElementType(FI->getType());
3907 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3908 if (FieldRecord) {
3909 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3910 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3911 UE = FieldRecord->field_end();
3912 UI != UE; ++UI) {
3913 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3914 CXXRecordDecl *UnionFieldRecord =
3915 UnionFieldType->getAsCXXRecordDecl();
3916
3917 // -- X is a union-like class that has a variant member with a non-
3918 // trivial destructor.
3919 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3920 return true;
3921 }
3922 // Technically we are supposed to do this next check unconditionally.
3923 // But that makes absolutely no sense.
3924 } else {
3925 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3926
3927 // -- any of the non-static data members has class type M (or array
3928 // thereof) and M has a deleted destructor or a destructor that is
3929 // inaccessible from the defaulted destructor
3930 if (FieldDtor->isDeleted())
3931 return true;
3932 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3933 AR_accessible)
3934 return true;
3935
3936 // -- X is a union-like class that has a variant member with a non-
3937 // trivial destructor.
3938 if (Union && !FieldDtor->isTrivial())
3939 return true;
3940 }
3941 }
3942 }
3943
3944 if (DD->isVirtual()) {
3945 FunctionDecl *OperatorDelete = 0;
3946 DeclarationName Name =
3947 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3948 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
3949 false))
3950 return true;
3951 }
3952
3953
3954 return false;
3955 }
3956
3957 /// \brief Data used with FindHiddenVirtualMethod
3958 namespace {
3959 struct FindHiddenVirtualMethodData {
3960 Sema *S;
3961 CXXMethodDecl *Method;
3962 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3963 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3964 };
3965 }
3966
3967 /// \brief Member lookup function that determines whether a given C++
3968 /// method overloads virtual methods in a base class without overriding any,
3969 /// to be used with CXXRecordDecl::lookupInBases().
FindHiddenVirtualMethod(const CXXBaseSpecifier * Specifier,CXXBasePath & Path,void * UserData)3970 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3971 CXXBasePath &Path,
3972 void *UserData) {
3973 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3974
3975 FindHiddenVirtualMethodData &Data
3976 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3977
3978 DeclarationName Name = Data.Method->getDeclName();
3979 assert(Name.getNameKind() == DeclarationName::Identifier);
3980
3981 bool foundSameNameMethod = false;
3982 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3983 for (Path.Decls = BaseRecord->lookup(Name);
3984 Path.Decls.first != Path.Decls.second;
3985 ++Path.Decls.first) {
3986 NamedDecl *D = *Path.Decls.first;
3987 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3988 MD = MD->getCanonicalDecl();
3989 foundSameNameMethod = true;
3990 // Interested only in hidden virtual methods.
3991 if (!MD->isVirtual())
3992 continue;
3993 // If the method we are checking overrides a method from its base
3994 // don't warn about the other overloaded methods.
3995 if (!Data.S->IsOverload(Data.Method, MD, false))
3996 return true;
3997 // Collect the overload only if its hidden.
3998 if (!Data.OverridenAndUsingBaseMethods.count(MD))
3999 overloadedMethods.push_back(MD);
4000 }
4001 }
4002
4003 if (foundSameNameMethod)
4004 Data.OverloadedMethods.append(overloadedMethods.begin(),
4005 overloadedMethods.end());
4006 return foundSameNameMethod;
4007 }
4008
4009 /// \brief See if a method overloads virtual methods in a base class without
4010 /// overriding any.
DiagnoseHiddenVirtualMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)4011 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4012 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4013 MD->getLocation()) == Diagnostic::Ignored)
4014 return;
4015 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4016 return;
4017
4018 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4019 /*bool RecordPaths=*/false,
4020 /*bool DetectVirtual=*/false);
4021 FindHiddenVirtualMethodData Data;
4022 Data.Method = MD;
4023 Data.S = this;
4024
4025 // Keep the base methods that were overriden or introduced in the subclass
4026 // by 'using' in a set. A base method not in this set is hidden.
4027 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4028 res.first != res.second; ++res.first) {
4029 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4030 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4031 E = MD->end_overridden_methods();
4032 I != E; ++I)
4033 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4034 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4035 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4036 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4037 }
4038
4039 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4040 !Data.OverloadedMethods.empty()) {
4041 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4042 << MD << (Data.OverloadedMethods.size() > 1);
4043
4044 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4045 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4046 Diag(overloadedMD->getLocation(),
4047 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4048 }
4049 }
4050 }
4051
ActOnFinishCXXMemberSpecification(Scope * S,SourceLocation RLoc,Decl * TagDecl,SourceLocation LBrac,SourceLocation RBrac,AttributeList * AttrList)4052 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4053 Decl *TagDecl,
4054 SourceLocation LBrac,
4055 SourceLocation RBrac,
4056 AttributeList *AttrList) {
4057 if (!TagDecl)
4058 return;
4059
4060 AdjustDeclIfTemplate(TagDecl);
4061
4062 ActOnFields(S, RLoc, TagDecl,
4063 // strict aliasing violation!
4064 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4065 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4066
4067 CheckCompletedCXXClass(
4068 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4069 }
4070
4071 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4072 /// special functions, such as the default constructor, copy
4073 /// constructor, or destructor, to the given C++ class (C++
4074 /// [special]p1). This routine can only be executed just before the
4075 /// definition of the class is complete.
AddImplicitlyDeclaredMembersToClass(CXXRecordDecl * ClassDecl)4076 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4077 if (!ClassDecl->hasUserDeclaredConstructor())
4078 ++ASTContext::NumImplicitDefaultConstructors;
4079
4080 if (!ClassDecl->hasUserDeclaredCopyConstructor())
4081 ++ASTContext::NumImplicitCopyConstructors;
4082
4083 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4084 ++ASTContext::NumImplicitCopyAssignmentOperators;
4085
4086 // If we have a dynamic class, then the copy assignment operator may be
4087 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4088 // it shows up in the right place in the vtable and that we diagnose
4089 // problems with the implicit exception specification.
4090 if (ClassDecl->isDynamicClass())
4091 DeclareImplicitCopyAssignment(ClassDecl);
4092 }
4093
4094 if (!ClassDecl->hasUserDeclaredDestructor()) {
4095 ++ASTContext::NumImplicitDestructors;
4096
4097 // If we have a dynamic class, then the destructor may be virtual, so we
4098 // have to declare the destructor immediately. This ensures that, e.g., it
4099 // shows up in the right place in the vtable and that we diagnose problems
4100 // with the implicit exception specification.
4101 if (ClassDecl->isDynamicClass())
4102 DeclareImplicitDestructor(ClassDecl);
4103 }
4104 }
4105
ActOnReenterDeclaratorTemplateScope(Scope * S,DeclaratorDecl * D)4106 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4107 if (!D)
4108 return;
4109
4110 int NumParamList = D->getNumTemplateParameterLists();
4111 for (int i = 0; i < NumParamList; i++) {
4112 TemplateParameterList* Params = D->getTemplateParameterList(i);
4113 for (TemplateParameterList::iterator Param = Params->begin(),
4114 ParamEnd = Params->end();
4115 Param != ParamEnd; ++Param) {
4116 NamedDecl *Named = cast<NamedDecl>(*Param);
4117 if (Named->getDeclName()) {
4118 S->AddDecl(Named);
4119 IdResolver.AddDecl(Named);
4120 }
4121 }
4122 }
4123 }
4124
ActOnReenterTemplateScope(Scope * S,Decl * D)4125 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4126 if (!D)
4127 return;
4128
4129 TemplateParameterList *Params = 0;
4130 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4131 Params = Template->getTemplateParameters();
4132 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4133 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4134 Params = PartialSpec->getTemplateParameters();
4135 else
4136 return;
4137
4138 for (TemplateParameterList::iterator Param = Params->begin(),
4139 ParamEnd = Params->end();
4140 Param != ParamEnd; ++Param) {
4141 NamedDecl *Named = cast<NamedDecl>(*Param);
4142 if (Named->getDeclName()) {
4143 S->AddDecl(Named);
4144 IdResolver.AddDecl(Named);
4145 }
4146 }
4147 }
4148
ActOnStartDelayedMemberDeclarations(Scope * S,Decl * RecordD)4149 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4150 if (!RecordD) return;
4151 AdjustDeclIfTemplate(RecordD);
4152 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4153 PushDeclContext(S, Record);
4154 }
4155
ActOnFinishDelayedMemberDeclarations(Scope * S,Decl * RecordD)4156 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4157 if (!RecordD) return;
4158 PopDeclContext();
4159 }
4160
4161 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
4162 /// parsing a top-level (non-nested) C++ class, and we are now
4163 /// parsing those parts of the given Method declaration that could
4164 /// not be parsed earlier (C++ [class.mem]p2), such as default
4165 /// arguments. This action should enter the scope of the given
4166 /// Method declaration as if we had just parsed the qualified method
4167 /// name. However, it should not bring the parameters into scope;
4168 /// that will be performed by ActOnDelayedCXXMethodParameter.
ActOnStartDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)4169 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4170 }
4171
4172 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
4173 /// C++ method declaration. We're (re-)introducing the given
4174 /// function parameter into scope for use in parsing later parts of
4175 /// the method declaration. For example, we could see an
4176 /// ActOnParamDefaultArgument event for this parameter.
ActOnDelayedCXXMethodParameter(Scope * S,Decl * ParamD)4177 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4178 if (!ParamD)
4179 return;
4180
4181 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4182
4183 // If this parameter has an unparsed default argument, clear it out
4184 // to make way for the parsed default argument.
4185 if (Param->hasUnparsedDefaultArg())
4186 Param->setDefaultArg(0);
4187
4188 S->AddDecl(Param);
4189 if (Param->getDeclName())
4190 IdResolver.AddDecl(Param);
4191 }
4192
4193 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4194 /// processing the delayed method declaration for Method. The method
4195 /// declaration is now considered finished. There may be a separate
4196 /// ActOnStartOfFunctionDef action later (not necessarily
4197 /// immediately!) for this method, if it was also defined inside the
4198 /// class body.
ActOnFinishDelayedCXXMethodDeclaration(Scope * S,Decl * MethodD)4199 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4200 if (!MethodD)
4201 return;
4202
4203 AdjustDeclIfTemplate(MethodD);
4204
4205 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4206
4207 // Now that we have our default arguments, check the constructor
4208 // again. It could produce additional diagnostics or affect whether
4209 // the class has implicitly-declared destructors, among other
4210 // things.
4211 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4212 CheckConstructor(Constructor);
4213
4214 // Check the default arguments, which we may have added.
4215 if (!Method->isInvalidDecl())
4216 CheckCXXDefaultArguments(Method);
4217 }
4218
4219 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4220 /// the well-formedness of the constructor declarator @p D with type @p
4221 /// R. If there are any errors in the declarator, this routine will
4222 /// emit diagnostics and set the invalid bit to true. In any case, the type
4223 /// will be updated to reflect a well-formed type for the constructor and
4224 /// returned.
CheckConstructorDeclarator(Declarator & D,QualType R,StorageClass & SC)4225 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4226 StorageClass &SC) {
4227 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4228
4229 // C++ [class.ctor]p3:
4230 // A constructor shall not be virtual (10.3) or static (9.4). A
4231 // constructor can be invoked for a const, volatile or const
4232 // volatile object. A constructor shall not be declared const,
4233 // volatile, or const volatile (9.3.2).
4234 if (isVirtual) {
4235 if (!D.isInvalidType())
4236 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4237 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4238 << SourceRange(D.getIdentifierLoc());
4239 D.setInvalidType();
4240 }
4241 if (SC == SC_Static) {
4242 if (!D.isInvalidType())
4243 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4244 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4245 << SourceRange(D.getIdentifierLoc());
4246 D.setInvalidType();
4247 SC = SC_None;
4248 }
4249
4250 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4251 if (FTI.TypeQuals != 0) {
4252 if (FTI.TypeQuals & Qualifiers::Const)
4253 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4254 << "const" << SourceRange(D.getIdentifierLoc());
4255 if (FTI.TypeQuals & Qualifiers::Volatile)
4256 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4257 << "volatile" << SourceRange(D.getIdentifierLoc());
4258 if (FTI.TypeQuals & Qualifiers::Restrict)
4259 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4260 << "restrict" << SourceRange(D.getIdentifierLoc());
4261 D.setInvalidType();
4262 }
4263
4264 // C++0x [class.ctor]p4:
4265 // A constructor shall not be declared with a ref-qualifier.
4266 if (FTI.hasRefQualifier()) {
4267 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4268 << FTI.RefQualifierIsLValueRef
4269 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4270 D.setInvalidType();
4271 }
4272
4273 // Rebuild the function type "R" without any type qualifiers (in
4274 // case any of the errors above fired) and with "void" as the
4275 // return type, since constructors don't have return types.
4276 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4277 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4278 return R;
4279
4280 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4281 EPI.TypeQuals = 0;
4282 EPI.RefQualifier = RQ_None;
4283
4284 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4285 Proto->getNumArgs(), EPI);
4286 }
4287
4288 /// CheckConstructor - Checks a fully-formed constructor for
4289 /// well-formedness, issuing any diagnostics required. Returns true if
4290 /// the constructor declarator is invalid.
CheckConstructor(CXXConstructorDecl * Constructor)4291 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4292 CXXRecordDecl *ClassDecl
4293 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4294 if (!ClassDecl)
4295 return Constructor->setInvalidDecl();
4296
4297 // C++ [class.copy]p3:
4298 // A declaration of a constructor for a class X is ill-formed if
4299 // its first parameter is of type (optionally cv-qualified) X and
4300 // either there are no other parameters or else all other
4301 // parameters have default arguments.
4302 if (!Constructor->isInvalidDecl() &&
4303 ((Constructor->getNumParams() == 1) ||
4304 (Constructor->getNumParams() > 1 &&
4305 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4306 Constructor->getTemplateSpecializationKind()
4307 != TSK_ImplicitInstantiation) {
4308 QualType ParamType = Constructor->getParamDecl(0)->getType();
4309 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4310 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4311 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4312 const char *ConstRef
4313 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4314 : " const &";
4315 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4316 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4317
4318 // FIXME: Rather that making the constructor invalid, we should endeavor
4319 // to fix the type.
4320 Constructor->setInvalidDecl();
4321 }
4322 }
4323 }
4324
4325 /// CheckDestructor - Checks a fully-formed destructor definition for
4326 /// well-formedness, issuing any diagnostics required. Returns true
4327 /// on error.
CheckDestructor(CXXDestructorDecl * Destructor)4328 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4329 CXXRecordDecl *RD = Destructor->getParent();
4330
4331 if (Destructor->isVirtual()) {
4332 SourceLocation Loc;
4333
4334 if (!Destructor->isImplicit())
4335 Loc = Destructor->getLocation();
4336 else
4337 Loc = RD->getLocation();
4338
4339 // If we have a virtual destructor, look up the deallocation function
4340 FunctionDecl *OperatorDelete = 0;
4341 DeclarationName Name =
4342 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4343 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4344 return true;
4345
4346 MarkDeclarationReferenced(Loc, OperatorDelete);
4347
4348 Destructor->setOperatorDelete(OperatorDelete);
4349 }
4350
4351 return false;
4352 }
4353
4354 static inline bool
FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo & FTI)4355 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4356 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4357 FTI.ArgInfo[0].Param &&
4358 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4359 }
4360
4361 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4362 /// the well-formednes of the destructor declarator @p D with type @p
4363 /// R. If there are any errors in the declarator, this routine will
4364 /// emit diagnostics and set the declarator to invalid. Even if this happens,
4365 /// will be updated to reflect a well-formed type for the destructor and
4366 /// returned.
CheckDestructorDeclarator(Declarator & D,QualType R,StorageClass & SC)4367 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4368 StorageClass& SC) {
4369 // C++ [class.dtor]p1:
4370 // [...] A typedef-name that names a class is a class-name
4371 // (7.1.3); however, a typedef-name that names a class shall not
4372 // be used as the identifier in the declarator for a destructor
4373 // declaration.
4374 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4375 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4376 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4377 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4378 else if (const TemplateSpecializationType *TST =
4379 DeclaratorType->getAs<TemplateSpecializationType>())
4380 if (TST->isTypeAlias())
4381 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4382 << DeclaratorType << 1;
4383
4384 // C++ [class.dtor]p2:
4385 // A destructor is used to destroy objects of its class type. A
4386 // destructor takes no parameters, and no return type can be
4387 // specified for it (not even void). The address of a destructor
4388 // shall not be taken. A destructor shall not be static. A
4389 // destructor can be invoked for a const, volatile or const
4390 // volatile object. A destructor shall not be declared const,
4391 // volatile or const volatile (9.3.2).
4392 if (SC == SC_Static) {
4393 if (!D.isInvalidType())
4394 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4395 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4396 << SourceRange(D.getIdentifierLoc())
4397 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4398
4399 SC = SC_None;
4400 }
4401 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4402 // Destructors don't have return types, but the parser will
4403 // happily parse something like:
4404 //
4405 // class X {
4406 // float ~X();
4407 // };
4408 //
4409 // The return type will be eliminated later.
4410 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4411 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4412 << SourceRange(D.getIdentifierLoc());
4413 }
4414
4415 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4416 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4417 if (FTI.TypeQuals & Qualifiers::Const)
4418 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4419 << "const" << SourceRange(D.getIdentifierLoc());
4420 if (FTI.TypeQuals & Qualifiers::Volatile)
4421 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4422 << "volatile" << SourceRange(D.getIdentifierLoc());
4423 if (FTI.TypeQuals & Qualifiers::Restrict)
4424 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4425 << "restrict" << SourceRange(D.getIdentifierLoc());
4426 D.setInvalidType();
4427 }
4428
4429 // C++0x [class.dtor]p2:
4430 // A destructor shall not be declared with a ref-qualifier.
4431 if (FTI.hasRefQualifier()) {
4432 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4433 << FTI.RefQualifierIsLValueRef
4434 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4435 D.setInvalidType();
4436 }
4437
4438 // Make sure we don't have any parameters.
4439 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
4440 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4441
4442 // Delete the parameters.
4443 FTI.freeArgs();
4444 D.setInvalidType();
4445 }
4446
4447 // Make sure the destructor isn't variadic.
4448 if (FTI.isVariadic) {
4449 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
4450 D.setInvalidType();
4451 }
4452
4453 // Rebuild the function type "R" without any type qualifiers or
4454 // parameters (in case any of the errors above fired) and with
4455 // "void" as the return type, since destructors don't have return
4456 // types.
4457 if (!D.isInvalidType())
4458 return R;
4459
4460 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4461 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4462 EPI.Variadic = false;
4463 EPI.TypeQuals = 0;
4464 EPI.RefQualifier = RQ_None;
4465 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
4466 }
4467
4468 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4469 /// well-formednes of the conversion function declarator @p D with
4470 /// type @p R. If there are any errors in the declarator, this routine
4471 /// will emit diagnostics and return true. Otherwise, it will return
4472 /// false. Either way, the type @p R will be updated to reflect a
4473 /// well-formed type for the conversion operator.
CheckConversionDeclarator(Declarator & D,QualType & R,StorageClass & SC)4474 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
4475 StorageClass& SC) {
4476 // C++ [class.conv.fct]p1:
4477 // Neither parameter types nor return type can be specified. The
4478 // type of a conversion function (8.3.5) is "function taking no
4479 // parameter returning conversion-type-id."
4480 if (SC == SC_Static) {
4481 if (!D.isInvalidType())
4482 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4483 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4484 << SourceRange(D.getIdentifierLoc());
4485 D.setInvalidType();
4486 SC = SC_None;
4487 }
4488
4489 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4490
4491 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4492 // Conversion functions don't have return types, but the parser will
4493 // happily parse something like:
4494 //
4495 // class X {
4496 // float operator bool();
4497 // };
4498 //
4499 // The return type will be changed later anyway.
4500 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4501 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4502 << SourceRange(D.getIdentifierLoc());
4503 D.setInvalidType();
4504 }
4505
4506 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4507
4508 // Make sure we don't have any parameters.
4509 if (Proto->getNumArgs() > 0) {
4510 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4511
4512 // Delete the parameters.
4513 D.getFunctionTypeInfo().freeArgs();
4514 D.setInvalidType();
4515 } else if (Proto->isVariadic()) {
4516 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
4517 D.setInvalidType();
4518 }
4519
4520 // Diagnose "&operator bool()" and other such nonsense. This
4521 // is actually a gcc extension which we don't support.
4522 if (Proto->getResultType() != ConvType) {
4523 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4524 << Proto->getResultType();
4525 D.setInvalidType();
4526 ConvType = Proto->getResultType();
4527 }
4528
4529 // C++ [class.conv.fct]p4:
4530 // The conversion-type-id shall not represent a function type nor
4531 // an array type.
4532 if (ConvType->isArrayType()) {
4533 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4534 ConvType = Context.getPointerType(ConvType);
4535 D.setInvalidType();
4536 } else if (ConvType->isFunctionType()) {
4537 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4538 ConvType = Context.getPointerType(ConvType);
4539 D.setInvalidType();
4540 }
4541
4542 // Rebuild the function type "R" without any parameters (in case any
4543 // of the errors above fired) and with the conversion type as the
4544 // return type.
4545 if (D.isInvalidType())
4546 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
4547
4548 // C++0x explicit conversion operators.
4549 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
4550 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4551 diag::warn_explicit_conversion_functions)
4552 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
4553 }
4554
4555 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4556 /// the declaration of the given C++ conversion function. This routine
4557 /// is responsible for recording the conversion function in the C++
4558 /// class, if possible.
ActOnConversionDeclarator(CXXConversionDecl * Conversion)4559 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
4560 assert(Conversion && "Expected to receive a conversion function declaration");
4561
4562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
4563
4564 // Make sure we aren't redeclaring the conversion function.
4565 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
4566
4567 // C++ [class.conv.fct]p1:
4568 // [...] A conversion function is never used to convert a
4569 // (possibly cv-qualified) object to the (possibly cv-qualified)
4570 // same object type (or a reference to it), to a (possibly
4571 // cv-qualified) base class of that type (or a reference to it),
4572 // or to (possibly cv-qualified) void.
4573 // FIXME: Suppress this warning if the conversion function ends up being a
4574 // virtual function that overrides a virtual function in a base class.
4575 QualType ClassType
4576 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4577 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
4578 ConvType = ConvTypeRef->getPointeeType();
4579 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4580 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4581 /* Suppress diagnostics for instantiations. */;
4582 else if (ConvType->isRecordType()) {
4583 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4584 if (ConvType == ClassType)
4585 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
4586 << ClassType;
4587 else if (IsDerivedFrom(ClassType, ConvType))
4588 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
4589 << ClassType << ConvType;
4590 } else if (ConvType->isVoidType()) {
4591 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
4592 << ClassType << ConvType;
4593 }
4594
4595 if (FunctionTemplateDecl *ConversionTemplate
4596 = Conversion->getDescribedFunctionTemplate())
4597 return ConversionTemplate;
4598
4599 return Conversion;
4600 }
4601
4602 //===----------------------------------------------------------------------===//
4603 // Namespace Handling
4604 //===----------------------------------------------------------------------===//
4605
4606
4607
4608 /// ActOnStartNamespaceDef - This is called at the start of a namespace
4609 /// definition.
ActOnStartNamespaceDef(Scope * NamespcScope,SourceLocation InlineLoc,SourceLocation NamespaceLoc,SourceLocation IdentLoc,IdentifierInfo * II,SourceLocation LBrace,AttributeList * AttrList)4610 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
4611 SourceLocation InlineLoc,
4612 SourceLocation NamespaceLoc,
4613 SourceLocation IdentLoc,
4614 IdentifierInfo *II,
4615 SourceLocation LBrace,
4616 AttributeList *AttrList) {
4617 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4618 // For anonymous namespace, take the location of the left brace.
4619 SourceLocation Loc = II ? IdentLoc : LBrace;
4620 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
4621 StartLoc, Loc, II);
4622 Namespc->setInline(InlineLoc.isValid());
4623
4624 Scope *DeclRegionScope = NamespcScope->getParent();
4625
4626 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4627
4628 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4629 PushNamespaceVisibilityAttr(Attr);
4630
4631 if (II) {
4632 // C++ [namespace.def]p2:
4633 // The identifier in an original-namespace-definition shall not
4634 // have been previously defined in the declarative region in
4635 // which the original-namespace-definition appears. The
4636 // identifier in an original-namespace-definition is the name of
4637 // the namespace. Subsequently in that declarative region, it is
4638 // treated as an original-namespace-name.
4639 //
4640 // Since namespace names are unique in their scope, and we don't
4641 // look through using directives, just look for any ordinary names.
4642
4643 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4644 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4645 Decl::IDNS_Namespace;
4646 NamedDecl *PrevDecl = 0;
4647 for (DeclContext::lookup_result R
4648 = CurContext->getRedeclContext()->lookup(II);
4649 R.first != R.second; ++R.first) {
4650 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4651 PrevDecl = *R.first;
4652 break;
4653 }
4654 }
4655
4656 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4657 // This is an extended namespace definition.
4658 if (Namespc->isInline() != OrigNS->isInline()) {
4659 // inline-ness must match
4660 if (OrigNS->isInline()) {
4661 // The user probably just forgot the 'inline', so suggest that it
4662 // be added back.
4663 Diag(Namespc->getLocation(),
4664 diag::warn_inline_namespace_reopened_noninline)
4665 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4666 } else {
4667 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4668 << Namespc->isInline();
4669 }
4670 Diag(OrigNS->getLocation(), diag::note_previous_definition);
4671
4672 // Recover by ignoring the new namespace's inline status.
4673 Namespc->setInline(OrigNS->isInline());
4674 }
4675
4676 // Attach this namespace decl to the chain of extended namespace
4677 // definitions.
4678 OrigNS->setNextNamespace(Namespc);
4679 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
4680
4681 // Remove the previous declaration from the scope.
4682 if (DeclRegionScope->isDeclScope(OrigNS)) {
4683 IdResolver.RemoveDecl(OrigNS);
4684 DeclRegionScope->RemoveDecl(OrigNS);
4685 }
4686 } else if (PrevDecl) {
4687 // This is an invalid name redefinition.
4688 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4689 << Namespc->getDeclName();
4690 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4691 Namespc->setInvalidDecl();
4692 // Continue on to push Namespc as current DeclContext and return it.
4693 } else if (II->isStr("std") &&
4694 CurContext->getRedeclContext()->isTranslationUnit()) {
4695 // This is the first "real" definition of the namespace "std", so update
4696 // our cache of the "std" namespace to point at this definition.
4697 if (NamespaceDecl *StdNS = getStdNamespace()) {
4698 // We had already defined a dummy namespace "std". Link this new
4699 // namespace definition to the dummy namespace "std".
4700 StdNS->setNextNamespace(Namespc);
4701 StdNS->setLocation(IdentLoc);
4702 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
4703 }
4704
4705 // Make our StdNamespace cache point at the first real definition of the
4706 // "std" namespace.
4707 StdNamespace = Namespc;
4708
4709 // Add this instance of "std" to the set of known namespaces
4710 KnownNamespaces[Namespc] = false;
4711 } else if (!Namespc->isInline()) {
4712 // Since this is an "original" namespace, add it to the known set of
4713 // namespaces if it is not an inline namespace.
4714 KnownNamespaces[Namespc] = false;
4715 }
4716
4717 PushOnScopeChains(Namespc, DeclRegionScope);
4718 } else {
4719 // Anonymous namespaces.
4720 assert(Namespc->isAnonymousNamespace());
4721
4722 // Link the anonymous namespace into its parent.
4723 NamespaceDecl *PrevDecl;
4724 DeclContext *Parent = CurContext->getRedeclContext();
4725 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4726 PrevDecl = TU->getAnonymousNamespace();
4727 TU->setAnonymousNamespace(Namespc);
4728 } else {
4729 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4730 PrevDecl = ND->getAnonymousNamespace();
4731 ND->setAnonymousNamespace(Namespc);
4732 }
4733
4734 // Link the anonymous namespace with its previous declaration.
4735 if (PrevDecl) {
4736 assert(PrevDecl->isAnonymousNamespace());
4737 assert(!PrevDecl->getNextNamespace());
4738 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4739 PrevDecl->setNextNamespace(Namespc);
4740
4741 if (Namespc->isInline() != PrevDecl->isInline()) {
4742 // inline-ness must match
4743 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4744 << Namespc->isInline();
4745 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4746 Namespc->setInvalidDecl();
4747 // Recover by ignoring the new namespace's inline status.
4748 Namespc->setInline(PrevDecl->isInline());
4749 }
4750 }
4751
4752 CurContext->addDecl(Namespc);
4753
4754 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4755 // behaves as if it were replaced by
4756 // namespace unique { /* empty body */ }
4757 // using namespace unique;
4758 // namespace unique { namespace-body }
4759 // where all occurrences of 'unique' in a translation unit are
4760 // replaced by the same identifier and this identifier differs
4761 // from all other identifiers in the entire program.
4762
4763 // We just create the namespace with an empty name and then add an
4764 // implicit using declaration, just like the standard suggests.
4765 //
4766 // CodeGen enforces the "universally unique" aspect by giving all
4767 // declarations semantically contained within an anonymous
4768 // namespace internal linkage.
4769
4770 if (!PrevDecl) {
4771 UsingDirectiveDecl* UD
4772 = UsingDirectiveDecl::Create(Context, CurContext,
4773 /* 'using' */ LBrace,
4774 /* 'namespace' */ SourceLocation(),
4775 /* qualifier */ NestedNameSpecifierLoc(),
4776 /* identifier */ SourceLocation(),
4777 Namespc,
4778 /* Ancestor */ CurContext);
4779 UD->setImplicit();
4780 CurContext->addDecl(UD);
4781 }
4782 }
4783
4784 // Although we could have an invalid decl (i.e. the namespace name is a
4785 // redefinition), push it as current DeclContext and try to continue parsing.
4786 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4787 // for the namespace has the declarations that showed up in that particular
4788 // namespace definition.
4789 PushDeclContext(NamespcScope, Namespc);
4790 return Namespc;
4791 }
4792
4793 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4794 /// is a namespace alias, returns the namespace it points to.
getNamespaceDecl(NamedDecl * D)4795 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4796 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4797 return AD->getNamespace();
4798 return dyn_cast_or_null<NamespaceDecl>(D);
4799 }
4800
4801 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
4802 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
ActOnFinishNamespaceDef(Decl * Dcl,SourceLocation RBrace)4803 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
4804 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4805 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
4806 Namespc->setRBraceLoc(RBrace);
4807 PopDeclContext();
4808 if (Namespc->hasAttr<VisibilityAttr>())
4809 PopPragmaVisibility();
4810 }
4811
getStdBadAlloc() const4812 CXXRecordDecl *Sema::getStdBadAlloc() const {
4813 return cast_or_null<CXXRecordDecl>(
4814 StdBadAlloc.get(Context.getExternalSource()));
4815 }
4816
getStdNamespace() const4817 NamespaceDecl *Sema::getStdNamespace() const {
4818 return cast_or_null<NamespaceDecl>(
4819 StdNamespace.get(Context.getExternalSource()));
4820 }
4821
4822 /// \brief Retrieve the special "std" namespace, which may require us to
4823 /// implicitly define the namespace.
getOrCreateStdNamespace()4824 NamespaceDecl *Sema::getOrCreateStdNamespace() {
4825 if (!StdNamespace) {
4826 // The "std" namespace has not yet been defined, so build one implicitly.
4827 StdNamespace = NamespaceDecl::Create(Context,
4828 Context.getTranslationUnitDecl(),
4829 SourceLocation(), SourceLocation(),
4830 &PP.getIdentifierTable().get("std"));
4831 getStdNamespace()->setImplicit(true);
4832 }
4833
4834 return getStdNamespace();
4835 }
4836
4837 /// \brief Determine whether a using statement is in a context where it will be
4838 /// apply in all contexts.
IsUsingDirectiveInToplevelContext(DeclContext * CurContext)4839 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4840 switch (CurContext->getDeclKind()) {
4841 case Decl::TranslationUnit:
4842 return true;
4843 case Decl::LinkageSpec:
4844 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4845 default:
4846 return false;
4847 }
4848 }
4849
TryNamespaceTypoCorrection(Sema & S,LookupResult & R,Scope * Sc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)4850 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
4851 CXXScopeSpec &SS,
4852 SourceLocation IdentLoc,
4853 IdentifierInfo *Ident) {
4854 R.clear();
4855 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
4856 R.getLookupKind(), Sc, &SS, NULL,
4857 false, S.CTC_NoKeywords, NULL)) {
4858 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
4859 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
4860 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
4861 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
4862 if (DeclContext *DC = S.computeDeclContext(SS, false))
4863 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
4864 << Ident << DC << CorrectedQuotedStr << SS.getRange()
4865 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4866 else
4867 S.Diag(IdentLoc, diag::err_using_directive_suggest)
4868 << Ident << CorrectedQuotedStr
4869 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4870
4871 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
4872 diag::note_namespace_defined_here) << CorrectedQuotedStr;
4873
4874 Ident = Corrected.getCorrectionAsIdentifierInfo();
4875 R.addDecl(Corrected.getCorrectionDecl());
4876 return true;
4877 }
4878 R.setLookupName(Ident);
4879 }
4880 return false;
4881 }
4882
ActOnUsingDirective(Scope * S,SourceLocation UsingLoc,SourceLocation NamespcLoc,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * NamespcName,AttributeList * AttrList)4883 Decl *Sema::ActOnUsingDirective(Scope *S,
4884 SourceLocation UsingLoc,
4885 SourceLocation NamespcLoc,
4886 CXXScopeSpec &SS,
4887 SourceLocation IdentLoc,
4888 IdentifierInfo *NamespcName,
4889 AttributeList *AttrList) {
4890 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4891 assert(NamespcName && "Invalid NamespcName.");
4892 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
4893
4894 // This can only happen along a recovery path.
4895 while (S->getFlags() & Scope::TemplateParamScope)
4896 S = S->getParent();
4897 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4898
4899 UsingDirectiveDecl *UDir = 0;
4900 NestedNameSpecifier *Qualifier = 0;
4901 if (SS.isSet())
4902 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4903
4904 // Lookup namespace name.
4905 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4906 LookupParsedName(R, S, &SS);
4907 if (R.isAmbiguous())
4908 return 0;
4909
4910 if (R.empty()) {
4911 R.clear();
4912 // Allow "using namespace std;" or "using namespace ::std;" even if
4913 // "std" hasn't been defined yet, for GCC compatibility.
4914 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4915 NamespcName->isStr("std")) {
4916 Diag(IdentLoc, diag::ext_using_undefined_std);
4917 R.addDecl(getOrCreateStdNamespace());
4918 R.resolveKind();
4919 }
4920 // Otherwise, attempt typo correction.
4921 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
4922 }
4923
4924 if (!R.empty()) {
4925 NamedDecl *Named = R.getFoundDecl();
4926 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4927 && "expected namespace decl");
4928 // C++ [namespace.udir]p1:
4929 // A using-directive specifies that the names in the nominated
4930 // namespace can be used in the scope in which the
4931 // using-directive appears after the using-directive. During
4932 // unqualified name lookup (3.4.1), the names appear as if they
4933 // were declared in the nearest enclosing namespace which
4934 // contains both the using-directive and the nominated
4935 // namespace. [Note: in this context, "contains" means "contains
4936 // directly or indirectly". ]
4937
4938 // Find enclosing context containing both using-directive and
4939 // nominated namespace.
4940 NamespaceDecl *NS = getNamespaceDecl(Named);
4941 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4942 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4943 CommonAncestor = CommonAncestor->getParent();
4944
4945 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
4946 SS.getWithLocInContext(Context),
4947 IdentLoc, Named, CommonAncestor);
4948
4949 if (IsUsingDirectiveInToplevelContext(CurContext) &&
4950 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
4951 Diag(IdentLoc, diag::warn_using_directive_in_header);
4952 }
4953
4954 PushUsingDirective(S, UDir);
4955 } else {
4956 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
4957 }
4958
4959 // FIXME: We ignore attributes for now.
4960 return UDir;
4961 }
4962
PushUsingDirective(Scope * S,UsingDirectiveDecl * UDir)4963 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4964 // If scope has associated entity, then using directive is at namespace
4965 // or translation unit scope. We add UsingDirectiveDecls, into
4966 // it's lookup structure.
4967 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
4968 Ctx->addDecl(UDir);
4969 else
4970 // Otherwise it is block-sope. using-directives will affect lookup
4971 // only to the end of scope.
4972 S->PushUsingDirective(UDir);
4973 }
4974
4975
ActOnUsingDeclaration(Scope * S,AccessSpecifier AS,bool HasUsingKeyword,SourceLocation UsingLoc,CXXScopeSpec & SS,UnqualifiedId & Name,AttributeList * AttrList,bool IsTypeName,SourceLocation TypenameLoc)4976 Decl *Sema::ActOnUsingDeclaration(Scope *S,
4977 AccessSpecifier AS,
4978 bool HasUsingKeyword,
4979 SourceLocation UsingLoc,
4980 CXXScopeSpec &SS,
4981 UnqualifiedId &Name,
4982 AttributeList *AttrList,
4983 bool IsTypeName,
4984 SourceLocation TypenameLoc) {
4985 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4986
4987 switch (Name.getKind()) {
4988 case UnqualifiedId::IK_ImplicitSelfParam:
4989 case UnqualifiedId::IK_Identifier:
4990 case UnqualifiedId::IK_OperatorFunctionId:
4991 case UnqualifiedId::IK_LiteralOperatorId:
4992 case UnqualifiedId::IK_ConversionFunctionId:
4993 break;
4994
4995 case UnqualifiedId::IK_ConstructorName:
4996 case UnqualifiedId::IK_ConstructorTemplateId:
4997 // C++0x inherited constructors.
4998 if (getLangOptions().CPlusPlus0x) break;
4999
5000 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5001 << SS.getRange();
5002 return 0;
5003
5004 case UnqualifiedId::IK_DestructorName:
5005 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5006 << SS.getRange();
5007 return 0;
5008
5009 case UnqualifiedId::IK_TemplateId:
5010 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5011 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5012 return 0;
5013 }
5014
5015 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5016 DeclarationName TargetName = TargetNameInfo.getName();
5017 if (!TargetName)
5018 return 0;
5019
5020 // Warn about using declarations.
5021 // TODO: store that the declaration was written without 'using' and
5022 // talk about access decls instead of using decls in the
5023 // diagnostics.
5024 if (!HasUsingKeyword) {
5025 UsingLoc = Name.getSourceRange().getBegin();
5026
5027 Diag(UsingLoc, diag::warn_access_decl_deprecated)
5028 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5029 }
5030
5031 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5032 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5033 return 0;
5034
5035 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5036 TargetNameInfo, AttrList,
5037 /* IsInstantiation */ false,
5038 IsTypeName, TypenameLoc);
5039 if (UD)
5040 PushOnScopeChains(UD, S, /*AddToContext*/ false);
5041
5042 return UD;
5043 }
5044
5045 /// \brief Determine whether a using declaration considers the given
5046 /// declarations as "equivalent", e.g., if they are redeclarations of
5047 /// the same entity or are both typedefs of the same type.
5048 static bool
IsEquivalentForUsingDecl(ASTContext & Context,NamedDecl * D1,NamedDecl * D2,bool & SuppressRedeclaration)5049 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5050 bool &SuppressRedeclaration) {
5051 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5052 SuppressRedeclaration = false;
5053 return true;
5054 }
5055
5056 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5057 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5058 SuppressRedeclaration = true;
5059 return Context.hasSameType(TD1->getUnderlyingType(),
5060 TD2->getUnderlyingType());
5061 }
5062
5063 return false;
5064 }
5065
5066
5067 /// Determines whether to create a using shadow decl for a particular
5068 /// decl, given the set of decls existing prior to this using lookup.
CheckUsingShadowDecl(UsingDecl * Using,NamedDecl * Orig,const LookupResult & Previous)5069 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5070 const LookupResult &Previous) {
5071 // Diagnose finding a decl which is not from a base class of the
5072 // current class. We do this now because there are cases where this
5073 // function will silently decide not to build a shadow decl, which
5074 // will pre-empt further diagnostics.
5075 //
5076 // We don't need to do this in C++0x because we do the check once on
5077 // the qualifier.
5078 //
5079 // FIXME: diagnose the following if we care enough:
5080 // struct A { int foo; };
5081 // struct B : A { using A::foo; };
5082 // template <class T> struct C : A {};
5083 // template <class T> struct D : C<T> { using B::foo; } // <---
5084 // This is invalid (during instantiation) in C++03 because B::foo
5085 // resolves to the using decl in B, which is not a base class of D<T>.
5086 // We can't diagnose it immediately because C<T> is an unknown
5087 // specialization. The UsingShadowDecl in D<T> then points directly
5088 // to A::foo, which will look well-formed when we instantiate.
5089 // The right solution is to not collapse the shadow-decl chain.
5090 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5091 DeclContext *OrigDC = Orig->getDeclContext();
5092
5093 // Handle enums and anonymous structs.
5094 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5095 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5096 while (OrigRec->isAnonymousStructOrUnion())
5097 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5098
5099 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5100 if (OrigDC == CurContext) {
5101 Diag(Using->getLocation(),
5102 diag::err_using_decl_nested_name_specifier_is_current_class)
5103 << Using->getQualifierLoc().getSourceRange();
5104 Diag(Orig->getLocation(), diag::note_using_decl_target);
5105 return true;
5106 }
5107
5108 Diag(Using->getQualifierLoc().getBeginLoc(),
5109 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5110 << Using->getQualifier()
5111 << cast<CXXRecordDecl>(CurContext)
5112 << Using->getQualifierLoc().getSourceRange();
5113 Diag(Orig->getLocation(), diag::note_using_decl_target);
5114 return true;
5115 }
5116 }
5117
5118 if (Previous.empty()) return false;
5119
5120 NamedDecl *Target = Orig;
5121 if (isa<UsingShadowDecl>(Target))
5122 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5123
5124 // If the target happens to be one of the previous declarations, we
5125 // don't have a conflict.
5126 //
5127 // FIXME: but we might be increasing its access, in which case we
5128 // should redeclare it.
5129 NamedDecl *NonTag = 0, *Tag = 0;
5130 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5131 I != E; ++I) {
5132 NamedDecl *D = (*I)->getUnderlyingDecl();
5133 bool Result;
5134 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5135 return Result;
5136
5137 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5138 }
5139
5140 if (Target->isFunctionOrFunctionTemplate()) {
5141 FunctionDecl *FD;
5142 if (isa<FunctionTemplateDecl>(Target))
5143 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5144 else
5145 FD = cast<FunctionDecl>(Target);
5146
5147 NamedDecl *OldDecl = 0;
5148 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5149 case Ovl_Overload:
5150 return false;
5151
5152 case Ovl_NonFunction:
5153 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5154 break;
5155
5156 // We found a decl with the exact signature.
5157 case Ovl_Match:
5158 // If we're in a record, we want to hide the target, so we
5159 // return true (without a diagnostic) to tell the caller not to
5160 // build a shadow decl.
5161 if (CurContext->isRecord())
5162 return true;
5163
5164 // If we're not in a record, this is an error.
5165 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5166 break;
5167 }
5168
5169 Diag(Target->getLocation(), diag::note_using_decl_target);
5170 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5171 return true;
5172 }
5173
5174 // Target is not a function.
5175
5176 if (isa<TagDecl>(Target)) {
5177 // No conflict between a tag and a non-tag.
5178 if (!Tag) return false;
5179
5180 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5181 Diag(Target->getLocation(), diag::note_using_decl_target);
5182 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5183 return true;
5184 }
5185
5186 // No conflict between a tag and a non-tag.
5187 if (!NonTag) return false;
5188
5189 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5190 Diag(Target->getLocation(), diag::note_using_decl_target);
5191 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5192 return true;
5193 }
5194
5195 /// Builds a shadow declaration corresponding to a 'using' declaration.
BuildUsingShadowDecl(Scope * S,UsingDecl * UD,NamedDecl * Orig)5196 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5197 UsingDecl *UD,
5198 NamedDecl *Orig) {
5199
5200 // If we resolved to another shadow declaration, just coalesce them.
5201 NamedDecl *Target = Orig;
5202 if (isa<UsingShadowDecl>(Target)) {
5203 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5204 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5205 }
5206
5207 UsingShadowDecl *Shadow
5208 = UsingShadowDecl::Create(Context, CurContext,
5209 UD->getLocation(), UD, Target);
5210 UD->addShadowDecl(Shadow);
5211
5212 Shadow->setAccess(UD->getAccess());
5213 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5214 Shadow->setInvalidDecl();
5215
5216 if (S)
5217 PushOnScopeChains(Shadow, S);
5218 else
5219 CurContext->addDecl(Shadow);
5220
5221
5222 return Shadow;
5223 }
5224
5225 /// Hides a using shadow declaration. This is required by the current
5226 /// using-decl implementation when a resolvable using declaration in a
5227 /// class is followed by a declaration which would hide or override
5228 /// one or more of the using decl's targets; for example:
5229 ///
5230 /// struct Base { void foo(int); };
5231 /// struct Derived : Base {
5232 /// using Base::foo;
5233 /// void foo(int);
5234 /// };
5235 ///
5236 /// The governing language is C++03 [namespace.udecl]p12:
5237 ///
5238 /// When a using-declaration brings names from a base class into a
5239 /// derived class scope, member functions in the derived class
5240 /// override and/or hide member functions with the same name and
5241 /// parameter types in a base class (rather than conflicting).
5242 ///
5243 /// There are two ways to implement this:
5244 /// (1) optimistically create shadow decls when they're not hidden
5245 /// by existing declarations, or
5246 /// (2) don't create any shadow decls (or at least don't make them
5247 /// visible) until we've fully parsed/instantiated the class.
5248 /// The problem with (1) is that we might have to retroactively remove
5249 /// a shadow decl, which requires several O(n) operations because the
5250 /// decl structures are (very reasonably) not designed for removal.
5251 /// (2) avoids this but is very fiddly and phase-dependent.
HideUsingShadowDecl(Scope * S,UsingShadowDecl * Shadow)5252 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5253 if (Shadow->getDeclName().getNameKind() ==
5254 DeclarationName::CXXConversionFunctionName)
5255 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5256
5257 // Remove it from the DeclContext...
5258 Shadow->getDeclContext()->removeDecl(Shadow);
5259
5260 // ...and the scope, if applicable...
5261 if (S) {
5262 S->RemoveDecl(Shadow);
5263 IdResolver.RemoveDecl(Shadow);
5264 }
5265
5266 // ...and the using decl.
5267 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5268
5269 // TODO: complain somehow if Shadow was used. It shouldn't
5270 // be possible for this to happen, because...?
5271 }
5272
5273 /// Builds a using declaration.
5274 ///
5275 /// \param IsInstantiation - Whether this call arises from an
5276 /// instantiation of an unresolved using declaration. We treat
5277 /// the lookup differently for these declarations.
BuildUsingDeclaration(Scope * S,AccessSpecifier AS,SourceLocation UsingLoc,CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,AttributeList * AttrList,bool IsInstantiation,bool IsTypeName,SourceLocation TypenameLoc)5278 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5279 SourceLocation UsingLoc,
5280 CXXScopeSpec &SS,
5281 const DeclarationNameInfo &NameInfo,
5282 AttributeList *AttrList,
5283 bool IsInstantiation,
5284 bool IsTypeName,
5285 SourceLocation TypenameLoc) {
5286 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5287 SourceLocation IdentLoc = NameInfo.getLoc();
5288 assert(IdentLoc.isValid() && "Invalid TargetName location.");
5289
5290 // FIXME: We ignore attributes for now.
5291
5292 if (SS.isEmpty()) {
5293 Diag(IdentLoc, diag::err_using_requires_qualname);
5294 return 0;
5295 }
5296
5297 // Do the redeclaration lookup in the current scope.
5298 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5299 ForRedeclaration);
5300 Previous.setHideTags(false);
5301 if (S) {
5302 LookupName(Previous, S);
5303
5304 // It is really dumb that we have to do this.
5305 LookupResult::Filter F = Previous.makeFilter();
5306 while (F.hasNext()) {
5307 NamedDecl *D = F.next();
5308 if (!isDeclInScope(D, CurContext, S))
5309 F.erase();
5310 }
5311 F.done();
5312 } else {
5313 assert(IsInstantiation && "no scope in non-instantiation");
5314 assert(CurContext->isRecord() && "scope not record in instantiation");
5315 LookupQualifiedName(Previous, CurContext);
5316 }
5317
5318 // Check for invalid redeclarations.
5319 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5320 return 0;
5321
5322 // Check for bad qualifiers.
5323 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5324 return 0;
5325
5326 DeclContext *LookupContext = computeDeclContext(SS);
5327 NamedDecl *D;
5328 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5329 if (!LookupContext) {
5330 if (IsTypeName) {
5331 // FIXME: not all declaration name kinds are legal here
5332 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5333 UsingLoc, TypenameLoc,
5334 QualifierLoc,
5335 IdentLoc, NameInfo.getName());
5336 } else {
5337 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5338 QualifierLoc, NameInfo);
5339 }
5340 } else {
5341 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5342 NameInfo, IsTypeName);
5343 }
5344 D->setAccess(AS);
5345 CurContext->addDecl(D);
5346
5347 if (!LookupContext) return D;
5348 UsingDecl *UD = cast<UsingDecl>(D);
5349
5350 if (RequireCompleteDeclContext(SS, LookupContext)) {
5351 UD->setInvalidDecl();
5352 return UD;
5353 }
5354
5355 // Constructor inheriting using decls get special treatment.
5356 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5357 if (CheckInheritedConstructorUsingDecl(UD))
5358 UD->setInvalidDecl();
5359 return UD;
5360 }
5361
5362 // Otherwise, look up the target name.
5363
5364 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5365 R.setUsingDeclaration(true);
5366
5367 // Unlike most lookups, we don't always want to hide tag
5368 // declarations: tag names are visible through the using declaration
5369 // even if hidden by ordinary names, *except* in a dependent context
5370 // where it's important for the sanity of two-phase lookup.
5371 if (!IsInstantiation)
5372 R.setHideTags(false);
5373
5374 LookupQualifiedName(R, LookupContext);
5375
5376 if (R.empty()) {
5377 Diag(IdentLoc, diag::err_no_member)
5378 << NameInfo.getName() << LookupContext << SS.getRange();
5379 UD->setInvalidDecl();
5380 return UD;
5381 }
5382
5383 if (R.isAmbiguous()) {
5384 UD->setInvalidDecl();
5385 return UD;
5386 }
5387
5388 if (IsTypeName) {
5389 // If we asked for a typename and got a non-type decl, error out.
5390 if (!R.getAsSingle<TypeDecl>()) {
5391 Diag(IdentLoc, diag::err_using_typename_non_type);
5392 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5393 Diag((*I)->getUnderlyingDecl()->getLocation(),
5394 diag::note_using_decl_target);
5395 UD->setInvalidDecl();
5396 return UD;
5397 }
5398 } else {
5399 // If we asked for a non-typename and we got a type, error out,
5400 // but only if this is an instantiation of an unresolved using
5401 // decl. Otherwise just silently find the type name.
5402 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5403 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5404 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5405 UD->setInvalidDecl();
5406 return UD;
5407 }
5408 }
5409
5410 // C++0x N2914 [namespace.udecl]p6:
5411 // A using-declaration shall not name a namespace.
5412 if (R.getAsSingle<NamespaceDecl>()) {
5413 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5414 << SS.getRange();
5415 UD->setInvalidDecl();
5416 return UD;
5417 }
5418
5419 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5420 if (!CheckUsingShadowDecl(UD, *I, Previous))
5421 BuildUsingShadowDecl(S, UD, *I);
5422 }
5423
5424 return UD;
5425 }
5426
5427 /// Additional checks for a using declaration referring to a constructor name.
CheckInheritedConstructorUsingDecl(UsingDecl * UD)5428 bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5429 if (UD->isTypeName()) {
5430 // FIXME: Cannot specify typename when specifying constructor
5431 return true;
5432 }
5433
5434 const Type *SourceType = UD->getQualifier()->getAsType();
5435 assert(SourceType &&
5436 "Using decl naming constructor doesn't have type in scope spec.");
5437 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5438
5439 // Check whether the named type is a direct base class.
5440 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5441 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5442 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5443 BaseIt != BaseE; ++BaseIt) {
5444 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5445 if (CanonicalSourceType == BaseType)
5446 break;
5447 }
5448
5449 if (BaseIt == BaseE) {
5450 // Did not find SourceType in the bases.
5451 Diag(UD->getUsingLocation(),
5452 diag::err_using_decl_constructor_not_in_direct_base)
5453 << UD->getNameInfo().getSourceRange()
5454 << QualType(SourceType, 0) << TargetClass;
5455 return true;
5456 }
5457
5458 BaseIt->setInheritConstructors();
5459
5460 return false;
5461 }
5462
5463 /// Checks that the given using declaration is not an invalid
5464 /// redeclaration. Note that this is checking only for the using decl
5465 /// itself, not for any ill-formedness among the UsingShadowDecls.
CheckUsingDeclRedeclaration(SourceLocation UsingLoc,bool isTypeName,const CXXScopeSpec & SS,SourceLocation NameLoc,const LookupResult & Prev)5466 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5467 bool isTypeName,
5468 const CXXScopeSpec &SS,
5469 SourceLocation NameLoc,
5470 const LookupResult &Prev) {
5471 // C++03 [namespace.udecl]p8:
5472 // C++0x [namespace.udecl]p10:
5473 // A using-declaration is a declaration and can therefore be used
5474 // repeatedly where (and only where) multiple declarations are
5475 // allowed.
5476 //
5477 // That's in non-member contexts.
5478 if (!CurContext->getRedeclContext()->isRecord())
5479 return false;
5480
5481 NestedNameSpecifier *Qual
5482 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5483
5484 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5485 NamedDecl *D = *I;
5486
5487 bool DTypename;
5488 NestedNameSpecifier *DQual;
5489 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5490 DTypename = UD->isTypeName();
5491 DQual = UD->getQualifier();
5492 } else if (UnresolvedUsingValueDecl *UD
5493 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5494 DTypename = false;
5495 DQual = UD->getQualifier();
5496 } else if (UnresolvedUsingTypenameDecl *UD
5497 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5498 DTypename = true;
5499 DQual = UD->getQualifier();
5500 } else continue;
5501
5502 // using decls differ if one says 'typename' and the other doesn't.
5503 // FIXME: non-dependent using decls?
5504 if (isTypeName != DTypename) continue;
5505
5506 // using decls differ if they name different scopes (but note that
5507 // template instantiation can cause this check to trigger when it
5508 // didn't before instantiation).
5509 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5510 Context.getCanonicalNestedNameSpecifier(DQual))
5511 continue;
5512
5513 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
5514 Diag(D->getLocation(), diag::note_using_decl) << 1;
5515 return true;
5516 }
5517
5518 return false;
5519 }
5520
5521
5522 /// Checks that the given nested-name qualifier used in a using decl
5523 /// in the current context is appropriately related to the current
5524 /// scope. If an error is found, diagnoses it and returns true.
CheckUsingDeclQualifier(SourceLocation UsingLoc,const CXXScopeSpec & SS,SourceLocation NameLoc)5525 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5526 const CXXScopeSpec &SS,
5527 SourceLocation NameLoc) {
5528 DeclContext *NamedContext = computeDeclContext(SS);
5529
5530 if (!CurContext->isRecord()) {
5531 // C++03 [namespace.udecl]p3:
5532 // C++0x [namespace.udecl]p8:
5533 // A using-declaration for a class member shall be a member-declaration.
5534
5535 // If we weren't able to compute a valid scope, it must be a
5536 // dependent class scope.
5537 if (!NamedContext || NamedContext->isRecord()) {
5538 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5539 << SS.getRange();
5540 return true;
5541 }
5542
5543 // Otherwise, everything is known to be fine.
5544 return false;
5545 }
5546
5547 // The current scope is a record.
5548
5549 // If the named context is dependent, we can't decide much.
5550 if (!NamedContext) {
5551 // FIXME: in C++0x, we can diagnose if we can prove that the
5552 // nested-name-specifier does not refer to a base class, which is
5553 // still possible in some cases.
5554
5555 // Otherwise we have to conservatively report that things might be
5556 // okay.
5557 return false;
5558 }
5559
5560 if (!NamedContext->isRecord()) {
5561 // Ideally this would point at the last name in the specifier,
5562 // but we don't have that level of source info.
5563 Diag(SS.getRange().getBegin(),
5564 diag::err_using_decl_nested_name_specifier_is_not_class)
5565 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5566 return true;
5567 }
5568
5569 if (!NamedContext->isDependentContext() &&
5570 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5571 return true;
5572
5573 if (getLangOptions().CPlusPlus0x) {
5574 // C++0x [namespace.udecl]p3:
5575 // In a using-declaration used as a member-declaration, the
5576 // nested-name-specifier shall name a base class of the class
5577 // being defined.
5578
5579 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5580 cast<CXXRecordDecl>(NamedContext))) {
5581 if (CurContext == NamedContext) {
5582 Diag(NameLoc,
5583 diag::err_using_decl_nested_name_specifier_is_current_class)
5584 << SS.getRange();
5585 return true;
5586 }
5587
5588 Diag(SS.getRange().getBegin(),
5589 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5590 << (NestedNameSpecifier*) SS.getScopeRep()
5591 << cast<CXXRecordDecl>(CurContext)
5592 << SS.getRange();
5593 return true;
5594 }
5595
5596 return false;
5597 }
5598
5599 // C++03 [namespace.udecl]p4:
5600 // A using-declaration used as a member-declaration shall refer
5601 // to a member of a base class of the class being defined [etc.].
5602
5603 // Salient point: SS doesn't have to name a base class as long as
5604 // lookup only finds members from base classes. Therefore we can
5605 // diagnose here only if we can prove that that can't happen,
5606 // i.e. if the class hierarchies provably don't intersect.
5607
5608 // TODO: it would be nice if "definitely valid" results were cached
5609 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5610 // need to be repeated.
5611
5612 struct UserData {
5613 llvm::DenseSet<const CXXRecordDecl*> Bases;
5614
5615 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5616 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5617 Data->Bases.insert(Base);
5618 return true;
5619 }
5620
5621 bool hasDependentBases(const CXXRecordDecl *Class) {
5622 return !Class->forallBases(collect, this);
5623 }
5624
5625 /// Returns true if the base is dependent or is one of the
5626 /// accumulated base classes.
5627 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5628 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5629 return !Data->Bases.count(Base);
5630 }
5631
5632 bool mightShareBases(const CXXRecordDecl *Class) {
5633 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5634 }
5635 };
5636
5637 UserData Data;
5638
5639 // Returns false if we find a dependent base.
5640 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5641 return false;
5642
5643 // Returns false if the class has a dependent base or if it or one
5644 // of its bases is present in the base set of the current context.
5645 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5646 return false;
5647
5648 Diag(SS.getRange().getBegin(),
5649 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5650 << (NestedNameSpecifier*) SS.getScopeRep()
5651 << cast<CXXRecordDecl>(CurContext)
5652 << SS.getRange();
5653
5654 return true;
5655 }
5656
ActOnAliasDeclaration(Scope * S,AccessSpecifier AS,MultiTemplateParamsArg TemplateParamLists,SourceLocation UsingLoc,UnqualifiedId & Name,TypeResult Type)5657 Decl *Sema::ActOnAliasDeclaration(Scope *S,
5658 AccessSpecifier AS,
5659 MultiTemplateParamsArg TemplateParamLists,
5660 SourceLocation UsingLoc,
5661 UnqualifiedId &Name,
5662 TypeResult Type) {
5663 // Skip up to the relevant declaration scope.
5664 while (S->getFlags() & Scope::TemplateParamScope)
5665 S = S->getParent();
5666 assert((S->getFlags() & Scope::DeclScope) &&
5667 "got alias-declaration outside of declaration scope");
5668
5669 if (Type.isInvalid())
5670 return 0;
5671
5672 bool Invalid = false;
5673 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5674 TypeSourceInfo *TInfo = 0;
5675 GetTypeFromParser(Type.get(), &TInfo);
5676
5677 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5678 return 0;
5679
5680 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
5681 UPPC_DeclarationType)) {
5682 Invalid = true;
5683 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5684 TInfo->getTypeLoc().getBeginLoc());
5685 }
5686
5687 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5688 LookupName(Previous, S);
5689
5690 // Warn about shadowing the name of a template parameter.
5691 if (Previous.isSingleResult() &&
5692 Previous.getFoundDecl()->isTemplateParameter()) {
5693 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5694 Previous.getFoundDecl()))
5695 Invalid = true;
5696 Previous.clear();
5697 }
5698
5699 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5700 "name in alias declaration must be an identifier");
5701 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5702 Name.StartLocation,
5703 Name.Identifier, TInfo);
5704
5705 NewTD->setAccess(AS);
5706
5707 if (Invalid)
5708 NewTD->setInvalidDecl();
5709
5710 CheckTypedefForVariablyModifiedType(S, NewTD);
5711 Invalid |= NewTD->isInvalidDecl();
5712
5713 bool Redeclaration = false;
5714
5715 NamedDecl *NewND;
5716 if (TemplateParamLists.size()) {
5717 TypeAliasTemplateDecl *OldDecl = 0;
5718 TemplateParameterList *OldTemplateParams = 0;
5719
5720 if (TemplateParamLists.size() != 1) {
5721 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5722 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5723 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5724 }
5725 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5726
5727 // Only consider previous declarations in the same scope.
5728 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5729 /*ExplicitInstantiationOrSpecialization*/false);
5730 if (!Previous.empty()) {
5731 Redeclaration = true;
5732
5733 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5734 if (!OldDecl && !Invalid) {
5735 Diag(UsingLoc, diag::err_redefinition_different_kind)
5736 << Name.Identifier;
5737
5738 NamedDecl *OldD = Previous.getRepresentativeDecl();
5739 if (OldD->getLocation().isValid())
5740 Diag(OldD->getLocation(), diag::note_previous_definition);
5741
5742 Invalid = true;
5743 }
5744
5745 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5746 if (TemplateParameterListsAreEqual(TemplateParams,
5747 OldDecl->getTemplateParameters(),
5748 /*Complain=*/true,
5749 TPL_TemplateMatch))
5750 OldTemplateParams = OldDecl->getTemplateParameters();
5751 else
5752 Invalid = true;
5753
5754 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5755 if (!Invalid &&
5756 !Context.hasSameType(OldTD->getUnderlyingType(),
5757 NewTD->getUnderlyingType())) {
5758 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5759 // but we can't reasonably accept it.
5760 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5761 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5762 if (OldTD->getLocation().isValid())
5763 Diag(OldTD->getLocation(), diag::note_previous_definition);
5764 Invalid = true;
5765 }
5766 }
5767 }
5768
5769 // Merge any previous default template arguments into our parameters,
5770 // and check the parameter list.
5771 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5772 TPC_TypeAliasTemplate))
5773 return 0;
5774
5775 TypeAliasTemplateDecl *NewDecl =
5776 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5777 Name.Identifier, TemplateParams,
5778 NewTD);
5779
5780 NewDecl->setAccess(AS);
5781
5782 if (Invalid)
5783 NewDecl->setInvalidDecl();
5784 else if (OldDecl)
5785 NewDecl->setPreviousDeclaration(OldDecl);
5786
5787 NewND = NewDecl;
5788 } else {
5789 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5790 NewND = NewTD;
5791 }
5792
5793 if (!Redeclaration)
5794 PushOnScopeChains(NewND, S);
5795
5796 return NewND;
5797 }
5798
ActOnNamespaceAliasDef(Scope * S,SourceLocation NamespaceLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,CXXScopeSpec & SS,SourceLocation IdentLoc,IdentifierInfo * Ident)5799 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
5800 SourceLocation NamespaceLoc,
5801 SourceLocation AliasLoc,
5802 IdentifierInfo *Alias,
5803 CXXScopeSpec &SS,
5804 SourceLocation IdentLoc,
5805 IdentifierInfo *Ident) {
5806
5807 // Lookup the namespace name.
5808 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5809 LookupParsedName(R, S, &SS);
5810
5811 // Check if we have a previous declaration with the same name.
5812 NamedDecl *PrevDecl
5813 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5814 ForRedeclaration);
5815 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5816 PrevDecl = 0;
5817
5818 if (PrevDecl) {
5819 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
5820 // We already have an alias with the same name that points to the same
5821 // namespace, so don't create a new one.
5822 // FIXME: At some point, we'll want to create the (redundant)
5823 // declaration to maintain better source information.
5824 if (!R.isAmbiguous() && !R.empty() &&
5825 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
5826 return 0;
5827 }
5828
5829 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5830 diag::err_redefinition_different_kind;
5831 Diag(AliasLoc, DiagID) << Alias;
5832 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5833 return 0;
5834 }
5835
5836 if (R.isAmbiguous())
5837 return 0;
5838
5839 if (R.empty()) {
5840 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
5841 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
5842 return 0;
5843 }
5844 }
5845
5846 NamespaceAliasDecl *AliasDecl =
5847 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
5848 Alias, SS.getWithLocInContext(Context),
5849 IdentLoc, R.getFoundDecl());
5850
5851 PushOnScopeChains(AliasDecl, S);
5852 return AliasDecl;
5853 }
5854
5855 namespace {
5856 /// \brief Scoped object used to handle the state changes required in Sema
5857 /// to implicitly define the body of a C++ member function;
5858 class ImplicitlyDefinedFunctionScope {
5859 Sema &S;
5860 Sema::ContextRAII SavedContext;
5861
5862 public:
ImplicitlyDefinedFunctionScope(Sema & S,CXXMethodDecl * Method)5863 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
5864 : S(S), SavedContext(S, Method)
5865 {
5866 S.PushFunctionScope();
5867 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5868 }
5869
~ImplicitlyDefinedFunctionScope()5870 ~ImplicitlyDefinedFunctionScope() {
5871 S.PopExpressionEvaluationContext();
5872 S.PopFunctionOrBlockScope();
5873 }
5874 };
5875 }
5876
5877 Sema::ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl * ClassDecl)5878 Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
5879 // C++ [except.spec]p14:
5880 // An implicitly declared special member function (Clause 12) shall have an
5881 // exception-specification. [...]
5882 ImplicitExceptionSpecification ExceptSpec(Context);
5883 if (ClassDecl->isInvalidDecl())
5884 return ExceptSpec;
5885
5886 // Direct base-class constructors.
5887 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5888 BEnd = ClassDecl->bases_end();
5889 B != BEnd; ++B) {
5890 if (B->isVirtual()) // Handled below.
5891 continue;
5892
5893 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5894 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5895 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5896 // If this is a deleted function, add it anyway. This might be conformant
5897 // with the standard. This might not. I'm not sure. It might not matter.
5898 if (Constructor)
5899 ExceptSpec.CalledDecl(Constructor);
5900 }
5901 }
5902
5903 // Virtual base-class constructors.
5904 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5905 BEnd = ClassDecl->vbases_end();
5906 B != BEnd; ++B) {
5907 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5908 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5909 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5910 // If this is a deleted function, add it anyway. This might be conformant
5911 // with the standard. This might not. I'm not sure. It might not matter.
5912 if (Constructor)
5913 ExceptSpec.CalledDecl(Constructor);
5914 }
5915 }
5916
5917 // Field constructors.
5918 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5919 FEnd = ClassDecl->field_end();
5920 F != FEnd; ++F) {
5921 if (F->hasInClassInitializer()) {
5922 if (Expr *E = F->getInClassInitializer())
5923 ExceptSpec.CalledExpr(E);
5924 else if (!F->isInvalidDecl())
5925 ExceptSpec.SetDelayed();
5926 } else if (const RecordType *RecordTy
5927 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5928 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5929 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5930 // If this is a deleted function, add it anyway. This might be conformant
5931 // with the standard. This might not. I'm not sure. It might not matter.
5932 // In particular, the problem is that this function never gets called. It
5933 // might just be ill-formed because this function attempts to refer to
5934 // a deleted function here.
5935 if (Constructor)
5936 ExceptSpec.CalledDecl(Constructor);
5937 }
5938 }
5939
5940 return ExceptSpec;
5941 }
5942
DeclareImplicitDefaultConstructor(CXXRecordDecl * ClassDecl)5943 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5944 CXXRecordDecl *ClassDecl) {
5945 // C++ [class.ctor]p5:
5946 // A default constructor for a class X is a constructor of class X
5947 // that can be called without an argument. If there is no
5948 // user-declared constructor for class X, a default constructor is
5949 // implicitly declared. An implicitly-declared default constructor
5950 // is an inline public member of its class.
5951 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5952 "Should not build implicit default constructor!");
5953
5954 ImplicitExceptionSpecification Spec =
5955 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5956 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
5957
5958 // Create the actual constructor declaration.
5959 CanQualType ClassType
5960 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5961 SourceLocation ClassLoc = ClassDecl->getLocation();
5962 DeclarationName Name
5963 = Context.DeclarationNames.getCXXConstructorName(ClassType);
5964 DeclarationNameInfo NameInfo(Name, ClassLoc);
5965 CXXConstructorDecl *DefaultCon
5966 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
5967 Context.getFunctionType(Context.VoidTy,
5968 0, 0, EPI),
5969 /*TInfo=*/0,
5970 /*isExplicit=*/false,
5971 /*isInline=*/true,
5972 /*isImplicitlyDeclared=*/true);
5973 DefaultCon->setAccess(AS_public);
5974 DefaultCon->setDefaulted();
5975 DefaultCon->setImplicit();
5976 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
5977
5978 // Note that we have declared this constructor.
5979 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5980
5981 if (Scope *S = getScopeForContext(ClassDecl))
5982 PushOnScopeChains(DefaultCon, S, false);
5983 ClassDecl->addDecl(DefaultCon);
5984
5985 if (ShouldDeleteDefaultConstructor(DefaultCon))
5986 DefaultCon->setDeletedAsWritten();
5987
5988 return DefaultCon;
5989 }
5990
DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * Constructor)5991 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5992 CXXConstructorDecl *Constructor) {
5993 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5994 !Constructor->doesThisDeclarationHaveABody() &&
5995 !Constructor->isDeleted()) &&
5996 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
5997
5998 CXXRecordDecl *ClassDecl = Constructor->getParent();
5999 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6000
6001 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6002 DiagnosticErrorTrap Trap(Diags);
6003 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6004 Trap.hasErrorOccurred()) {
6005 Diag(CurrentLocation, diag::note_member_synthesized_at)
6006 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6007 Constructor->setInvalidDecl();
6008 return;
6009 }
6010
6011 SourceLocation Loc = Constructor->getLocation();
6012 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6013
6014 Constructor->setUsed();
6015 MarkVTableUsed(CurrentLocation, ClassDecl);
6016
6017 if (ASTMutationListener *L = getASTMutationListener()) {
6018 L->CompletedImplicitDefinition(Constructor);
6019 }
6020 }
6021
6022 /// Get any existing defaulted default constructor for the given class. Do not
6023 /// implicitly define one if it does not exist.
getDefaultedDefaultConstructorUnsafe(Sema & Self,CXXRecordDecl * D)6024 static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6025 CXXRecordDecl *D) {
6026 ASTContext &Context = Self.Context;
6027 QualType ClassType = Context.getTypeDeclType(D);
6028 DeclarationName ConstructorName
6029 = Context.DeclarationNames.getCXXConstructorName(
6030 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6031
6032 DeclContext::lookup_const_iterator Con, ConEnd;
6033 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6034 Con != ConEnd; ++Con) {
6035 // A function template cannot be defaulted.
6036 if (isa<FunctionTemplateDecl>(*Con))
6037 continue;
6038
6039 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6040 if (Constructor->isDefaultConstructor())
6041 return Constructor->isDefaulted() ? Constructor : 0;
6042 }
6043 return 0;
6044 }
6045
ActOnFinishDelayedMemberInitializers(Decl * D)6046 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6047 if (!D) return;
6048 AdjustDeclIfTemplate(D);
6049
6050 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6051 CXXConstructorDecl *CtorDecl
6052 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6053
6054 if (!CtorDecl) return;
6055
6056 // Compute the exception specification for the default constructor.
6057 const FunctionProtoType *CtorTy =
6058 CtorDecl->getType()->castAs<FunctionProtoType>();
6059 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6060 ImplicitExceptionSpecification Spec =
6061 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6062 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6063 assert(EPI.ExceptionSpecType != EST_Delayed);
6064
6065 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6066 }
6067
6068 // If the default constructor is explicitly defaulted, checking the exception
6069 // specification is deferred until now.
6070 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6071 !ClassDecl->isDependentType())
6072 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6073 }
6074
DeclareInheritedConstructors(CXXRecordDecl * ClassDecl)6075 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6076 // We start with an initial pass over the base classes to collect those that
6077 // inherit constructors from. If there are none, we can forgo all further
6078 // processing.
6079 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6080 BasesVector BasesToInheritFrom;
6081 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6082 BaseE = ClassDecl->bases_end();
6083 BaseIt != BaseE; ++BaseIt) {
6084 if (BaseIt->getInheritConstructors()) {
6085 QualType Base = BaseIt->getType();
6086 if (Base->isDependentType()) {
6087 // If we inherit constructors from anything that is dependent, just
6088 // abort processing altogether. We'll get another chance for the
6089 // instantiations.
6090 return;
6091 }
6092 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6093 }
6094 }
6095 if (BasesToInheritFrom.empty())
6096 return;
6097
6098 // Now collect the constructors that we already have in the current class.
6099 // Those take precedence over inherited constructors.
6100 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6101 // unless there is a user-declared constructor with the same signature in
6102 // the class where the using-declaration appears.
6103 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6104 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6105 CtorE = ClassDecl->ctor_end();
6106 CtorIt != CtorE; ++CtorIt) {
6107 ExistingConstructors.insert(
6108 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6109 }
6110
6111 Scope *S = getScopeForContext(ClassDecl);
6112 DeclarationName CreatedCtorName =
6113 Context.DeclarationNames.getCXXConstructorName(
6114 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6115
6116 // Now comes the true work.
6117 // First, we keep a map from constructor types to the base that introduced
6118 // them. Needed for finding conflicting constructors. We also keep the
6119 // actually inserted declarations in there, for pretty diagnostics.
6120 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6121 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6122 ConstructorToSourceMap InheritedConstructors;
6123 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6124 BaseE = BasesToInheritFrom.end();
6125 BaseIt != BaseE; ++BaseIt) {
6126 const RecordType *Base = *BaseIt;
6127 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6128 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6129 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6130 CtorE = BaseDecl->ctor_end();
6131 CtorIt != CtorE; ++CtorIt) {
6132 // Find the using declaration for inheriting this base's constructors.
6133 DeclarationName Name =
6134 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6135 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6136 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6137 SourceLocation UsingLoc = UD ? UD->getLocation() :
6138 ClassDecl->getLocation();
6139
6140 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6141 // from the class X named in the using-declaration consists of actual
6142 // constructors and notional constructors that result from the
6143 // transformation of defaulted parameters as follows:
6144 // - all non-template default constructors of X, and
6145 // - for each non-template constructor of X that has at least one
6146 // parameter with a default argument, the set of constructors that
6147 // results from omitting any ellipsis parameter specification and
6148 // successively omitting parameters with a default argument from the
6149 // end of the parameter-type-list.
6150 CXXConstructorDecl *BaseCtor = *CtorIt;
6151 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6152 const FunctionProtoType *BaseCtorType =
6153 BaseCtor->getType()->getAs<FunctionProtoType>();
6154
6155 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6156 maxParams = BaseCtor->getNumParams();
6157 params <= maxParams; ++params) {
6158 // Skip default constructors. They're never inherited.
6159 if (params == 0)
6160 continue;
6161 // Skip copy and move constructors for the same reason.
6162 if (CanBeCopyOrMove && params == 1)
6163 continue;
6164
6165 // Build up a function type for this particular constructor.
6166 // FIXME: The working paper does not consider that the exception spec
6167 // for the inheriting constructor might be larger than that of the
6168 // source. This code doesn't yet, either. When it does, this code will
6169 // need to be delayed until after exception specifications and in-class
6170 // member initializers are attached.
6171 const Type *NewCtorType;
6172 if (params == maxParams)
6173 NewCtorType = BaseCtorType;
6174 else {
6175 llvm::SmallVector<QualType, 16> Args;
6176 for (unsigned i = 0; i < params; ++i) {
6177 Args.push_back(BaseCtorType->getArgType(i));
6178 }
6179 FunctionProtoType::ExtProtoInfo ExtInfo =
6180 BaseCtorType->getExtProtoInfo();
6181 ExtInfo.Variadic = false;
6182 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6183 Args.data(), params, ExtInfo)
6184 .getTypePtr();
6185 }
6186 const Type *CanonicalNewCtorType =
6187 Context.getCanonicalType(NewCtorType);
6188
6189 // Now that we have the type, first check if the class already has a
6190 // constructor with this signature.
6191 if (ExistingConstructors.count(CanonicalNewCtorType))
6192 continue;
6193
6194 // Then we check if we have already declared an inherited constructor
6195 // with this signature.
6196 std::pair<ConstructorToSourceMap::iterator, bool> result =
6197 InheritedConstructors.insert(std::make_pair(
6198 CanonicalNewCtorType,
6199 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6200 if (!result.second) {
6201 // Already in the map. If it came from a different class, that's an
6202 // error. Not if it's from the same.
6203 CanQualType PreviousBase = result.first->second.first;
6204 if (CanonicalBase != PreviousBase) {
6205 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6206 const CXXConstructorDecl *PrevBaseCtor =
6207 PrevCtor->getInheritedConstructor();
6208 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6209
6210 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6211 Diag(BaseCtor->getLocation(),
6212 diag::note_using_decl_constructor_conflict_current_ctor);
6213 Diag(PrevBaseCtor->getLocation(),
6214 diag::note_using_decl_constructor_conflict_previous_ctor);
6215 Diag(PrevCtor->getLocation(),
6216 diag::note_using_decl_constructor_conflict_previous_using);
6217 }
6218 continue;
6219 }
6220
6221 // OK, we're there, now add the constructor.
6222 // C++0x [class.inhctor]p8: [...] that would be performed by a
6223 // user-writtern inline constructor [...]
6224 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6225 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6226 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6227 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6228 /*ImplicitlyDeclared=*/true);
6229 NewCtor->setAccess(BaseCtor->getAccess());
6230
6231 // Build up the parameter decls and add them.
6232 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6233 for (unsigned i = 0; i < params; ++i) {
6234 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6235 UsingLoc, UsingLoc,
6236 /*IdentifierInfo=*/0,
6237 BaseCtorType->getArgType(i),
6238 /*TInfo=*/0, SC_None,
6239 SC_None, /*DefaultArg=*/0));
6240 }
6241 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6242 NewCtor->setInheritedConstructor(BaseCtor);
6243
6244 PushOnScopeChains(NewCtor, S, false);
6245 ClassDecl->addDecl(NewCtor);
6246 result.first->second.second = NewCtor;
6247 }
6248 }
6249 }
6250 }
6251
6252 Sema::ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXRecordDecl * ClassDecl)6253 Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6254 // C++ [except.spec]p14:
6255 // An implicitly declared special member function (Clause 12) shall have
6256 // an exception-specification.
6257 ImplicitExceptionSpecification ExceptSpec(Context);
6258 if (ClassDecl->isInvalidDecl())
6259 return ExceptSpec;
6260
6261 // Direct base-class destructors.
6262 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6263 BEnd = ClassDecl->bases_end();
6264 B != BEnd; ++B) {
6265 if (B->isVirtual()) // Handled below.
6266 continue;
6267
6268 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6269 ExceptSpec.CalledDecl(
6270 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6271 }
6272
6273 // Virtual base-class destructors.
6274 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6275 BEnd = ClassDecl->vbases_end();
6276 B != BEnd; ++B) {
6277 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6278 ExceptSpec.CalledDecl(
6279 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6280 }
6281
6282 // Field destructors.
6283 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6284 FEnd = ClassDecl->field_end();
6285 F != FEnd; ++F) {
6286 if (const RecordType *RecordTy
6287 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6288 ExceptSpec.CalledDecl(
6289 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6290 }
6291
6292 return ExceptSpec;
6293 }
6294
DeclareImplicitDestructor(CXXRecordDecl * ClassDecl)6295 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6296 // C++ [class.dtor]p2:
6297 // If a class has no user-declared destructor, a destructor is
6298 // declared implicitly. An implicitly-declared destructor is an
6299 // inline public member of its class.
6300
6301 ImplicitExceptionSpecification Spec =
6302 ComputeDefaultedDtorExceptionSpec(ClassDecl);
6303 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6304
6305 // Create the actual destructor declaration.
6306 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6307
6308 CanQualType ClassType
6309 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6310 SourceLocation ClassLoc = ClassDecl->getLocation();
6311 DeclarationName Name
6312 = Context.DeclarationNames.getCXXDestructorName(ClassType);
6313 DeclarationNameInfo NameInfo(Name, ClassLoc);
6314 CXXDestructorDecl *Destructor
6315 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6316 /*isInline=*/true,
6317 /*isImplicitlyDeclared=*/true);
6318 Destructor->setAccess(AS_public);
6319 Destructor->setDefaulted();
6320 Destructor->setImplicit();
6321 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6322
6323 // Note that we have declared this destructor.
6324 ++ASTContext::NumImplicitDestructorsDeclared;
6325
6326 // Introduce this destructor into its scope.
6327 if (Scope *S = getScopeForContext(ClassDecl))
6328 PushOnScopeChains(Destructor, S, false);
6329 ClassDecl->addDecl(Destructor);
6330
6331 // This could be uniqued if it ever proves significant.
6332 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6333
6334 if (ShouldDeleteDestructor(Destructor))
6335 Destructor->setDeletedAsWritten();
6336
6337 AddOverriddenMethods(ClassDecl, Destructor);
6338
6339 return Destructor;
6340 }
6341
DefineImplicitDestructor(SourceLocation CurrentLocation,CXXDestructorDecl * Destructor)6342 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6343 CXXDestructorDecl *Destructor) {
6344 assert((Destructor->isDefaulted() &&
6345 !Destructor->doesThisDeclarationHaveABody()) &&
6346 "DefineImplicitDestructor - call it for implicit default dtor");
6347 CXXRecordDecl *ClassDecl = Destructor->getParent();
6348 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6349
6350 if (Destructor->isInvalidDecl())
6351 return;
6352
6353 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6354
6355 DiagnosticErrorTrap Trap(Diags);
6356 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6357 Destructor->getParent());
6358
6359 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6360 Diag(CurrentLocation, diag::note_member_synthesized_at)
6361 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6362
6363 Destructor->setInvalidDecl();
6364 return;
6365 }
6366
6367 SourceLocation Loc = Destructor->getLocation();
6368 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6369
6370 Destructor->setUsed();
6371 MarkVTableUsed(CurrentLocation, ClassDecl);
6372
6373 if (ASTMutationListener *L = getASTMutationListener()) {
6374 L->CompletedImplicitDefinition(Destructor);
6375 }
6376 }
6377
AdjustDestructorExceptionSpec(CXXRecordDecl * classDecl,CXXDestructorDecl * destructor)6378 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6379 CXXDestructorDecl *destructor) {
6380 // C++11 [class.dtor]p3:
6381 // A declaration of a destructor that does not have an exception-
6382 // specification is implicitly considered to have the same exception-
6383 // specification as an implicit declaration.
6384 const FunctionProtoType *dtorType = destructor->getType()->
6385 getAs<FunctionProtoType>();
6386 if (dtorType->hasExceptionSpec())
6387 return;
6388
6389 ImplicitExceptionSpecification exceptSpec =
6390 ComputeDefaultedDtorExceptionSpec(classDecl);
6391
6392 // Replace the destructor's type.
6393 FunctionProtoType::ExtProtoInfo epi;
6394 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6395 epi.NumExceptions = exceptSpec.size();
6396 epi.Exceptions = exceptSpec.data();
6397 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6398
6399 destructor->setType(ty);
6400
6401 // FIXME: If the destructor has a body that could throw, and the newly created
6402 // spec doesn't allow exceptions, we should emit a warning, because this
6403 // change in behavior can break conforming C++03 programs at runtime.
6404 // However, we don't have a body yet, so it needs to be done somewhere else.
6405 }
6406
6407 /// \brief Builds a statement that copies the given entity from \p From to
6408 /// \c To.
6409 ///
6410 /// This routine is used to copy the members of a class with an
6411 /// implicitly-declared copy assignment operator. When the entities being
6412 /// copied are arrays, this routine builds for loops to copy them.
6413 ///
6414 /// \param S The Sema object used for type-checking.
6415 ///
6416 /// \param Loc The location where the implicit copy is being generated.
6417 ///
6418 /// \param T The type of the expressions being copied. Both expressions must
6419 /// have this type.
6420 ///
6421 /// \param To The expression we are copying to.
6422 ///
6423 /// \param From The expression we are copying from.
6424 ///
6425 /// \param CopyingBaseSubobject Whether we're copying a base subobject.
6426 /// Otherwise, it's a non-static member subobject.
6427 ///
6428 /// \param Depth Internal parameter recording the depth of the recursion.
6429 ///
6430 /// \returns A statement or a loop that copies the expressions.
6431 static StmtResult
BuildSingleCopyAssign(Sema & S,SourceLocation Loc,QualType T,Expr * To,Expr * From,bool CopyingBaseSubobject,unsigned Depth=0)6432 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
6433 Expr *To, Expr *From,
6434 bool CopyingBaseSubobject, unsigned Depth = 0) {
6435 // C++0x [class.copy]p30:
6436 // Each subobject is assigned in the manner appropriate to its type:
6437 //
6438 // - if the subobject is of class type, the copy assignment operator
6439 // for the class is used (as if by explicit qualification; that is,
6440 // ignoring any possible virtual overriding functions in more derived
6441 // classes);
6442 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6443 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6444
6445 // Look for operator=.
6446 DeclarationName Name
6447 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6448 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6449 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6450
6451 // Filter out any result that isn't a copy-assignment operator.
6452 LookupResult::Filter F = OpLookup.makeFilter();
6453 while (F.hasNext()) {
6454 NamedDecl *D = F.next();
6455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6456 if (Method->isCopyAssignmentOperator())
6457 continue;
6458
6459 F.erase();
6460 }
6461 F.done();
6462
6463 // Suppress the protected check (C++ [class.protected]) for each of the
6464 // assignment operators we found. This strange dance is required when
6465 // we're assigning via a base classes's copy-assignment operator. To
6466 // ensure that we're getting the right base class subobject (without
6467 // ambiguities), we need to cast "this" to that subobject type; to
6468 // ensure that we don't go through the virtual call mechanism, we need
6469 // to qualify the operator= name with the base class (see below). However,
6470 // this means that if the base class has a protected copy assignment
6471 // operator, the protected member access check will fail. So, we
6472 // rewrite "protected" access to "public" access in this case, since we
6473 // know by construction that we're calling from a derived class.
6474 if (CopyingBaseSubobject) {
6475 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6476 L != LEnd; ++L) {
6477 if (L.getAccess() == AS_protected)
6478 L.setAccess(AS_public);
6479 }
6480 }
6481
6482 // Create the nested-name-specifier that will be used to qualify the
6483 // reference to operator=; this is required to suppress the virtual
6484 // call mechanism.
6485 CXXScopeSpec SS;
6486 SS.MakeTrivial(S.Context,
6487 NestedNameSpecifier::Create(S.Context, 0, false,
6488 T.getTypePtr()),
6489 Loc);
6490
6491 // Create the reference to operator=.
6492 ExprResult OpEqualRef
6493 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
6494 /*FirstQualifierInScope=*/0, OpLookup,
6495 /*TemplateArgs=*/0,
6496 /*SuppressQualifierCheck=*/true);
6497 if (OpEqualRef.isInvalid())
6498 return StmtError();
6499
6500 // Build the call to the assignment operator.
6501
6502 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
6503 OpEqualRef.takeAs<Expr>(),
6504 Loc, &From, 1, Loc);
6505 if (Call.isInvalid())
6506 return StmtError();
6507
6508 return S.Owned(Call.takeAs<Stmt>());
6509 }
6510
6511 // - if the subobject is of scalar type, the built-in assignment
6512 // operator is used.
6513 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6514 if (!ArrayTy) {
6515 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
6516 if (Assignment.isInvalid())
6517 return StmtError();
6518
6519 return S.Owned(Assignment.takeAs<Stmt>());
6520 }
6521
6522 // - if the subobject is an array, each element is assigned, in the
6523 // manner appropriate to the element type;
6524
6525 // Construct a loop over the array bounds, e.g.,
6526 //
6527 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6528 //
6529 // that will copy each of the array elements.
6530 QualType SizeType = S.Context.getSizeType();
6531
6532 // Create the iteration variable.
6533 IdentifierInfo *IterationVarName = 0;
6534 {
6535 llvm::SmallString<8> Str;
6536 llvm::raw_svector_ostream OS(Str);
6537 OS << "__i" << Depth;
6538 IterationVarName = &S.Context.Idents.get(OS.str());
6539 }
6540 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
6541 IterationVarName, SizeType,
6542 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
6543 SC_None, SC_None);
6544
6545 // Initialize the iteration variable to zero.
6546 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
6547 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
6548
6549 // Create a reference to the iteration variable; we'll use this several
6550 // times throughout.
6551 Expr *IterationVarRef
6552 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
6553 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6554
6555 // Create the DeclStmt that holds the iteration variable.
6556 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6557
6558 // Create the comparison against the array bound.
6559 llvm::APInt Upper
6560 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
6561 Expr *Comparison
6562 = new (S.Context) BinaryOperator(IterationVarRef,
6563 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6564 BO_NE, S.Context.BoolTy,
6565 VK_RValue, OK_Ordinary, Loc);
6566
6567 // Create the pre-increment of the iteration variable.
6568 Expr *Increment
6569 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6570 VK_LValue, OK_Ordinary, Loc);
6571
6572 // Subscript the "from" and "to" expressions with the iteration variable.
6573 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6574 IterationVarRef, Loc));
6575 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6576 IterationVarRef, Loc));
6577
6578 // Build the copy for an individual element of the array.
6579 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6580 To, From, CopyingBaseSubobject,
6581 Depth + 1);
6582 if (Copy.isInvalid())
6583 return StmtError();
6584
6585 // Construct the loop that copies all elements of this array.
6586 return S.ActOnForStmt(Loc, Loc, InitStmt,
6587 S.MakeFullExpr(Comparison),
6588 0, S.MakeFullExpr(Increment),
6589 Loc, Copy.take());
6590 }
6591
6592 std::pair<Sema::ImplicitExceptionSpecification, bool>
ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl * ClassDecl)6593 Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6594 CXXRecordDecl *ClassDecl) {
6595 if (ClassDecl->isInvalidDecl())
6596 return std::make_pair(ImplicitExceptionSpecification(Context), false);
6597
6598 // C++ [class.copy]p10:
6599 // If the class definition does not explicitly declare a copy
6600 // assignment operator, one is declared implicitly.
6601 // The implicitly-defined copy assignment operator for a class X
6602 // will have the form
6603 //
6604 // X& X::operator=(const X&)
6605 //
6606 // if
6607 bool HasConstCopyAssignment = true;
6608
6609 // -- each direct base class B of X has a copy assignment operator
6610 // whose parameter is of type const B&, const volatile B& or B,
6611 // and
6612 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6613 BaseEnd = ClassDecl->bases_end();
6614 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6615 // We'll handle this below
6616 if (LangOpts.CPlusPlus0x && Base->isVirtual())
6617 continue;
6618
6619 assert(!Base->getType()->isDependentType() &&
6620 "Cannot generate implicit members for class with dependent bases.");
6621 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6622 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6623 &HasConstCopyAssignment);
6624 }
6625
6626 // In C++0x, the above citation has "or virtual added"
6627 if (LangOpts.CPlusPlus0x) {
6628 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6629 BaseEnd = ClassDecl->vbases_end();
6630 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6631 assert(!Base->getType()->isDependentType() &&
6632 "Cannot generate implicit members for class with dependent bases.");
6633 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6634 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6635 &HasConstCopyAssignment);
6636 }
6637 }
6638
6639 // -- for all the nonstatic data members of X that are of a class
6640 // type M (or array thereof), each such class type has a copy
6641 // assignment operator whose parameter is of type const M&,
6642 // const volatile M& or M.
6643 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6644 FieldEnd = ClassDecl->field_end();
6645 HasConstCopyAssignment && Field != FieldEnd;
6646 ++Field) {
6647 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6648 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6649 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6650 &HasConstCopyAssignment);
6651 }
6652 }
6653
6654 // Otherwise, the implicitly declared copy assignment operator will
6655 // have the form
6656 //
6657 // X& X::operator=(X&)
6658
6659 // C++ [except.spec]p14:
6660 // An implicitly declared special member function (Clause 12) shall have an
6661 // exception-specification. [...]
6662
6663 // It is unspecified whether or not an implicit copy assignment operator
6664 // attempts to deduplicate calls to assignment operators of virtual bases are
6665 // made. As such, this exception specification is effectively unspecified.
6666 // Based on a similar decision made for constness in C++0x, we're erring on
6667 // the side of assuming such calls to be made regardless of whether they
6668 // actually happen.
6669 ImplicitExceptionSpecification ExceptSpec(Context);
6670 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
6671 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6672 BaseEnd = ClassDecl->bases_end();
6673 Base != BaseEnd; ++Base) {
6674 if (Base->isVirtual())
6675 continue;
6676
6677 CXXRecordDecl *BaseClassDecl
6678 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6679 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6680 ArgQuals, false, 0))
6681 ExceptSpec.CalledDecl(CopyAssign);
6682 }
6683
6684 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6685 BaseEnd = ClassDecl->vbases_end();
6686 Base != BaseEnd; ++Base) {
6687 CXXRecordDecl *BaseClassDecl
6688 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6689 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6690 ArgQuals, false, 0))
6691 ExceptSpec.CalledDecl(CopyAssign);
6692 }
6693
6694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6695 FieldEnd = ClassDecl->field_end();
6696 Field != FieldEnd;
6697 ++Field) {
6698 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6699 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6700 if (CXXMethodDecl *CopyAssign =
6701 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6702 ExceptSpec.CalledDecl(CopyAssign);
6703 }
6704 }
6705
6706 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6707 }
6708
DeclareImplicitCopyAssignment(CXXRecordDecl * ClassDecl)6709 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6710 // Note: The following rules are largely analoguous to the copy
6711 // constructor rules. Note that virtual bases are not taken into account
6712 // for determining the argument type of the operator. Note also that
6713 // operators taking an object instead of a reference are allowed.
6714
6715 ImplicitExceptionSpecification Spec(Context);
6716 bool Const;
6717 llvm::tie(Spec, Const) =
6718 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6719
6720 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6721 QualType RetType = Context.getLValueReferenceType(ArgType);
6722 if (Const)
6723 ArgType = ArgType.withConst();
6724 ArgType = Context.getLValueReferenceType(ArgType);
6725
6726 // An implicitly-declared copy assignment operator is an inline public
6727 // member of its class.
6728 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6729 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6730 SourceLocation ClassLoc = ClassDecl->getLocation();
6731 DeclarationNameInfo NameInfo(Name, ClassLoc);
6732 CXXMethodDecl *CopyAssignment
6733 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6734 Context.getFunctionType(RetType, &ArgType, 1, EPI),
6735 /*TInfo=*/0, /*isStatic=*/false,
6736 /*StorageClassAsWritten=*/SC_None,
6737 /*isInline=*/true,
6738 SourceLocation());
6739 CopyAssignment->setAccess(AS_public);
6740 CopyAssignment->setDefaulted();
6741 CopyAssignment->setImplicit();
6742 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
6743
6744 // Add the parameter to the operator.
6745 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
6746 ClassLoc, ClassLoc, /*Id=*/0,
6747 ArgType, /*TInfo=*/0,
6748 SC_None,
6749 SC_None, 0);
6750 CopyAssignment->setParams(&FromParam, 1);
6751
6752 // Note that we have added this copy-assignment operator.
6753 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
6754
6755 if (Scope *S = getScopeForContext(ClassDecl))
6756 PushOnScopeChains(CopyAssignment, S, false);
6757 ClassDecl->addDecl(CopyAssignment);
6758
6759 // C++0x [class.copy]p18:
6760 // ... If the class definition declares a move constructor or move
6761 // assignment operator, the implicitly declared copy assignment operator is
6762 // defined as deleted; ...
6763 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6764 ClassDecl->hasUserDeclaredMoveAssignment() ||
6765 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6766 CopyAssignment->setDeletedAsWritten();
6767
6768 AddOverriddenMethods(ClassDecl, CopyAssignment);
6769 return CopyAssignment;
6770 }
6771
DefineImplicitCopyAssignment(SourceLocation CurrentLocation,CXXMethodDecl * CopyAssignOperator)6772 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6773 CXXMethodDecl *CopyAssignOperator) {
6774 assert((CopyAssignOperator->isDefaulted() &&
6775 CopyAssignOperator->isOverloadedOperator() &&
6776 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
6777 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
6778 "DefineImplicitCopyAssignment called for wrong function");
6779
6780 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6781
6782 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6783 CopyAssignOperator->setInvalidDecl();
6784 return;
6785 }
6786
6787 CopyAssignOperator->setUsed();
6788
6789 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
6790 DiagnosticErrorTrap Trap(Diags);
6791
6792 // C++0x [class.copy]p30:
6793 // The implicitly-defined or explicitly-defaulted copy assignment operator
6794 // for a non-union class X performs memberwise copy assignment of its
6795 // subobjects. The direct base classes of X are assigned first, in the
6796 // order of their declaration in the base-specifier-list, and then the
6797 // immediate non-static data members of X are assigned, in the order in
6798 // which they were declared in the class definition.
6799
6800 // The statements that form the synthesized function body.
6801 ASTOwningVector<Stmt*> Statements(*this);
6802
6803 // The parameter for the "other" object, which we are copying from.
6804 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6805 Qualifiers OtherQuals = Other->getType().getQualifiers();
6806 QualType OtherRefType = Other->getType();
6807 if (const LValueReferenceType *OtherRef
6808 = OtherRefType->getAs<LValueReferenceType>()) {
6809 OtherRefType = OtherRef->getPointeeType();
6810 OtherQuals = OtherRefType.getQualifiers();
6811 }
6812
6813 // Our location for everything implicitly-generated.
6814 SourceLocation Loc = CopyAssignOperator->getLocation();
6815
6816 // Construct a reference to the "other" object. We'll be using this
6817 // throughout the generated ASTs.
6818 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
6819 assert(OtherRef && "Reference to parameter cannot fail!");
6820
6821 // Construct the "this" pointer. We'll be using this throughout the generated
6822 // ASTs.
6823 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6824 assert(This && "Reference to this cannot fail!");
6825
6826 // Assign base classes.
6827 bool Invalid = false;
6828 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6829 E = ClassDecl->bases_end(); Base != E; ++Base) {
6830 // Form the assignment:
6831 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6832 QualType BaseType = Base->getType().getUnqualifiedType();
6833 if (!BaseType->isRecordType()) {
6834 Invalid = true;
6835 continue;
6836 }
6837
6838 CXXCastPath BasePath;
6839 BasePath.push_back(Base);
6840
6841 // Construct the "from" expression, which is an implicit cast to the
6842 // appropriately-qualified base type.
6843 Expr *From = OtherRef;
6844 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6845 CK_UncheckedDerivedToBase,
6846 VK_LValue, &BasePath).take();
6847
6848 // Dereference "this".
6849 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
6850
6851 // Implicitly cast "this" to the appropriately-qualified base type.
6852 To = ImpCastExprToType(To.take(),
6853 Context.getCVRQualifiedType(BaseType,
6854 CopyAssignOperator->getTypeQualifiers()),
6855 CK_UncheckedDerivedToBase,
6856 VK_LValue, &BasePath);
6857
6858 // Build the copy.
6859 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
6860 To.get(), From,
6861 /*CopyingBaseSubobject=*/true);
6862 if (Copy.isInvalid()) {
6863 Diag(CurrentLocation, diag::note_member_synthesized_at)
6864 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6865 CopyAssignOperator->setInvalidDecl();
6866 return;
6867 }
6868
6869 // Success! Record the copy.
6870 Statements.push_back(Copy.takeAs<Expr>());
6871 }
6872
6873 // \brief Reference to the __builtin_memcpy function.
6874 Expr *BuiltinMemCpyRef = 0;
6875 // \brief Reference to the __builtin_objc_memmove_collectable function.
6876 Expr *CollectableMemCpyRef = 0;
6877
6878 // Assign non-static members.
6879 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6880 FieldEnd = ClassDecl->field_end();
6881 Field != FieldEnd; ++Field) {
6882 // Check for members of reference type; we can't copy those.
6883 if (Field->getType()->isReferenceType()) {
6884 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6885 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6886 Diag(Field->getLocation(), diag::note_declared_at);
6887 Diag(CurrentLocation, diag::note_member_synthesized_at)
6888 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6889 Invalid = true;
6890 continue;
6891 }
6892
6893 // Check for members of const-qualified, non-class type.
6894 QualType BaseType = Context.getBaseElementType(Field->getType());
6895 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6896 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6897 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6898 Diag(Field->getLocation(), diag::note_declared_at);
6899 Diag(CurrentLocation, diag::note_member_synthesized_at)
6900 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6901 Invalid = true;
6902 continue;
6903 }
6904
6905 // Suppress assigning zero-width bitfields.
6906 if (const Expr *Width = Field->getBitWidth())
6907 if (Width->EvaluateAsInt(Context) == 0)
6908 continue;
6909
6910 QualType FieldType = Field->getType().getNonReferenceType();
6911 if (FieldType->isIncompleteArrayType()) {
6912 assert(ClassDecl->hasFlexibleArrayMember() &&
6913 "Incomplete array type is not valid");
6914 continue;
6915 }
6916
6917 // Build references to the field in the object we're copying from and to.
6918 CXXScopeSpec SS; // Intentionally empty
6919 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6920 LookupMemberName);
6921 MemberLookup.addDecl(*Field);
6922 MemberLookup.resolveKind();
6923 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
6924 Loc, /*IsArrow=*/false,
6925 SS, 0, MemberLookup, 0);
6926 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
6927 Loc, /*IsArrow=*/true,
6928 SS, 0, MemberLookup, 0);
6929 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6930 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6931
6932 // If the field should be copied with __builtin_memcpy rather than via
6933 // explicit assignments, do so. This optimization only applies for arrays
6934 // of scalars and arrays of class type with trivial copy-assignment
6935 // operators.
6936 if (FieldType->isArrayType() &&
6937 BaseType.hasTrivialCopyAssignment(Context)) {
6938 // Compute the size of the memory buffer to be copied.
6939 QualType SizeType = Context.getSizeType();
6940 llvm::APInt Size(Context.getTypeSize(SizeType),
6941 Context.getTypeSizeInChars(BaseType).getQuantity());
6942 for (const ConstantArrayType *Array
6943 = Context.getAsConstantArrayType(FieldType);
6944 Array;
6945 Array = Context.getAsConstantArrayType(Array->getElementType())) {
6946 llvm::APInt ArraySize
6947 = Array->getSize().zextOrTrunc(Size.getBitWidth());
6948 Size *= ArraySize;
6949 }
6950
6951 // Take the address of the field references for "from" and "to".
6952 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6953 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
6954
6955 bool NeedsCollectableMemCpy =
6956 (BaseType->isRecordType() &&
6957 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6958
6959 if (NeedsCollectableMemCpy) {
6960 if (!CollectableMemCpyRef) {
6961 // Create a reference to the __builtin_objc_memmove_collectable function.
6962 LookupResult R(*this,
6963 &Context.Idents.get("__builtin_objc_memmove_collectable"),
6964 Loc, LookupOrdinaryName);
6965 LookupName(R, TUScope, true);
6966
6967 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6968 if (!CollectableMemCpy) {
6969 // Something went horribly wrong earlier, and we will have
6970 // complained about it.
6971 Invalid = true;
6972 continue;
6973 }
6974
6975 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6976 CollectableMemCpy->getType(),
6977 VK_LValue, Loc, 0).take();
6978 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6979 }
6980 }
6981 // Create a reference to the __builtin_memcpy builtin function.
6982 else if (!BuiltinMemCpyRef) {
6983 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6984 LookupOrdinaryName);
6985 LookupName(R, TUScope, true);
6986
6987 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6988 if (!BuiltinMemCpy) {
6989 // Something went horribly wrong earlier, and we will have complained
6990 // about it.
6991 Invalid = true;
6992 continue;
6993 }
6994
6995 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6996 BuiltinMemCpy->getType(),
6997 VK_LValue, Loc, 0).take();
6998 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6999 }
7000
7001 ASTOwningVector<Expr*> CallArgs(*this);
7002 CallArgs.push_back(To.takeAs<Expr>());
7003 CallArgs.push_back(From.takeAs<Expr>());
7004 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7005 ExprResult Call = ExprError();
7006 if (NeedsCollectableMemCpy)
7007 Call = ActOnCallExpr(/*Scope=*/0,
7008 CollectableMemCpyRef,
7009 Loc, move_arg(CallArgs),
7010 Loc);
7011 else
7012 Call = ActOnCallExpr(/*Scope=*/0,
7013 BuiltinMemCpyRef,
7014 Loc, move_arg(CallArgs),
7015 Loc);
7016
7017 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7018 Statements.push_back(Call.takeAs<Expr>());
7019 continue;
7020 }
7021
7022 // Build the copy of this field.
7023 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7024 To.get(), From.get(),
7025 /*CopyingBaseSubobject=*/false);
7026 if (Copy.isInvalid()) {
7027 Diag(CurrentLocation, diag::note_member_synthesized_at)
7028 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7029 CopyAssignOperator->setInvalidDecl();
7030 return;
7031 }
7032
7033 // Success! Record the copy.
7034 Statements.push_back(Copy.takeAs<Stmt>());
7035 }
7036
7037 if (!Invalid) {
7038 // Add a "return *this;"
7039 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7040
7041 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7042 if (Return.isInvalid())
7043 Invalid = true;
7044 else {
7045 Statements.push_back(Return.takeAs<Stmt>());
7046
7047 if (Trap.hasErrorOccurred()) {
7048 Diag(CurrentLocation, diag::note_member_synthesized_at)
7049 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7050 Invalid = true;
7051 }
7052 }
7053 }
7054
7055 if (Invalid) {
7056 CopyAssignOperator->setInvalidDecl();
7057 return;
7058 }
7059
7060 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7061 /*isStmtExpr=*/false);
7062 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7063 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7064
7065 if (ASTMutationListener *L = getASTMutationListener()) {
7066 L->CompletedImplicitDefinition(CopyAssignOperator);
7067 }
7068 }
7069
7070 std::pair<Sema::ImplicitExceptionSpecification, bool>
ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl * ClassDecl)7071 Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
7072 if (ClassDecl->isInvalidDecl())
7073 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7074
7075 // C++ [class.copy]p5:
7076 // The implicitly-declared copy constructor for a class X will
7077 // have the form
7078 //
7079 // X::X(const X&)
7080 //
7081 // if
7082 // FIXME: It ought to be possible to store this on the record.
7083 bool HasConstCopyConstructor = true;
7084
7085 // -- each direct or virtual base class B of X has a copy
7086 // constructor whose first parameter is of type const B& or
7087 // const volatile B&, and
7088 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7089 BaseEnd = ClassDecl->bases_end();
7090 HasConstCopyConstructor && Base != BaseEnd;
7091 ++Base) {
7092 // Virtual bases are handled below.
7093 if (Base->isVirtual())
7094 continue;
7095
7096 CXXRecordDecl *BaseClassDecl
7097 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7098 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7099 &HasConstCopyConstructor);
7100 }
7101
7102 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7103 BaseEnd = ClassDecl->vbases_end();
7104 HasConstCopyConstructor && Base != BaseEnd;
7105 ++Base) {
7106 CXXRecordDecl *BaseClassDecl
7107 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7108 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7109 &HasConstCopyConstructor);
7110 }
7111
7112 // -- for all the nonstatic data members of X that are of a
7113 // class type M (or array thereof), each such class type
7114 // has a copy constructor whose first parameter is of type
7115 // const M& or const volatile M&.
7116 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7117 FieldEnd = ClassDecl->field_end();
7118 HasConstCopyConstructor && Field != FieldEnd;
7119 ++Field) {
7120 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7121 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7122 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7123 &HasConstCopyConstructor);
7124 }
7125 }
7126 // Otherwise, the implicitly declared copy constructor will have
7127 // the form
7128 //
7129 // X::X(X&)
7130
7131 // C++ [except.spec]p14:
7132 // An implicitly declared special member function (Clause 12) shall have an
7133 // exception-specification. [...]
7134 ImplicitExceptionSpecification ExceptSpec(Context);
7135 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7136 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7137 BaseEnd = ClassDecl->bases_end();
7138 Base != BaseEnd;
7139 ++Base) {
7140 // Virtual bases are handled below.
7141 if (Base->isVirtual())
7142 continue;
7143
7144 CXXRecordDecl *BaseClassDecl
7145 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7146 if (CXXConstructorDecl *CopyConstructor =
7147 LookupCopyingConstructor(BaseClassDecl, Quals))
7148 ExceptSpec.CalledDecl(CopyConstructor);
7149 }
7150 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7151 BaseEnd = ClassDecl->vbases_end();
7152 Base != BaseEnd;
7153 ++Base) {
7154 CXXRecordDecl *BaseClassDecl
7155 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7156 if (CXXConstructorDecl *CopyConstructor =
7157 LookupCopyingConstructor(BaseClassDecl, Quals))
7158 ExceptSpec.CalledDecl(CopyConstructor);
7159 }
7160 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7161 FieldEnd = ClassDecl->field_end();
7162 Field != FieldEnd;
7163 ++Field) {
7164 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7165 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7166 if (CXXConstructorDecl *CopyConstructor =
7167 LookupCopyingConstructor(FieldClassDecl, Quals))
7168 ExceptSpec.CalledDecl(CopyConstructor);
7169 }
7170 }
7171
7172 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7173 }
7174
DeclareImplicitCopyConstructor(CXXRecordDecl * ClassDecl)7175 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7176 CXXRecordDecl *ClassDecl) {
7177 // C++ [class.copy]p4:
7178 // If the class definition does not explicitly declare a copy
7179 // constructor, one is declared implicitly.
7180
7181 ImplicitExceptionSpecification Spec(Context);
7182 bool Const;
7183 llvm::tie(Spec, Const) =
7184 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7185
7186 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7187 QualType ArgType = ClassType;
7188 if (Const)
7189 ArgType = ArgType.withConst();
7190 ArgType = Context.getLValueReferenceType(ArgType);
7191
7192 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7193
7194 DeclarationName Name
7195 = Context.DeclarationNames.getCXXConstructorName(
7196 Context.getCanonicalType(ClassType));
7197 SourceLocation ClassLoc = ClassDecl->getLocation();
7198 DeclarationNameInfo NameInfo(Name, ClassLoc);
7199
7200 // An implicitly-declared copy constructor is an inline public
7201 // member of its class.
7202 CXXConstructorDecl *CopyConstructor
7203 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7204 Context.getFunctionType(Context.VoidTy,
7205 &ArgType, 1, EPI),
7206 /*TInfo=*/0,
7207 /*isExplicit=*/false,
7208 /*isInline=*/true,
7209 /*isImplicitlyDeclared=*/true);
7210 CopyConstructor->setAccess(AS_public);
7211 CopyConstructor->setDefaulted();
7212 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7213
7214 // Note that we have declared this constructor.
7215 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7216
7217 // Add the parameter to the constructor.
7218 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
7219 ClassLoc, ClassLoc,
7220 /*IdentifierInfo=*/0,
7221 ArgType, /*TInfo=*/0,
7222 SC_None,
7223 SC_None, 0);
7224 CopyConstructor->setParams(&FromParam, 1);
7225
7226 if (Scope *S = getScopeForContext(ClassDecl))
7227 PushOnScopeChains(CopyConstructor, S, false);
7228 ClassDecl->addDecl(CopyConstructor);
7229
7230 // C++0x [class.copy]p7:
7231 // ... If the class definition declares a move constructor or move
7232 // assignment operator, the implicitly declared constructor is defined as
7233 // deleted; ...
7234 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7235 ClassDecl->hasUserDeclaredMoveAssignment() ||
7236 ShouldDeleteCopyConstructor(CopyConstructor))
7237 CopyConstructor->setDeletedAsWritten();
7238
7239 return CopyConstructor;
7240 }
7241
DefineImplicitCopyConstructor(SourceLocation CurrentLocation,CXXConstructorDecl * CopyConstructor)7242 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
7243 CXXConstructorDecl *CopyConstructor) {
7244 assert((CopyConstructor->isDefaulted() &&
7245 CopyConstructor->isCopyConstructor() &&
7246 !CopyConstructor->doesThisDeclarationHaveABody()) &&
7247 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
7248
7249 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
7250 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
7251
7252 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
7253 DiagnosticErrorTrap Trap(Diags);
7254
7255 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
7256 Trap.hasErrorOccurred()) {
7257 Diag(CurrentLocation, diag::note_member_synthesized_at)
7258 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
7259 CopyConstructor->setInvalidDecl();
7260 } else {
7261 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7262 CopyConstructor->getLocation(),
7263 MultiStmtArg(*this, 0, 0),
7264 /*isStmtExpr=*/false)
7265 .takeAs<Stmt>());
7266 }
7267
7268 CopyConstructor->setUsed();
7269
7270 if (ASTMutationListener *L = getASTMutationListener()) {
7271 L->CompletedImplicitDefinition(CopyConstructor);
7272 }
7273 }
7274
7275 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,MultiExprArg ExprArgs,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)7276 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7277 CXXConstructorDecl *Constructor,
7278 MultiExprArg ExprArgs,
7279 bool RequiresZeroInit,
7280 unsigned ConstructKind,
7281 SourceRange ParenRange) {
7282 bool Elidable = false;
7283
7284 // C++0x [class.copy]p34:
7285 // When certain criteria are met, an implementation is allowed to
7286 // omit the copy/move construction of a class object, even if the
7287 // copy/move constructor and/or destructor for the object have
7288 // side effects. [...]
7289 // - when a temporary class object that has not been bound to a
7290 // reference (12.2) would be copied/moved to a class object
7291 // with the same cv-unqualified type, the copy/move operation
7292 // can be omitted by constructing the temporary object
7293 // directly into the target of the omitted copy/move
7294 if (ConstructKind == CXXConstructExpr::CK_Complete &&
7295 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
7296 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
7297 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
7298 }
7299
7300 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
7301 Elidable, move(ExprArgs), RequiresZeroInit,
7302 ConstructKind, ParenRange);
7303 }
7304
7305 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
7306 /// including handling of its default argument expressions.
7307 ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc,QualType DeclInitType,CXXConstructorDecl * Constructor,bool Elidable,MultiExprArg ExprArgs,bool RequiresZeroInit,unsigned ConstructKind,SourceRange ParenRange)7308 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7309 CXXConstructorDecl *Constructor, bool Elidable,
7310 MultiExprArg ExprArgs,
7311 bool RequiresZeroInit,
7312 unsigned ConstructKind,
7313 SourceRange ParenRange) {
7314 unsigned NumExprs = ExprArgs.size();
7315 Expr **Exprs = (Expr **)ExprArgs.release();
7316
7317 for (specific_attr_iterator<NonNullAttr>
7318 i = Constructor->specific_attr_begin<NonNullAttr>(),
7319 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7320 const NonNullAttr *NonNull = *i;
7321 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7322 }
7323
7324 MarkDeclarationReferenced(ConstructLoc, Constructor);
7325 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
7326 Constructor, Elidable, Exprs, NumExprs,
7327 RequiresZeroInit,
7328 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7329 ParenRange));
7330 }
7331
InitializeVarWithConstructor(VarDecl * VD,CXXConstructorDecl * Constructor,MultiExprArg Exprs)7332 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
7333 CXXConstructorDecl *Constructor,
7334 MultiExprArg Exprs) {
7335 // FIXME: Provide the correct paren SourceRange when available.
7336 ExprResult TempResult =
7337 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
7338 move(Exprs), false, CXXConstructExpr::CK_Complete,
7339 SourceRange());
7340 if (TempResult.isInvalid())
7341 return true;
7342
7343 Expr *Temp = TempResult.takeAs<Expr>();
7344 CheckImplicitConversions(Temp, VD->getLocation());
7345 MarkDeclarationReferenced(VD->getLocation(), Constructor);
7346 Temp = MaybeCreateExprWithCleanups(Temp);
7347 VD->setInit(Temp);
7348
7349 return false;
7350 }
7351
FinalizeVarWithDestructor(VarDecl * VD,const RecordType * Record)7352 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
7353 if (VD->isInvalidDecl()) return;
7354
7355 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
7356 if (ClassDecl->isInvalidDecl()) return;
7357 if (ClassDecl->hasTrivialDestructor()) return;
7358 if (ClassDecl->isDependentContext()) return;
7359
7360 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7361 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7362 CheckDestructorAccess(VD->getLocation(), Destructor,
7363 PDiag(diag::err_access_dtor_var)
7364 << VD->getDeclName()
7365 << VD->getType());
7366
7367 if (!VD->hasGlobalStorage()) return;
7368
7369 // Emit warning for non-trivial dtor in global scope (a real global,
7370 // class-static, function-static).
7371 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7372
7373 // TODO: this should be re-enabled for static locals by !CXAAtExit
7374 if (!VD->isStaticLocal())
7375 Diag(VD->getLocation(), diag::warn_global_destructor);
7376 }
7377
7378 /// AddCXXDirectInitializerToDecl - This action is called immediately after
7379 /// ActOnDeclarator, when a C++ direct initializer is present.
7380 /// e.g: "int x(1);"
AddCXXDirectInitializerToDecl(Decl * RealDecl,SourceLocation LParenLoc,MultiExprArg Exprs,SourceLocation RParenLoc,bool TypeMayContainAuto)7381 void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
7382 SourceLocation LParenLoc,
7383 MultiExprArg Exprs,
7384 SourceLocation RParenLoc,
7385 bool TypeMayContainAuto) {
7386 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
7387
7388 // If there is no declaration, there was an error parsing it. Just ignore
7389 // the initializer.
7390 if (RealDecl == 0)
7391 return;
7392
7393 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7394 if (!VDecl) {
7395 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7396 RealDecl->setInvalidDecl();
7397 return;
7398 }
7399
7400 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7401 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
7402 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7403 if (Exprs.size() > 1) {
7404 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7405 diag::err_auto_var_init_multiple_expressions)
7406 << VDecl->getDeclName() << VDecl->getType()
7407 << VDecl->getSourceRange();
7408 RealDecl->setInvalidDecl();
7409 return;
7410 }
7411
7412 Expr *Init = Exprs.get()[0];
7413 TypeSourceInfo *DeducedType = 0;
7414 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
7415 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7416 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7417 << Init->getSourceRange();
7418 if (!DeducedType) {
7419 RealDecl->setInvalidDecl();
7420 return;
7421 }
7422 VDecl->setTypeSourceInfo(DeducedType);
7423 VDecl->setType(DeducedType->getType());
7424
7425 // In ARC, infer lifetime.
7426 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7427 VDecl->setInvalidDecl();
7428
7429 // If this is a redeclaration, check that the type we just deduced matches
7430 // the previously declared type.
7431 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7432 MergeVarDeclTypes(VDecl, Old);
7433 }
7434
7435 // We will represent direct-initialization similarly to copy-initialization:
7436 // int x(1); -as-> int x = 1;
7437 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7438 //
7439 // Clients that want to distinguish between the two forms, can check for
7440 // direct initializer using VarDecl::hasCXXDirectInitializer().
7441 // A major benefit is that clients that don't particularly care about which
7442 // exactly form was it (like the CodeGen) can handle both cases without
7443 // special case code.
7444
7445 // C++ 8.5p11:
7446 // The form of initialization (using parentheses or '=') is generally
7447 // insignificant, but does matter when the entity being initialized has a
7448 // class type.
7449
7450 if (!VDecl->getType()->isDependentType() &&
7451 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
7452 diag::err_typecheck_decl_incomplete_type)) {
7453 VDecl->setInvalidDecl();
7454 return;
7455 }
7456
7457 // The variable can not have an abstract class type.
7458 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7459 diag::err_abstract_type_in_decl,
7460 AbstractVariableType))
7461 VDecl->setInvalidDecl();
7462
7463 const VarDecl *Def;
7464 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
7465 Diag(VDecl->getLocation(), diag::err_redefinition)
7466 << VDecl->getDeclName();
7467 Diag(Def->getLocation(), diag::note_previous_definition);
7468 VDecl->setInvalidDecl();
7469 return;
7470 }
7471
7472 // C++ [class.static.data]p4
7473 // If a static data member is of const integral or const
7474 // enumeration type, its declaration in the class definition can
7475 // specify a constant-initializer which shall be an integral
7476 // constant expression (5.19). In that case, the member can appear
7477 // in integral constant expressions. The member shall still be
7478 // defined in a namespace scope if it is used in the program and the
7479 // namespace scope definition shall not contain an initializer.
7480 //
7481 // We already performed a redefinition check above, but for static
7482 // data members we also need to check whether there was an in-class
7483 // declaration with an initializer.
7484 const VarDecl* PrevInit = 0;
7485 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7486 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7487 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7488 return;
7489 }
7490
7491 bool IsDependent = false;
7492 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7493 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7494 VDecl->setInvalidDecl();
7495 return;
7496 }
7497
7498 if (Exprs.get()[I]->isTypeDependent())
7499 IsDependent = true;
7500 }
7501
7502 // If either the declaration has a dependent type or if any of the
7503 // expressions is type-dependent, we represent the initialization
7504 // via a ParenListExpr for later use during template instantiation.
7505 if (VDecl->getType()->isDependentType() || IsDependent) {
7506 // Let clients know that initialization was done with a direct initializer.
7507 VDecl->setCXXDirectInitializer(true);
7508
7509 // Store the initialization expressions as a ParenListExpr.
7510 unsigned NumExprs = Exprs.size();
7511 VDecl->setInit(new (Context) ParenListExpr(
7512 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
7513 VDecl->getType().getNonReferenceType()));
7514 return;
7515 }
7516
7517 // Capture the variable that is being initialized and the style of
7518 // initialization.
7519 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7520
7521 // FIXME: Poor source location information.
7522 InitializationKind Kind
7523 = InitializationKind::CreateDirect(VDecl->getLocation(),
7524 LParenLoc, RParenLoc);
7525
7526 InitializationSequence InitSeq(*this, Entity, Kind,
7527 Exprs.get(), Exprs.size());
7528 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
7529 if (Result.isInvalid()) {
7530 VDecl->setInvalidDecl();
7531 return;
7532 }
7533
7534 CheckImplicitConversions(Result.get(), LParenLoc);
7535
7536 Result = MaybeCreateExprWithCleanups(Result);
7537 VDecl->setInit(Result.takeAs<Expr>());
7538 VDecl->setCXXDirectInitializer(true);
7539
7540 CheckCompleteVariableDeclaration(VDecl);
7541 }
7542
7543 /// \brief Given a constructor and the set of arguments provided for the
7544 /// constructor, convert the arguments and add any required default arguments
7545 /// to form a proper call to this constructor.
7546 ///
7547 /// \returns true if an error occurred, false otherwise.
7548 bool
CompleteConstructorCall(CXXConstructorDecl * Constructor,MultiExprArg ArgsPtr,SourceLocation Loc,ASTOwningVector<Expr * > & ConvertedArgs)7549 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7550 MultiExprArg ArgsPtr,
7551 SourceLocation Loc,
7552 ASTOwningVector<Expr*> &ConvertedArgs) {
7553 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7554 unsigned NumArgs = ArgsPtr.size();
7555 Expr **Args = (Expr **)ArgsPtr.get();
7556
7557 const FunctionProtoType *Proto
7558 = Constructor->getType()->getAs<FunctionProtoType>();
7559 assert(Proto && "Constructor without a prototype?");
7560 unsigned NumArgsInProto = Proto->getNumArgs();
7561
7562 // If too few arguments are available, we'll fill in the rest with defaults.
7563 if (NumArgs < NumArgsInProto)
7564 ConvertedArgs.reserve(NumArgsInProto);
7565 else
7566 ConvertedArgs.reserve(NumArgs);
7567
7568 VariadicCallType CallType =
7569 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7570 llvm::SmallVector<Expr *, 8> AllArgs;
7571 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7572 Proto, 0, Args, NumArgs, AllArgs,
7573 CallType);
7574 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7575 ConvertedArgs.push_back(AllArgs[i]);
7576 return Invalid;
7577 }
7578
7579 static inline bool
CheckOperatorNewDeleteDeclarationScope(Sema & SemaRef,const FunctionDecl * FnDecl)7580 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7581 const FunctionDecl *FnDecl) {
7582 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
7583 if (isa<NamespaceDecl>(DC)) {
7584 return SemaRef.Diag(FnDecl->getLocation(),
7585 diag::err_operator_new_delete_declared_in_namespace)
7586 << FnDecl->getDeclName();
7587 }
7588
7589 if (isa<TranslationUnitDecl>(DC) &&
7590 FnDecl->getStorageClass() == SC_Static) {
7591 return SemaRef.Diag(FnDecl->getLocation(),
7592 diag::err_operator_new_delete_declared_static)
7593 << FnDecl->getDeclName();
7594 }
7595
7596 return false;
7597 }
7598
7599 static inline bool
CheckOperatorNewDeleteTypes(Sema & SemaRef,const FunctionDecl * FnDecl,CanQualType ExpectedResultType,CanQualType ExpectedFirstParamType,unsigned DependentParamTypeDiag,unsigned InvalidParamTypeDiag)7600 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7601 CanQualType ExpectedResultType,
7602 CanQualType ExpectedFirstParamType,
7603 unsigned DependentParamTypeDiag,
7604 unsigned InvalidParamTypeDiag) {
7605 QualType ResultType =
7606 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7607
7608 // Check that the result type is not dependent.
7609 if (ResultType->isDependentType())
7610 return SemaRef.Diag(FnDecl->getLocation(),
7611 diag::err_operator_new_delete_dependent_result_type)
7612 << FnDecl->getDeclName() << ExpectedResultType;
7613
7614 // Check that the result type is what we expect.
7615 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7616 return SemaRef.Diag(FnDecl->getLocation(),
7617 diag::err_operator_new_delete_invalid_result_type)
7618 << FnDecl->getDeclName() << ExpectedResultType;
7619
7620 // A function template must have at least 2 parameters.
7621 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7622 return SemaRef.Diag(FnDecl->getLocation(),
7623 diag::err_operator_new_delete_template_too_few_parameters)
7624 << FnDecl->getDeclName();
7625
7626 // The function decl must have at least 1 parameter.
7627 if (FnDecl->getNumParams() == 0)
7628 return SemaRef.Diag(FnDecl->getLocation(),
7629 diag::err_operator_new_delete_too_few_parameters)
7630 << FnDecl->getDeclName();
7631
7632 // Check the the first parameter type is not dependent.
7633 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7634 if (FirstParamType->isDependentType())
7635 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7636 << FnDecl->getDeclName() << ExpectedFirstParamType;
7637
7638 // Check that the first parameter type is what we expect.
7639 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
7640 ExpectedFirstParamType)
7641 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7642 << FnDecl->getDeclName() << ExpectedFirstParamType;
7643
7644 return false;
7645 }
7646
7647 static bool
CheckOperatorNewDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)7648 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7649 // C++ [basic.stc.dynamic.allocation]p1:
7650 // A program is ill-formed if an allocation function is declared in a
7651 // namespace scope other than global scope or declared static in global
7652 // scope.
7653 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7654 return true;
7655
7656 CanQualType SizeTy =
7657 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7658
7659 // C++ [basic.stc.dynamic.allocation]p1:
7660 // The return type shall be void*. The first parameter shall have type
7661 // std::size_t.
7662 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7663 SizeTy,
7664 diag::err_operator_new_dependent_param_type,
7665 diag::err_operator_new_param_type))
7666 return true;
7667
7668 // C++ [basic.stc.dynamic.allocation]p1:
7669 // The first parameter shall not have an associated default argument.
7670 if (FnDecl->getParamDecl(0)->hasDefaultArg())
7671 return SemaRef.Diag(FnDecl->getLocation(),
7672 diag::err_operator_new_default_arg)
7673 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7674
7675 return false;
7676 }
7677
7678 static bool
CheckOperatorDeleteDeclaration(Sema & SemaRef,const FunctionDecl * FnDecl)7679 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7680 // C++ [basic.stc.dynamic.deallocation]p1:
7681 // A program is ill-formed if deallocation functions are declared in a
7682 // namespace scope other than global scope or declared static in global
7683 // scope.
7684 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7685 return true;
7686
7687 // C++ [basic.stc.dynamic.deallocation]p2:
7688 // Each deallocation function shall return void and its first parameter
7689 // shall be void*.
7690 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7691 SemaRef.Context.VoidPtrTy,
7692 diag::err_operator_delete_dependent_param_type,
7693 diag::err_operator_delete_param_type))
7694 return true;
7695
7696 return false;
7697 }
7698
7699 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
7700 /// of this overloaded operator is well-formed. If so, returns false;
7701 /// otherwise, emits appropriate diagnostics and returns true.
CheckOverloadedOperatorDeclaration(FunctionDecl * FnDecl)7702 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
7703 assert(FnDecl && FnDecl->isOverloadedOperator() &&
7704 "Expected an overloaded operator declaration");
7705
7706 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7707
7708 // C++ [over.oper]p5:
7709 // The allocation and deallocation functions, operator new,
7710 // operator new[], operator delete and operator delete[], are
7711 // described completely in 3.7.3. The attributes and restrictions
7712 // found in the rest of this subclause do not apply to them unless
7713 // explicitly stated in 3.7.3.
7714 if (Op == OO_Delete || Op == OO_Array_Delete)
7715 return CheckOperatorDeleteDeclaration(*this, FnDecl);
7716
7717 if (Op == OO_New || Op == OO_Array_New)
7718 return CheckOperatorNewDeclaration(*this, FnDecl);
7719
7720 // C++ [over.oper]p6:
7721 // An operator function shall either be a non-static member
7722 // function or be a non-member function and have at least one
7723 // parameter whose type is a class, a reference to a class, an
7724 // enumeration, or a reference to an enumeration.
7725 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7726 if (MethodDecl->isStatic())
7727 return Diag(FnDecl->getLocation(),
7728 diag::err_operator_overload_static) << FnDecl->getDeclName();
7729 } else {
7730 bool ClassOrEnumParam = false;
7731 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7732 ParamEnd = FnDecl->param_end();
7733 Param != ParamEnd; ++Param) {
7734 QualType ParamType = (*Param)->getType().getNonReferenceType();
7735 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7736 ParamType->isEnumeralType()) {
7737 ClassOrEnumParam = true;
7738 break;
7739 }
7740 }
7741
7742 if (!ClassOrEnumParam)
7743 return Diag(FnDecl->getLocation(),
7744 diag::err_operator_overload_needs_class_or_enum)
7745 << FnDecl->getDeclName();
7746 }
7747
7748 // C++ [over.oper]p8:
7749 // An operator function cannot have default arguments (8.3.6),
7750 // except where explicitly stated below.
7751 //
7752 // Only the function-call operator allows default arguments
7753 // (C++ [over.call]p1).
7754 if (Op != OO_Call) {
7755 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7756 Param != FnDecl->param_end(); ++Param) {
7757 if ((*Param)->hasDefaultArg())
7758 return Diag((*Param)->getLocation(),
7759 diag::err_operator_overload_default_arg)
7760 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
7761 }
7762 }
7763
7764 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7765 { false, false, false }
7766 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7767 , { Unary, Binary, MemberOnly }
7768 #include "clang/Basic/OperatorKinds.def"
7769 };
7770
7771 bool CanBeUnaryOperator = OperatorUses[Op][0];
7772 bool CanBeBinaryOperator = OperatorUses[Op][1];
7773 bool MustBeMemberOperator = OperatorUses[Op][2];
7774
7775 // C++ [over.oper]p8:
7776 // [...] Operator functions cannot have more or fewer parameters
7777 // than the number required for the corresponding operator, as
7778 // described in the rest of this subclause.
7779 unsigned NumParams = FnDecl->getNumParams()
7780 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
7781 if (Op != OO_Call &&
7782 ((NumParams == 1 && !CanBeUnaryOperator) ||
7783 (NumParams == 2 && !CanBeBinaryOperator) ||
7784 (NumParams < 1) || (NumParams > 2))) {
7785 // We have the wrong number of parameters.
7786 unsigned ErrorKind;
7787 if (CanBeUnaryOperator && CanBeBinaryOperator) {
7788 ErrorKind = 2; // 2 -> unary or binary.
7789 } else if (CanBeUnaryOperator) {
7790 ErrorKind = 0; // 0 -> unary
7791 } else {
7792 assert(CanBeBinaryOperator &&
7793 "All non-call overloaded operators are unary or binary!");
7794 ErrorKind = 1; // 1 -> binary
7795 }
7796
7797 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
7798 << FnDecl->getDeclName() << NumParams << ErrorKind;
7799 }
7800
7801 // Overloaded operators other than operator() cannot be variadic.
7802 if (Op != OO_Call &&
7803 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
7804 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
7805 << FnDecl->getDeclName();
7806 }
7807
7808 // Some operators must be non-static member functions.
7809 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7810 return Diag(FnDecl->getLocation(),
7811 diag::err_operator_overload_must_be_member)
7812 << FnDecl->getDeclName();
7813 }
7814
7815 // C++ [over.inc]p1:
7816 // The user-defined function called operator++ implements the
7817 // prefix and postfix ++ operator. If this function is a member
7818 // function with no parameters, or a non-member function with one
7819 // parameter of class or enumeration type, it defines the prefix
7820 // increment operator ++ for objects of that type. If the function
7821 // is a member function with one parameter (which shall be of type
7822 // int) or a non-member function with two parameters (the second
7823 // of which shall be of type int), it defines the postfix
7824 // increment operator ++ for objects of that type.
7825 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7826 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7827 bool ParamIsInt = false;
7828 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
7829 ParamIsInt = BT->getKind() == BuiltinType::Int;
7830
7831 if (!ParamIsInt)
7832 return Diag(LastParam->getLocation(),
7833 diag::err_operator_overload_post_incdec_must_be_int)
7834 << LastParam->getType() << (Op == OO_MinusMinus);
7835 }
7836
7837 return false;
7838 }
7839
7840 /// CheckLiteralOperatorDeclaration - Check whether the declaration
7841 /// of this literal operator function is well-formed. If so, returns
7842 /// false; otherwise, emits appropriate diagnostics and returns true.
CheckLiteralOperatorDeclaration(FunctionDecl * FnDecl)7843 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7844 DeclContext *DC = FnDecl->getDeclContext();
7845 Decl::Kind Kind = DC->getDeclKind();
7846 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7847 Kind != Decl::LinkageSpec) {
7848 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7849 << FnDecl->getDeclName();
7850 return true;
7851 }
7852
7853 bool Valid = false;
7854
7855 // template <char...> type operator "" name() is the only valid template
7856 // signature, and the only valid signature with no parameters.
7857 if (FnDecl->param_size() == 0) {
7858 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7859 // Must have only one template parameter
7860 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7861 if (Params->size() == 1) {
7862 NonTypeTemplateParmDecl *PmDecl =
7863 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
7864
7865 // The template parameter must be a char parameter pack.
7866 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7867 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7868 Valid = true;
7869 }
7870 }
7871 } else {
7872 // Check the first parameter
7873 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7874
7875 QualType T = (*Param)->getType();
7876
7877 // unsigned long long int, long double, and any character type are allowed
7878 // as the only parameters.
7879 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7880 Context.hasSameType(T, Context.LongDoubleTy) ||
7881 Context.hasSameType(T, Context.CharTy) ||
7882 Context.hasSameType(T, Context.WCharTy) ||
7883 Context.hasSameType(T, Context.Char16Ty) ||
7884 Context.hasSameType(T, Context.Char32Ty)) {
7885 if (++Param == FnDecl->param_end())
7886 Valid = true;
7887 goto FinishedParams;
7888 }
7889
7890 // Otherwise it must be a pointer to const; let's strip those qualifiers.
7891 const PointerType *PT = T->getAs<PointerType>();
7892 if (!PT)
7893 goto FinishedParams;
7894 T = PT->getPointeeType();
7895 if (!T.isConstQualified())
7896 goto FinishedParams;
7897 T = T.getUnqualifiedType();
7898
7899 // Move on to the second parameter;
7900 ++Param;
7901
7902 // If there is no second parameter, the first must be a const char *
7903 if (Param == FnDecl->param_end()) {
7904 if (Context.hasSameType(T, Context.CharTy))
7905 Valid = true;
7906 goto FinishedParams;
7907 }
7908
7909 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7910 // are allowed as the first parameter to a two-parameter function
7911 if (!(Context.hasSameType(T, Context.CharTy) ||
7912 Context.hasSameType(T, Context.WCharTy) ||
7913 Context.hasSameType(T, Context.Char16Ty) ||
7914 Context.hasSameType(T, Context.Char32Ty)))
7915 goto FinishedParams;
7916
7917 // The second and final parameter must be an std::size_t
7918 T = (*Param)->getType().getUnqualifiedType();
7919 if (Context.hasSameType(T, Context.getSizeType()) &&
7920 ++Param == FnDecl->param_end())
7921 Valid = true;
7922 }
7923
7924 // FIXME: This diagnostic is absolutely terrible.
7925 FinishedParams:
7926 if (!Valid) {
7927 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7928 << FnDecl->getDeclName();
7929 return true;
7930 }
7931
7932 return false;
7933 }
7934
7935 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7936 /// linkage specification, including the language and (if present)
7937 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7938 /// the location of the language string literal, which is provided
7939 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7940 /// the '{' brace. Otherwise, this linkage specification does not
7941 /// have any braces.
ActOnStartLinkageSpecification(Scope * S,SourceLocation ExternLoc,SourceLocation LangLoc,llvm::StringRef Lang,SourceLocation LBraceLoc)7942 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7943 SourceLocation LangLoc,
7944 llvm::StringRef Lang,
7945 SourceLocation LBraceLoc) {
7946 LinkageSpecDecl::LanguageIDs Language;
7947 if (Lang == "\"C\"")
7948 Language = LinkageSpecDecl::lang_c;
7949 else if (Lang == "\"C++\"")
7950 Language = LinkageSpecDecl::lang_cxx;
7951 else {
7952 Diag(LangLoc, diag::err_bad_language);
7953 return 0;
7954 }
7955
7956 // FIXME: Add all the various semantics of linkage specifications
7957
7958 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
7959 ExternLoc, LangLoc, Language);
7960 CurContext->addDecl(D);
7961 PushDeclContext(S, D);
7962 return D;
7963 }
7964
7965 /// ActOnFinishLinkageSpecification - Complete the definition of
7966 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
7967 /// valid, it's the position of the closing '}' brace in a linkage
7968 /// specification that uses braces.
ActOnFinishLinkageSpecification(Scope * S,Decl * LinkageSpec,SourceLocation RBraceLoc)7969 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
7970 Decl *LinkageSpec,
7971 SourceLocation RBraceLoc) {
7972 if (LinkageSpec) {
7973 if (RBraceLoc.isValid()) {
7974 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7975 LSDecl->setRBraceLoc(RBraceLoc);
7976 }
7977 PopDeclContext();
7978 }
7979 return LinkageSpec;
7980 }
7981
7982 /// \brief Perform semantic analysis for the variable declaration that
7983 /// occurs within a C++ catch clause, returning the newly-created
7984 /// variable.
BuildExceptionDeclaration(Scope * S,TypeSourceInfo * TInfo,SourceLocation StartLoc,SourceLocation Loc,IdentifierInfo * Name)7985 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
7986 TypeSourceInfo *TInfo,
7987 SourceLocation StartLoc,
7988 SourceLocation Loc,
7989 IdentifierInfo *Name) {
7990 bool Invalid = false;
7991 QualType ExDeclType = TInfo->getType();
7992
7993 // Arrays and functions decay.
7994 if (ExDeclType->isArrayType())
7995 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7996 else if (ExDeclType->isFunctionType())
7997 ExDeclType = Context.getPointerType(ExDeclType);
7998
7999 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8000 // The exception-declaration shall not denote a pointer or reference to an
8001 // incomplete type, other than [cv] void*.
8002 // N2844 forbids rvalue references.
8003 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
8004 Diag(Loc, diag::err_catch_rvalue_ref);
8005 Invalid = true;
8006 }
8007
8008 // GCC allows catching pointers and references to incomplete types
8009 // as an extension; so do we, but we warn by default.
8010
8011 QualType BaseType = ExDeclType;
8012 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
8013 unsigned DK = diag::err_catch_incomplete;
8014 bool IncompleteCatchIsInvalid = true;
8015 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
8016 BaseType = Ptr->getPointeeType();
8017 Mode = 1;
8018 DK = diag::ext_catch_incomplete_ptr;
8019 IncompleteCatchIsInvalid = false;
8020 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
8021 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
8022 BaseType = Ref->getPointeeType();
8023 Mode = 2;
8024 DK = diag::ext_catch_incomplete_ref;
8025 IncompleteCatchIsInvalid = false;
8026 }
8027 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
8028 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8029 IncompleteCatchIsInvalid)
8030 Invalid = true;
8031
8032 if (!Invalid && !ExDeclType->isDependentType() &&
8033 RequireNonAbstractType(Loc, ExDeclType,
8034 diag::err_abstract_type_in_decl,
8035 AbstractVariableType))
8036 Invalid = true;
8037
8038 // Only the non-fragile NeXT runtime currently supports C++ catches
8039 // of ObjC types, and no runtime supports catching ObjC types by value.
8040 if (!Invalid && getLangOptions().ObjC1) {
8041 QualType T = ExDeclType;
8042 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8043 T = RT->getPointeeType();
8044
8045 if (T->isObjCObjectType()) {
8046 Diag(Loc, diag::err_objc_object_catch);
8047 Invalid = true;
8048 } else if (T->isObjCObjectPointerType()) {
8049 if (!getLangOptions().ObjCNonFragileABI)
8050 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
8051 }
8052 }
8053
8054 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8055 ExDeclType, TInfo, SC_None, SC_None);
8056 ExDecl->setExceptionVariable(true);
8057
8058 if (!Invalid && !ExDeclType->isDependentType()) {
8059 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
8060 // C++ [except.handle]p16:
8061 // The object declared in an exception-declaration or, if the
8062 // exception-declaration does not specify a name, a temporary (12.2) is
8063 // copy-initialized (8.5) from the exception object. [...]
8064 // The object is destroyed when the handler exits, after the destruction
8065 // of any automatic objects initialized within the handler.
8066 //
8067 // We just pretend to initialize the object with itself, then make sure
8068 // it can be destroyed later.
8069 QualType initType = ExDeclType;
8070
8071 InitializedEntity entity =
8072 InitializedEntity::InitializeVariable(ExDecl);
8073 InitializationKind initKind =
8074 InitializationKind::CreateCopy(Loc, SourceLocation());
8075
8076 Expr *opaqueValue =
8077 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8078 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8079 ExprResult result = sequence.Perform(*this, entity, initKind,
8080 MultiExprArg(&opaqueValue, 1));
8081 if (result.isInvalid())
8082 Invalid = true;
8083 else {
8084 // If the constructor used was non-trivial, set this as the
8085 // "initializer".
8086 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8087 if (!construct->getConstructor()->isTrivial()) {
8088 Expr *init = MaybeCreateExprWithCleanups(construct);
8089 ExDecl->setInit(init);
8090 }
8091
8092 // And make sure it's destructable.
8093 FinalizeVarWithDestructor(ExDecl, recordType);
8094 }
8095 }
8096 }
8097
8098 if (Invalid)
8099 ExDecl->setInvalidDecl();
8100
8101 return ExDecl;
8102 }
8103
8104 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8105 /// handler.
ActOnExceptionDeclarator(Scope * S,Declarator & D)8106 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
8107 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8108 bool Invalid = D.isInvalidType();
8109
8110 // Check for unexpanded parameter packs.
8111 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8112 UPPC_ExceptionType)) {
8113 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8114 D.getIdentifierLoc());
8115 Invalid = true;
8116 }
8117
8118 IdentifierInfo *II = D.getIdentifier();
8119 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
8120 LookupOrdinaryName,
8121 ForRedeclaration)) {
8122 // The scope should be freshly made just for us. There is just no way
8123 // it contains any previous declaration.
8124 assert(!S->isDeclScope(PrevDecl));
8125 if (PrevDecl->isTemplateParameter()) {
8126 // Maybe we will complain about the shadowed template parameter.
8127 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8128 }
8129 }
8130
8131 if (D.getCXXScopeSpec().isSet() && !Invalid) {
8132 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8133 << D.getCXXScopeSpec().getRange();
8134 Invalid = true;
8135 }
8136
8137 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
8138 D.getSourceRange().getBegin(),
8139 D.getIdentifierLoc(),
8140 D.getIdentifier());
8141 if (Invalid)
8142 ExDecl->setInvalidDecl();
8143
8144 // Add the exception declaration into this scope.
8145 if (II)
8146 PushOnScopeChains(ExDecl, S);
8147 else
8148 CurContext->addDecl(ExDecl);
8149
8150 ProcessDeclAttributes(S, ExDecl, D);
8151 return ExDecl;
8152 }
8153
ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,Expr * AssertExpr,Expr * AssertMessageExpr_,SourceLocation RParenLoc)8154 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
8155 Expr *AssertExpr,
8156 Expr *AssertMessageExpr_,
8157 SourceLocation RParenLoc) {
8158 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
8159
8160 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8161 llvm::APSInt Value(32);
8162 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
8163 Diag(StaticAssertLoc,
8164 diag::err_static_assert_expression_is_not_constant) <<
8165 AssertExpr->getSourceRange();
8166 return 0;
8167 }
8168
8169 if (Value == 0) {
8170 Diag(StaticAssertLoc, diag::err_static_assert_failed)
8171 << AssertMessage->getString() << AssertExpr->getSourceRange();
8172 }
8173 }
8174
8175 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8176 return 0;
8177
8178 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8179 AssertExpr, AssertMessage, RParenLoc);
8180
8181 CurContext->addDecl(Decl);
8182 return Decl;
8183 }
8184
8185 /// \brief Perform semantic analysis of the given friend type declaration.
8186 ///
8187 /// \returns A friend declaration that.
CheckFriendTypeDecl(SourceLocation FriendLoc,TypeSourceInfo * TSInfo)8188 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8189 TypeSourceInfo *TSInfo) {
8190 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8191
8192 QualType T = TSInfo->getType();
8193 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
8194
8195 if (!getLangOptions().CPlusPlus0x) {
8196 // C++03 [class.friend]p2:
8197 // An elaborated-type-specifier shall be used in a friend declaration
8198 // for a class.*
8199 //
8200 // * The class-key of the elaborated-type-specifier is required.
8201 if (!ActiveTemplateInstantiations.empty()) {
8202 // Do not complain about the form of friend template types during
8203 // template instantiation; we will already have complained when the
8204 // template was declared.
8205 } else if (!T->isElaboratedTypeSpecifier()) {
8206 // If we evaluated the type to a record type, suggest putting
8207 // a tag in front.
8208 if (const RecordType *RT = T->getAs<RecordType>()) {
8209 RecordDecl *RD = RT->getDecl();
8210
8211 std::string InsertionText = std::string(" ") + RD->getKindName();
8212
8213 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8214 << (unsigned) RD->getTagKind()
8215 << T
8216 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8217 InsertionText);
8218 } else {
8219 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8220 << T
8221 << SourceRange(FriendLoc, TypeRange.getEnd());
8222 }
8223 } else if (T->getAs<EnumType>()) {
8224 Diag(FriendLoc, diag::ext_enum_friend)
8225 << T
8226 << SourceRange(FriendLoc, TypeRange.getEnd());
8227 }
8228 }
8229
8230 // C++0x [class.friend]p3:
8231 // If the type specifier in a friend declaration designates a (possibly
8232 // cv-qualified) class type, that class is declared as a friend; otherwise,
8233 // the friend declaration is ignored.
8234
8235 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8236 // in [class.friend]p3 that we do not implement.
8237
8238 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8239 }
8240
8241 /// Handle a friend tag declaration where the scope specifier was
8242 /// templated.
ActOnTemplatedFriendTag(Scope * S,SourceLocation FriendLoc,unsigned TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,AttributeList * Attr,MultiTemplateParamsArg TempParamLists)8243 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8244 unsigned TagSpec, SourceLocation TagLoc,
8245 CXXScopeSpec &SS,
8246 IdentifierInfo *Name, SourceLocation NameLoc,
8247 AttributeList *Attr,
8248 MultiTemplateParamsArg TempParamLists) {
8249 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8250
8251 bool isExplicitSpecialization = false;
8252 bool Invalid = false;
8253
8254 if (TemplateParameterList *TemplateParams
8255 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
8256 TempParamLists.get(),
8257 TempParamLists.size(),
8258 /*friend*/ true,
8259 isExplicitSpecialization,
8260 Invalid)) {
8261 if (TemplateParams->size() > 0) {
8262 // This is a declaration of a class template.
8263 if (Invalid)
8264 return 0;
8265
8266 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8267 SS, Name, NameLoc, Attr,
8268 TemplateParams, AS_public,
8269 TempParamLists.size() - 1,
8270 (TemplateParameterList**) TempParamLists.release()).take();
8271 } else {
8272 // The "template<>" header is extraneous.
8273 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8274 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8275 isExplicitSpecialization = true;
8276 }
8277 }
8278
8279 if (Invalid) return 0;
8280
8281 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8282
8283 bool isAllExplicitSpecializations = true;
8284 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
8285 if (TempParamLists.get()[I]->size()) {
8286 isAllExplicitSpecializations = false;
8287 break;
8288 }
8289 }
8290
8291 // FIXME: don't ignore attributes.
8292
8293 // If it's explicit specializations all the way down, just forget
8294 // about the template header and build an appropriate non-templated
8295 // friend. TODO: for source fidelity, remember the headers.
8296 if (isAllExplicitSpecializations) {
8297 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8298 ElaboratedTypeKeyword Keyword
8299 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8300 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
8301 *Name, NameLoc);
8302 if (T.isNull())
8303 return 0;
8304
8305 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8306 if (isa<DependentNameType>(T)) {
8307 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8308 TL.setKeywordLoc(TagLoc);
8309 TL.setQualifierLoc(QualifierLoc);
8310 TL.setNameLoc(NameLoc);
8311 } else {
8312 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8313 TL.setKeywordLoc(TagLoc);
8314 TL.setQualifierLoc(QualifierLoc);
8315 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8316 }
8317
8318 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8319 TSI, FriendLoc);
8320 Friend->setAccess(AS_public);
8321 CurContext->addDecl(Friend);
8322 return Friend;
8323 }
8324
8325 // Handle the case of a templated-scope friend class. e.g.
8326 // template <class T> class A<T>::B;
8327 // FIXME: we don't support these right now.
8328 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8329 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8330 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8331 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8332 TL.setKeywordLoc(TagLoc);
8333 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8334 TL.setNameLoc(NameLoc);
8335
8336 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8337 TSI, FriendLoc);
8338 Friend->setAccess(AS_public);
8339 Friend->setUnsupportedFriend(true);
8340 CurContext->addDecl(Friend);
8341 return Friend;
8342 }
8343
8344
8345 /// Handle a friend type declaration. This works in tandem with
8346 /// ActOnTag.
8347 ///
8348 /// Notes on friend class templates:
8349 ///
8350 /// We generally treat friend class declarations as if they were
8351 /// declaring a class. So, for example, the elaborated type specifier
8352 /// in a friend declaration is required to obey the restrictions of a
8353 /// class-head (i.e. no typedefs in the scope chain), template
8354 /// parameters are required to match up with simple template-ids, &c.
8355 /// However, unlike when declaring a template specialization, it's
8356 /// okay to refer to a template specialization without an empty
8357 /// template parameter declaration, e.g.
8358 /// friend class A<T>::B<unsigned>;
8359 /// We permit this as a special case; if there are any template
8360 /// parameters present at all, require proper matching, i.e.
8361 /// template <> template <class T> friend class A<int>::B;
ActOnFriendTypeDecl(Scope * S,const DeclSpec & DS,MultiTemplateParamsArg TempParams)8362 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
8363 MultiTemplateParamsArg TempParams) {
8364 SourceLocation Loc = DS.getSourceRange().getBegin();
8365
8366 assert(DS.isFriendSpecified());
8367 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8368
8369 // Try to convert the decl specifier to a type. This works for
8370 // friend templates because ActOnTag never produces a ClassTemplateDecl
8371 // for a TUK_Friend.
8372 Declarator TheDeclarator(DS, Declarator::MemberContext);
8373 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8374 QualType T = TSI->getType();
8375 if (TheDeclarator.isInvalidType())
8376 return 0;
8377
8378 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8379 return 0;
8380
8381 // This is definitely an error in C++98. It's probably meant to
8382 // be forbidden in C++0x, too, but the specification is just
8383 // poorly written.
8384 //
8385 // The problem is with declarations like the following:
8386 // template <T> friend A<T>::foo;
8387 // where deciding whether a class C is a friend or not now hinges
8388 // on whether there exists an instantiation of A that causes
8389 // 'foo' to equal C. There are restrictions on class-heads
8390 // (which we declare (by fiat) elaborated friend declarations to
8391 // be) that makes this tractable.
8392 //
8393 // FIXME: handle "template <> friend class A<T>;", which
8394 // is possibly well-formed? Who even knows?
8395 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
8396 Diag(Loc, diag::err_tagless_friend_type_template)
8397 << DS.getSourceRange();
8398 return 0;
8399 }
8400
8401 // C++98 [class.friend]p1: A friend of a class is a function
8402 // or class that is not a member of the class . . .
8403 // This is fixed in DR77, which just barely didn't make the C++03
8404 // deadline. It's also a very silly restriction that seriously
8405 // affects inner classes and which nobody else seems to implement;
8406 // thus we never diagnose it, not even in -pedantic.
8407 //
8408 // But note that we could warn about it: it's always useless to
8409 // friend one of your own members (it's not, however, worthless to
8410 // friend a member of an arbitrary specialization of your template).
8411
8412 Decl *D;
8413 if (unsigned NumTempParamLists = TempParams.size())
8414 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
8415 NumTempParamLists,
8416 TempParams.release(),
8417 TSI,
8418 DS.getFriendSpecLoc());
8419 else
8420 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8421
8422 if (!D)
8423 return 0;
8424
8425 D->setAccess(AS_public);
8426 CurContext->addDecl(D);
8427
8428 return D;
8429 }
8430
ActOnFriendFunctionDecl(Scope * S,Declarator & D,bool IsDefinition,MultiTemplateParamsArg TemplateParams)8431 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8432 MultiTemplateParamsArg TemplateParams) {
8433 const DeclSpec &DS = D.getDeclSpec();
8434
8435 assert(DS.isFriendSpecified());
8436 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8437
8438 SourceLocation Loc = D.getIdentifierLoc();
8439 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8440 QualType T = TInfo->getType();
8441
8442 // C++ [class.friend]p1
8443 // A friend of a class is a function or class....
8444 // Note that this sees through typedefs, which is intended.
8445 // It *doesn't* see through dependent types, which is correct
8446 // according to [temp.arg.type]p3:
8447 // If a declaration acquires a function type through a
8448 // type dependent on a template-parameter and this causes
8449 // a declaration that does not use the syntactic form of a
8450 // function declarator to have a function type, the program
8451 // is ill-formed.
8452 if (!T->isFunctionType()) {
8453 Diag(Loc, diag::err_unexpected_friend);
8454
8455 // It might be worthwhile to try to recover by creating an
8456 // appropriate declaration.
8457 return 0;
8458 }
8459
8460 // C++ [namespace.memdef]p3
8461 // - If a friend declaration in a non-local class first declares a
8462 // class or function, the friend class or function is a member
8463 // of the innermost enclosing namespace.
8464 // - The name of the friend is not found by simple name lookup
8465 // until a matching declaration is provided in that namespace
8466 // scope (either before or after the class declaration granting
8467 // friendship).
8468 // - If a friend function is called, its name may be found by the
8469 // name lookup that considers functions from namespaces and
8470 // classes associated with the types of the function arguments.
8471 // - When looking for a prior declaration of a class or a function
8472 // declared as a friend, scopes outside the innermost enclosing
8473 // namespace scope are not considered.
8474
8475 CXXScopeSpec &SS = D.getCXXScopeSpec();
8476 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8477 DeclarationName Name = NameInfo.getName();
8478 assert(Name);
8479
8480 // Check for unexpanded parameter packs.
8481 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8482 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8483 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8484 return 0;
8485
8486 // The context we found the declaration in, or in which we should
8487 // create the declaration.
8488 DeclContext *DC;
8489 Scope *DCScope = S;
8490 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8491 ForRedeclaration);
8492
8493 // FIXME: there are different rules in local classes
8494
8495 // There are four cases here.
8496 // - There's no scope specifier, in which case we just go to the
8497 // appropriate scope and look for a function or function template
8498 // there as appropriate.
8499 // Recover from invalid scope qualifiers as if they just weren't there.
8500 if (SS.isInvalid() || !SS.isSet()) {
8501 // C++0x [namespace.memdef]p3:
8502 // If the name in a friend declaration is neither qualified nor
8503 // a template-id and the declaration is a function or an
8504 // elaborated-type-specifier, the lookup to determine whether
8505 // the entity has been previously declared shall not consider
8506 // any scopes outside the innermost enclosing namespace.
8507 // C++0x [class.friend]p11:
8508 // If a friend declaration appears in a local class and the name
8509 // specified is an unqualified name, a prior declaration is
8510 // looked up without considering scopes that are outside the
8511 // innermost enclosing non-class scope. For a friend function
8512 // declaration, if there is no prior declaration, the program is
8513 // ill-formed.
8514 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
8515 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
8516
8517 // Find the appropriate context according to the above.
8518 DC = CurContext;
8519 while (true) {
8520 // Skip class contexts. If someone can cite chapter and verse
8521 // for this behavior, that would be nice --- it's what GCC and
8522 // EDG do, and it seems like a reasonable intent, but the spec
8523 // really only says that checks for unqualified existing
8524 // declarations should stop at the nearest enclosing namespace,
8525 // not that they should only consider the nearest enclosing
8526 // namespace.
8527 while (DC->isRecord())
8528 DC = DC->getParent();
8529
8530 LookupQualifiedName(Previous, DC);
8531
8532 // TODO: decide what we think about using declarations.
8533 if (isLocal || !Previous.empty())
8534 break;
8535
8536 if (isTemplateId) {
8537 if (isa<TranslationUnitDecl>(DC)) break;
8538 } else {
8539 if (DC->isFileContext()) break;
8540 }
8541 DC = DC->getParent();
8542 }
8543
8544 // C++ [class.friend]p1: A friend of a class is a function or
8545 // class that is not a member of the class . . .
8546 // C++0x changes this for both friend types and functions.
8547 // Most C++ 98 compilers do seem to give an error here, so
8548 // we do, too.
8549 if (!Previous.empty() && DC->Equals(CurContext)
8550 && !getLangOptions().CPlusPlus0x)
8551 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8552
8553 DCScope = getScopeForDeclContext(S, DC);
8554
8555 // - There's a non-dependent scope specifier, in which case we
8556 // compute it and do a previous lookup there for a function
8557 // or function template.
8558 } else if (!SS.getScopeRep()->isDependent()) {
8559 DC = computeDeclContext(SS);
8560 if (!DC) return 0;
8561
8562 if (RequireCompleteDeclContext(SS, DC)) return 0;
8563
8564 LookupQualifiedName(Previous, DC);
8565
8566 // Ignore things found implicitly in the wrong scope.
8567 // TODO: better diagnostics for this case. Suggesting the right
8568 // qualified scope would be nice...
8569 LookupResult::Filter F = Previous.makeFilter();
8570 while (F.hasNext()) {
8571 NamedDecl *D = F.next();
8572 if (!DC->InEnclosingNamespaceSetOf(
8573 D->getDeclContext()->getRedeclContext()))
8574 F.erase();
8575 }
8576 F.done();
8577
8578 if (Previous.empty()) {
8579 D.setInvalidType();
8580 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8581 return 0;
8582 }
8583
8584 // C++ [class.friend]p1: A friend of a class is a function or
8585 // class that is not a member of the class . . .
8586 if (DC->Equals(CurContext))
8587 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8588
8589 // - There's a scope specifier that does not match any template
8590 // parameter lists, in which case we use some arbitrary context,
8591 // create a method or method template, and wait for instantiation.
8592 // - There's a scope specifier that does match some template
8593 // parameter lists, which we don't handle right now.
8594 } else {
8595 DC = CurContext;
8596 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
8597 }
8598
8599 if (!DC->isRecord()) {
8600 // This implies that it has to be an operator or function.
8601 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8602 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8603 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
8604 Diag(Loc, diag::err_introducing_special_friend) <<
8605 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8606 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
8607 return 0;
8608 }
8609 }
8610
8611 bool Redeclaration = false;
8612 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
8613 move(TemplateParams),
8614 IsDefinition,
8615 Redeclaration);
8616 if (!ND) return 0;
8617
8618 assert(ND->getDeclContext() == DC);
8619 assert(ND->getLexicalDeclContext() == CurContext);
8620
8621 // Add the function declaration to the appropriate lookup tables,
8622 // adjusting the redeclarations list as necessary. We don't
8623 // want to do this yet if the friending class is dependent.
8624 //
8625 // Also update the scope-based lookup if the target context's
8626 // lookup context is in lexical scope.
8627 if (!CurContext->isDependentContext()) {
8628 DC = DC->getRedeclContext();
8629 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
8630 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8631 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
8632 }
8633
8634 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
8635 D.getIdentifierLoc(), ND,
8636 DS.getFriendSpecLoc());
8637 FrD->setAccess(AS_public);
8638 CurContext->addDecl(FrD);
8639
8640 if (ND->isInvalidDecl())
8641 FrD->setInvalidDecl();
8642 else {
8643 FunctionDecl *FD;
8644 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8645 FD = FTD->getTemplatedDecl();
8646 else
8647 FD = cast<FunctionDecl>(ND);
8648
8649 // Mark templated-scope function declarations as unsupported.
8650 if (FD->getNumTemplateParameterLists())
8651 FrD->setUnsupportedFriend(true);
8652 }
8653
8654 return ND;
8655 }
8656
SetDeclDeleted(Decl * Dcl,SourceLocation DelLoc)8657 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8658 AdjustDeclIfTemplate(Dcl);
8659
8660 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8661 if (!Fn) {
8662 Diag(DelLoc, diag::err_deleted_non_function);
8663 return;
8664 }
8665 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8666 Diag(DelLoc, diag::err_deleted_decl_not_first);
8667 Diag(Prev->getLocation(), diag::note_previous_declaration);
8668 // If the declaration wasn't the first, we delete the function anyway for
8669 // recovery.
8670 }
8671 Fn->setDeletedAsWritten();
8672 }
8673
SetDeclDefaulted(Decl * Dcl,SourceLocation DefaultLoc)8674 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8675 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8676
8677 if (MD) {
8678 if (MD->getParent()->isDependentType()) {
8679 MD->setDefaulted();
8680 MD->setExplicitlyDefaulted();
8681 return;
8682 }
8683
8684 CXXSpecialMember Member = getSpecialMember(MD);
8685 if (Member == CXXInvalid) {
8686 Diag(DefaultLoc, diag::err_default_special_members);
8687 return;
8688 }
8689
8690 MD->setDefaulted();
8691 MD->setExplicitlyDefaulted();
8692
8693 // If this definition appears within the record, do the checking when
8694 // the record is complete.
8695 const FunctionDecl *Primary = MD;
8696 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8697 // Find the uninstantiated declaration that actually had the '= default'
8698 // on it.
8699 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8700
8701 if (Primary == Primary->getCanonicalDecl())
8702 return;
8703
8704 switch (Member) {
8705 case CXXDefaultConstructor: {
8706 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8707 CheckExplicitlyDefaultedDefaultConstructor(CD);
8708 if (!CD->isInvalidDecl())
8709 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8710 break;
8711 }
8712
8713 case CXXCopyConstructor: {
8714 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8715 CheckExplicitlyDefaultedCopyConstructor(CD);
8716 if (!CD->isInvalidDecl())
8717 DefineImplicitCopyConstructor(DefaultLoc, CD);
8718 break;
8719 }
8720
8721 case CXXCopyAssignment: {
8722 CheckExplicitlyDefaultedCopyAssignment(MD);
8723 if (!MD->isInvalidDecl())
8724 DefineImplicitCopyAssignment(DefaultLoc, MD);
8725 break;
8726 }
8727
8728 case CXXDestructor: {
8729 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8730 CheckExplicitlyDefaultedDestructor(DD);
8731 if (!DD->isInvalidDecl())
8732 DefineImplicitDestructor(DefaultLoc, DD);
8733 break;
8734 }
8735
8736 case CXXMoveConstructor:
8737 case CXXMoveAssignment:
8738 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8739 break;
8740
8741 default:
8742 // FIXME: Do the rest once we have move functions
8743 break;
8744 }
8745 } else {
8746 Diag(DefaultLoc, diag::err_default_special_members);
8747 }
8748 }
8749
SearchForReturnInStmt(Sema & Self,Stmt * S)8750 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
8751 for (Stmt::child_range CI = S->children(); CI; ++CI) {
8752 Stmt *SubStmt = *CI;
8753 if (!SubStmt)
8754 continue;
8755 if (isa<ReturnStmt>(SubStmt))
8756 Self.Diag(SubStmt->getSourceRange().getBegin(),
8757 diag::err_return_in_constructor_handler);
8758 if (!isa<Expr>(SubStmt))
8759 SearchForReturnInStmt(Self, SubStmt);
8760 }
8761 }
8762
DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt * TryBlock)8763 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8764 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8765 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8766 SearchForReturnInStmt(*this, Handler);
8767 }
8768 }
8769
CheckOverridingFunctionReturnType(const CXXMethodDecl * New,const CXXMethodDecl * Old)8770 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
8771 const CXXMethodDecl *Old) {
8772 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8773 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
8774
8775 if (Context.hasSameType(NewTy, OldTy) ||
8776 NewTy->isDependentType() || OldTy->isDependentType())
8777 return false;
8778
8779 // Check if the return types are covariant
8780 QualType NewClassTy, OldClassTy;
8781
8782 /// Both types must be pointers or references to classes.
8783 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8784 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
8785 NewClassTy = NewPT->getPointeeType();
8786 OldClassTy = OldPT->getPointeeType();
8787 }
8788 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8789 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8790 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8791 NewClassTy = NewRT->getPointeeType();
8792 OldClassTy = OldRT->getPointeeType();
8793 }
8794 }
8795 }
8796
8797 // The return types aren't either both pointers or references to a class type.
8798 if (NewClassTy.isNull()) {
8799 Diag(New->getLocation(),
8800 diag::err_different_return_type_for_overriding_virtual_function)
8801 << New->getDeclName() << NewTy << OldTy;
8802 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8803
8804 return true;
8805 }
8806
8807 // C++ [class.virtual]p6:
8808 // If the return type of D::f differs from the return type of B::f, the
8809 // class type in the return type of D::f shall be complete at the point of
8810 // declaration of D::f or shall be the class type D.
8811 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8812 if (!RT->isBeingDefined() &&
8813 RequireCompleteType(New->getLocation(), NewClassTy,
8814 PDiag(diag::err_covariant_return_incomplete)
8815 << New->getDeclName()))
8816 return true;
8817 }
8818
8819 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
8820 // Check if the new class derives from the old class.
8821 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8822 Diag(New->getLocation(),
8823 diag::err_covariant_return_not_derived)
8824 << New->getDeclName() << NewTy << OldTy;
8825 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8826 return true;
8827 }
8828
8829 // Check if we the conversion from derived to base is valid.
8830 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
8831 diag::err_covariant_return_inaccessible_base,
8832 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8833 // FIXME: Should this point to the return type?
8834 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
8835 // FIXME: this note won't trigger for delayed access control
8836 // diagnostics, and it's impossible to get an undelayed error
8837 // here from access control during the original parse because
8838 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
8839 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8840 return true;
8841 }
8842 }
8843
8844 // The qualifiers of the return types must be the same.
8845 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
8846 Diag(New->getLocation(),
8847 diag::err_covariant_return_type_different_qualifications)
8848 << New->getDeclName() << NewTy << OldTy;
8849 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8850 return true;
8851 };
8852
8853
8854 // The new class type must have the same or less qualifiers as the old type.
8855 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8856 Diag(New->getLocation(),
8857 diag::err_covariant_return_type_class_type_more_qualified)
8858 << New->getDeclName() << NewTy << OldTy;
8859 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8860 return true;
8861 };
8862
8863 return false;
8864 }
8865
8866 /// \brief Mark the given method pure.
8867 ///
8868 /// \param Method the method to be marked pure.
8869 ///
8870 /// \param InitRange the source range that covers the "0" initializer.
CheckPureMethod(CXXMethodDecl * Method,SourceRange InitRange)8871 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
8872 SourceLocation EndLoc = InitRange.getEnd();
8873 if (EndLoc.isValid())
8874 Method->setRangeEnd(EndLoc);
8875
8876 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8877 Method->setPure();
8878 return false;
8879 }
8880
8881 if (!Method->isInvalidDecl())
8882 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8883 << Method->getDeclName() << InitRange;
8884 return true;
8885 }
8886
8887 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8888 /// an initializer for the out-of-line declaration 'Dcl'. The scope
8889 /// is a fresh scope pushed for just this purpose.
8890 ///
8891 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8892 /// static data member of class X, names should be looked up in the scope of
8893 /// class X.
ActOnCXXEnterDeclInitializer(Scope * S,Decl * D)8894 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
8895 // If there is no declaration, there was an error parsing it.
8896 if (D == 0 || D->isInvalidDecl()) return;
8897
8898 // We should only get called for declarations with scope specifiers, like:
8899 // int foo::bar;
8900 assert(D->isOutOfLine());
8901 EnterDeclaratorContext(S, D->getDeclContext());
8902 }
8903
8904 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
8905 /// initializer for the out-of-line declaration 'D'.
ActOnCXXExitDeclInitializer(Scope * S,Decl * D)8906 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
8907 // If there is no declaration, there was an error parsing it.
8908 if (D == 0 || D->isInvalidDecl()) return;
8909
8910 assert(D->isOutOfLine());
8911 ExitDeclaratorContext(S);
8912 }
8913
8914 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8915 /// C++ if/switch/while/for statement.
8916 /// e.g: "if (int x = f()) {...}"
ActOnCXXConditionDeclaration(Scope * S,Declarator & D)8917 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
8918 // C++ 6.4p2:
8919 // The declarator shall not specify a function or an array.
8920 // The type-specifier-seq shall not contain typedef and shall not declare a
8921 // new class or enumeration.
8922 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8923 "Parser allowed 'typedef' as storage class of condition decl.");
8924
8925 Decl *Dcl = ActOnDeclarator(S, D);
8926 if (!Dcl)
8927 return true;
8928
8929 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
8930 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
8931 << D.getSourceRange();
8932 return true;
8933 }
8934
8935 return Dcl;
8936 }
8937
MarkVTableUsed(SourceLocation Loc,CXXRecordDecl * Class,bool DefinitionRequired)8938 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8939 bool DefinitionRequired) {
8940 // Ignore any vtable uses in unevaluated operands or for classes that do
8941 // not have a vtable.
8942 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8943 CurContext->isDependentContext() ||
8944 ExprEvalContexts.back().Context == Unevaluated)
8945 return;
8946
8947 // Try to insert this class into the map.
8948 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8949 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8950 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8951 if (!Pos.second) {
8952 // If we already had an entry, check to see if we are promoting this vtable
8953 // to required a definition. If so, we need to reappend to the VTableUses
8954 // list, since we may have already processed the first entry.
8955 if (DefinitionRequired && !Pos.first->second) {
8956 Pos.first->second = true;
8957 } else {
8958 // Otherwise, we can early exit.
8959 return;
8960 }
8961 }
8962
8963 // Local classes need to have their virtual members marked
8964 // immediately. For all other classes, we mark their virtual members
8965 // at the end of the translation unit.
8966 if (Class->isLocalClass())
8967 MarkVirtualMembersReferenced(Loc, Class);
8968 else
8969 VTableUses.push_back(std::make_pair(Class, Loc));
8970 }
8971
DefineUsedVTables()8972 bool Sema::DefineUsedVTables() {
8973 if (VTableUses.empty())
8974 return false;
8975
8976 // Note: The VTableUses vector could grow as a result of marking
8977 // the members of a class as "used", so we check the size each
8978 // time through the loop and prefer indices (with are stable) to
8979 // iterators (which are not).
8980 bool DefinedAnything = false;
8981 for (unsigned I = 0; I != VTableUses.size(); ++I) {
8982 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
8983 if (!Class)
8984 continue;
8985
8986 SourceLocation Loc = VTableUses[I].second;
8987
8988 // If this class has a key function, but that key function is
8989 // defined in another translation unit, we don't need to emit the
8990 // vtable even though we're using it.
8991 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
8992 if (KeyFunction && !KeyFunction->hasBody()) {
8993 switch (KeyFunction->getTemplateSpecializationKind()) {
8994 case TSK_Undeclared:
8995 case TSK_ExplicitSpecialization:
8996 case TSK_ExplicitInstantiationDeclaration:
8997 // The key function is in another translation unit.
8998 continue;
8999
9000 case TSK_ExplicitInstantiationDefinition:
9001 case TSK_ImplicitInstantiation:
9002 // We will be instantiating the key function.
9003 break;
9004 }
9005 } else if (!KeyFunction) {
9006 // If we have a class with no key function that is the subject
9007 // of an explicit instantiation declaration, suppress the
9008 // vtable; it will live with the explicit instantiation
9009 // definition.
9010 bool IsExplicitInstantiationDeclaration
9011 = Class->getTemplateSpecializationKind()
9012 == TSK_ExplicitInstantiationDeclaration;
9013 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9014 REnd = Class->redecls_end();
9015 R != REnd; ++R) {
9016 TemplateSpecializationKind TSK
9017 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9018 if (TSK == TSK_ExplicitInstantiationDeclaration)
9019 IsExplicitInstantiationDeclaration = true;
9020 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9021 IsExplicitInstantiationDeclaration = false;
9022 break;
9023 }
9024 }
9025
9026 if (IsExplicitInstantiationDeclaration)
9027 continue;
9028 }
9029
9030 // Mark all of the virtual members of this class as referenced, so
9031 // that we can build a vtable. Then, tell the AST consumer that a
9032 // vtable for this class is required.
9033 DefinedAnything = true;
9034 MarkVirtualMembersReferenced(Loc, Class);
9035 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9036 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9037
9038 // Optionally warn if we're emitting a weak vtable.
9039 if (Class->getLinkage() == ExternalLinkage &&
9040 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
9041 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
9042 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9043 }
9044 }
9045 VTableUses.clear();
9046
9047 return DefinedAnything;
9048 }
9049
MarkVirtualMembersReferenced(SourceLocation Loc,const CXXRecordDecl * RD)9050 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9051 const CXXRecordDecl *RD) {
9052 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9053 e = RD->method_end(); i != e; ++i) {
9054 CXXMethodDecl *MD = *i;
9055
9056 // C++ [basic.def.odr]p2:
9057 // [...] A virtual member function is used if it is not pure. [...]
9058 if (MD->isVirtual() && !MD->isPure())
9059 MarkDeclarationReferenced(Loc, MD);
9060 }
9061
9062 // Only classes that have virtual bases need a VTT.
9063 if (RD->getNumVBases() == 0)
9064 return;
9065
9066 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9067 e = RD->bases_end(); i != e; ++i) {
9068 const CXXRecordDecl *Base =
9069 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
9070 if (Base->getNumVBases() == 0)
9071 continue;
9072 MarkVirtualMembersReferenced(Loc, Base);
9073 }
9074 }
9075
9076 /// SetIvarInitializers - This routine builds initialization ASTs for the
9077 /// Objective-C implementation whose ivars need be initialized.
SetIvarInitializers(ObjCImplementationDecl * ObjCImplementation)9078 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9079 if (!getLangOptions().CPlusPlus)
9080 return;
9081 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
9082 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9083 CollectIvarsToConstructOrDestruct(OID, ivars);
9084 if (ivars.empty())
9085 return;
9086 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
9087 for (unsigned i = 0; i < ivars.size(); i++) {
9088 FieldDecl *Field = ivars[i];
9089 if (Field->isInvalidDecl())
9090 continue;
9091
9092 CXXCtorInitializer *Member;
9093 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9094 InitializationKind InitKind =
9095 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9096
9097 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
9098 ExprResult MemberInit =
9099 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
9100 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
9101 // Note, MemberInit could actually come back empty if no initialization
9102 // is required (e.g., because it would call a trivial default constructor)
9103 if (!MemberInit.get() || MemberInit.isInvalid())
9104 continue;
9105
9106 Member =
9107 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9108 SourceLocation(),
9109 MemberInit.takeAs<Expr>(),
9110 SourceLocation());
9111 AllToInit.push_back(Member);
9112
9113 // Be sure that the destructor is accessible and is marked as referenced.
9114 if (const RecordType *RecordTy
9115 = Context.getBaseElementType(Field->getType())
9116 ->getAs<RecordType>()) {
9117 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
9118 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
9119 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9120 CheckDestructorAccess(Field->getLocation(), Destructor,
9121 PDiag(diag::err_access_dtor_ivar)
9122 << Context.getBaseElementType(Field->getType()));
9123 }
9124 }
9125 }
9126 ObjCImplementation->setIvarInitializers(Context,
9127 AllToInit.data(), AllToInit.size());
9128 }
9129 }
9130
9131 static
DelegatingCycleHelper(CXXConstructorDecl * Ctor,llvm::SmallSet<CXXConstructorDecl *,4> & Valid,llvm::SmallSet<CXXConstructorDecl *,4> & Invalid,llvm::SmallSet<CXXConstructorDecl *,4> & Current,Sema & S)9132 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9133 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9134 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9135 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9136 Sema &S) {
9137 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9138 CE = Current.end();
9139 if (Ctor->isInvalidDecl())
9140 return;
9141
9142 const FunctionDecl *FNTarget = 0;
9143 CXXConstructorDecl *Target;
9144
9145 // We ignore the result here since if we don't have a body, Target will be
9146 // null below.
9147 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9148 Target
9149 = const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9150
9151 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9152 // Avoid dereferencing a null pointer here.
9153 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9154
9155 if (!Current.insert(Canonical))
9156 return;
9157
9158 // We know that beyond here, we aren't chaining into a cycle.
9159 if (!Target || !Target->isDelegatingConstructor() ||
9160 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9161 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9162 Valid.insert(*CI);
9163 Current.clear();
9164 // We've hit a cycle.
9165 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9166 Current.count(TCanonical)) {
9167 // If we haven't diagnosed this cycle yet, do so now.
9168 if (!Invalid.count(TCanonical)) {
9169 S.Diag((*Ctor->init_begin())->getSourceLocation(),
9170 diag::warn_delegating_ctor_cycle)
9171 << Ctor;
9172
9173 // Don't add a note for a function delegating directo to itself.
9174 if (TCanonical != Canonical)
9175 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9176
9177 CXXConstructorDecl *C = Target;
9178 while (C->getCanonicalDecl() != Canonical) {
9179 (void)C->getTargetConstructor()->hasBody(FNTarget);
9180 assert(FNTarget && "Ctor cycle through bodiless function");
9181
9182 C
9183 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9184 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9185 }
9186 }
9187
9188 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9189 Invalid.insert(*CI);
9190 Current.clear();
9191 } else {
9192 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9193 }
9194 }
9195
9196
CheckDelegatingCtorCycles()9197 void Sema::CheckDelegatingCtorCycles() {
9198 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9199
9200 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9201 CE = Current.end();
9202
9203 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
9204 I = DelegatingCtorDecls.begin(),
9205 E = DelegatingCtorDecls.end();
9206 I != E; ++I) {
9207 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
9208 }
9209
9210 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9211 (*CI)->setInvalidDecl();
9212 }
9213