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