SemaDeclCXX.cpp revision e0883603389c5f380354474e0d6d1d63827f0c30
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/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTMutationListener.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/DeclVisitor.h" 21#include "clang/AST/EvaluatedExprVisitor.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/RecordLayout.h" 24#include "clang/AST/RecursiveASTVisitor.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Sema/CXXFieldCollector.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/Initialization.h" 34#include "clang/Sema/Lookup.h" 35#include "clang/Sema/ParsedTemplate.h" 36#include "clang/Sema/Scope.h" 37#include "clang/Sema/ScopeInfo.h" 38#include "llvm/ADT/STLExtras.h" 39#include "llvm/ADT/SmallString.h" 40#include <map> 41#include <set> 42 43using namespace clang; 44 45//===----------------------------------------------------------------------===// 46// CheckDefaultArgumentVisitor 47//===----------------------------------------------------------------------===// 48 49namespace { 50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 51 /// the default argument of a parameter to determine whether it 52 /// contains any ill-formed subexpressions. For example, this will 53 /// diagnose the use of local variables or parameters within the 54 /// default argument expression. 55 class CheckDefaultArgumentVisitor 56 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 57 Expr *DefaultArg; 58 Sema *S; 59 60 public: 61 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 62 : DefaultArg(defarg), S(s) {} 63 64 bool VisitExpr(Expr *Node); 65 bool VisitDeclRefExpr(DeclRefExpr *DRE); 66 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 67 bool VisitLambdaExpr(LambdaExpr *Lambda); 68 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 69 }; 70 71 /// VisitExpr - Visit all of the children of this expression. 72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 73 bool IsInvalid = false; 74 for (Stmt::child_range I = Node->children(); I; ++I) 75 IsInvalid |= Visit(*I); 76 return IsInvalid; 77 } 78 79 /// VisitDeclRefExpr - Visit a reference to a declaration, to 80 /// determine whether this declaration can be used in the default 81 /// argument expression. 82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 83 NamedDecl *Decl = DRE->getDecl(); 84 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 85 // C++ [dcl.fct.default]p9 86 // Default arguments are evaluated each time the function is 87 // called. The order of evaluation of function arguments is 88 // unspecified. Consequently, parameters of a function shall not 89 // be used in default argument expressions, even if they are not 90 // evaluated. Parameters of a function declared before a default 91 // argument expression are in scope and can hide namespace and 92 // class member names. 93 return S->Diag(DRE->getLocStart(), 94 diag::err_param_default_argument_references_param) 95 << Param->getDeclName() << DefaultArg->getSourceRange(); 96 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 97 // C++ [dcl.fct.default]p7 98 // Local variables shall not be used in default argument 99 // expressions. 100 if (VDecl->isLocalVarDecl()) 101 return S->Diag(DRE->getLocStart(), 102 diag::err_param_default_argument_references_local) 103 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 104 } 105 106 return false; 107 } 108 109 /// VisitCXXThisExpr - Visit a C++ "this" expression. 110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 111 // C++ [dcl.fct.default]p8: 112 // The keyword this shall not be used in a default argument of a 113 // member function. 114 return S->Diag(ThisE->getLocStart(), 115 diag::err_param_default_argument_references_this) 116 << ThisE->getSourceRange(); 117 } 118 119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 120 bool Invalid = false; 121 for (PseudoObjectExpr::semantics_iterator 122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 123 Expr *E = *i; 124 125 // Look through bindings. 126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 127 E = OVE->getSourceExpr(); 128 assert(E && "pseudo-object binding without source expression?"); 129 } 130 131 Invalid |= Visit(E); 132 } 133 return Invalid; 134 } 135 136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 137 // C++11 [expr.lambda.prim]p13: 138 // A lambda-expression appearing in a default argument shall not 139 // implicitly or explicitly capture any entity. 140 if (Lambda->capture_begin() == Lambda->capture_end()) 141 return false; 142 143 return S->Diag(Lambda->getLocStart(), 144 diag::err_lambda_capture_default_arg); 145 } 146} 147 148void 149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 150 const CXXMethodDecl *Method) { 151 // If we have an MSAny spec already, don't bother. 152 if (!Method || ComputedEST == EST_MSAny) 153 return; 154 155 const FunctionProtoType *Proto 156 = Method->getType()->getAs<FunctionProtoType>(); 157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 158 if (!Proto) 159 return; 160 161 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 162 163 // If this function can throw any exceptions, make a note of that. 164 if (EST == EST_MSAny || EST == EST_None) { 165 ClearExceptions(); 166 ComputedEST = EST; 167 return; 168 } 169 170 // FIXME: If the call to this decl is using any of its default arguments, we 171 // need to search them for potentially-throwing calls. 172 173 // If this function has a basic noexcept, it doesn't affect the outcome. 174 if (EST == EST_BasicNoexcept) 175 return; 176 177 // If we have a throw-all spec at this point, ignore the function. 178 if (ComputedEST == EST_None) 179 return; 180 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 if (EST == EST_DynamicNone) { 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 } 188 189 // Check out noexcept specs. 190 if (EST == EST_ComputedNoexcept) { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 199 // noexcept(false) -> no spec on the new function 200 if (NR == FunctionProtoType::NR_Throw) { 201 ClearExceptions(); 202 ComputedEST = EST_None; 203 } 204 // noexcept(true) won't change anything either. 205 return; 206 } 207 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 214 EEnd = Proto->exception_end(); 215 E != EEnd; ++E) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 217 Exceptions.push_back(*E); 218} 219 220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247} 248 249bool 250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.takeAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293} 294 295/// ActOnParamDefaultArgument - Check whether the default argument 296/// provided for a function parameter is well-formed. If so, attach it 297/// to the parameter declaration. 298void 299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329} 330 331/// ActOnParamUnparsedDefaultArgument - We've seen a default 332/// argument for a function parameter, but we can't parse it yet 333/// because we're inside a class definition. Note that this default 334/// argument will be parsed later. 335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 if (Param) 343 Param->setUnparsedDefaultArg(); 344 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346} 347 348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349/// the default argument for the parameter param failed. 350void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 356 Param->setInvalidDecl(); 357 358 UnparsedDefaultArgLocs.erase(Param); 359} 360 361/// CheckExtraCXXDefaultArguments - Check for any extra default 362/// arguments in the declarator, which is not a function declaration 363/// or definition and therefore is not permitted to have default 364/// arguments. This routine should be invoked for every declarator 365/// that is not a function declaration or definition. 366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 367 // C++ [dcl.fct.default]p3 368 // A default argument expression shall be specified only in the 369 // parameter-declaration-clause of a function declaration or in a 370 // template-parameter (14.1). It shall not be specified for a 371 // parameter pack. If it is specified in a 372 // parameter-declaration-clause, it shall not occur within a 373 // declarator or abstract-declarator of a parameter-declaration. 374 bool MightBeFunction = D.isFunctionDeclarationContext(); 375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 376 DeclaratorChunk &chunk = D.getTypeObject(i); 377 if (chunk.Kind == DeclaratorChunk::Function) { 378 if (MightBeFunction) { 379 // This is a function declaration. It can have default arguments, but 380 // keep looking in case its return type is a function type with default 381 // arguments. 382 MightBeFunction = false; 383 continue; 384 } 385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 386 ParmVarDecl *Param = 387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 388 if (Param->hasUnparsedDefaultArg()) { 389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 391 << SourceRange((*Toks)[1].getLocation(), 392 Toks->back().getLocation()); 393 delete Toks; 394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 395 } else if (Param->getDefaultArg()) { 396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 397 << Param->getDefaultArg()->getSourceRange(); 398 Param->setDefaultArg(0); 399 } 400 } 401 } else if (chunk.Kind != DeclaratorChunk::Paren) { 402 MightBeFunction = false; 403 } 404 } 405} 406 407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 410 if (!PVD->hasDefaultArg()) 411 return false; 412 if (!PVD->hasInheritedDefaultArg()) 413 return true; 414 } 415 return false; 416} 417 418/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 419/// function, once we already know that they have the same 420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 421/// error, false otherwise. 422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 423 Scope *S) { 424 bool Invalid = false; 425 426 // C++ [dcl.fct.default]p4: 427 // For non-template functions, default arguments can be added in 428 // later declarations of a function in the same 429 // scope. Declarations in different scopes have completely 430 // distinct sets of default arguments. That is, declarations in 431 // inner scopes do not acquire default arguments from 432 // declarations in outer scopes, and vice versa. In a given 433 // function declaration, all parameters subsequent to a 434 // parameter with a default argument shall have default 435 // arguments supplied in this or previous declarations. A 436 // default argument shall not be redefined by a later 437 // declaration (not even to the same value). 438 // 439 // C++ [dcl.fct.default]p6: 440 // Except for member functions of class templates, the default arguments 441 // in a member function definition that appears outside of the class 442 // definition are added to the set of default arguments provided by the 443 // member function declaration in the class definition. 444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 445 ParmVarDecl *OldParam = Old->getParamDecl(p); 446 ParmVarDecl *NewParam = New->getParamDecl(p); 447 448 bool OldParamHasDfl = OldParam->hasDefaultArg(); 449 bool NewParamHasDfl = NewParam->hasDefaultArg(); 450 451 NamedDecl *ND = Old; 452 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 453 // Ignore default parameters of old decl if they are not in 454 // the same scope. 455 OldParamHasDfl = false; 456 457 if (OldParamHasDfl && NewParamHasDfl) { 458 459 unsigned DiagDefaultParamID = 460 diag::err_param_default_argument_redefinition; 461 462 // MSVC accepts that default parameters be redefined for member functions 463 // of template class. The new default parameter's value is ignored. 464 Invalid = true; 465 if (getLangOpts().MicrosoftExt) { 466 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 467 if (MD && MD->getParent()->getDescribedClassTemplate()) { 468 // Merge the old default argument into the new parameter. 469 NewParam->setHasInheritedDefaultArg(); 470 if (OldParam->hasUninstantiatedDefaultArg()) 471 NewParam->setUninstantiatedDefaultArg( 472 OldParam->getUninstantiatedDefaultArg()); 473 else 474 NewParam->setDefaultArg(OldParam->getInit()); 475 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 476 Invalid = false; 477 } 478 } 479 480 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 481 // hint here. Alternatively, we could walk the type-source information 482 // for NewParam to find the last source location in the type... but it 483 // isn't worth the effort right now. This is the kind of test case that 484 // is hard to get right: 485 // int f(int); 486 // void g(int (*fp)(int) = f); 487 // void g(int (*fp)(int) = &f); 488 Diag(NewParam->getLocation(), DiagDefaultParamID) 489 << NewParam->getDefaultArgRange(); 490 491 // Look for the function declaration where the default argument was 492 // actually written, which may be a declaration prior to Old. 493 for (FunctionDecl *Older = Old->getPreviousDecl(); 494 Older; Older = Older->getPreviousDecl()) { 495 if (!Older->getParamDecl(p)->hasDefaultArg()) 496 break; 497 498 OldParam = Older->getParamDecl(p); 499 } 500 501 Diag(OldParam->getLocation(), diag::note_previous_definition) 502 << OldParam->getDefaultArgRange(); 503 } else if (OldParamHasDfl) { 504 // Merge the old default argument into the new parameter. 505 // It's important to use getInit() here; getDefaultArg() 506 // strips off any top-level ExprWithCleanups. 507 NewParam->setHasInheritedDefaultArg(); 508 if (OldParam->hasUninstantiatedDefaultArg()) 509 NewParam->setUninstantiatedDefaultArg( 510 OldParam->getUninstantiatedDefaultArg()); 511 else 512 NewParam->setDefaultArg(OldParam->getInit()); 513 } else if (NewParamHasDfl) { 514 if (New->getDescribedFunctionTemplate()) { 515 // Paragraph 4, quoted above, only applies to non-template functions. 516 Diag(NewParam->getLocation(), 517 diag::err_param_default_argument_template_redecl) 518 << NewParam->getDefaultArgRange(); 519 Diag(Old->getLocation(), diag::note_template_prev_declaration) 520 << false; 521 } else if (New->getTemplateSpecializationKind() 522 != TSK_ImplicitInstantiation && 523 New->getTemplateSpecializationKind() != TSK_Undeclared) { 524 // C++ [temp.expr.spec]p21: 525 // Default function arguments shall not be specified in a declaration 526 // or a definition for one of the following explicit specializations: 527 // - the explicit specialization of a function template; 528 // - the explicit specialization of a member function template; 529 // - the explicit specialization of a member function of a class 530 // template where the class template specialization to which the 531 // member function specialization belongs is implicitly 532 // instantiated. 533 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 534 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 535 << New->getDeclName() 536 << NewParam->getDefaultArgRange(); 537 } else if (New->getDeclContext()->isDependentContext()) { 538 // C++ [dcl.fct.default]p6 (DR217): 539 // Default arguments for a member function of a class template shall 540 // be specified on the initial declaration of the member function 541 // within the class template. 542 // 543 // Reading the tea leaves a bit in DR217 and its reference to DR205 544 // leads me to the conclusion that one cannot add default function 545 // arguments for an out-of-line definition of a member function of a 546 // dependent type. 547 int WhichKind = 2; 548 if (CXXRecordDecl *Record 549 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 550 if (Record->getDescribedClassTemplate()) 551 WhichKind = 0; 552 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 553 WhichKind = 1; 554 else 555 WhichKind = 2; 556 } 557 558 Diag(NewParam->getLocation(), 559 diag::err_param_default_argument_member_template_redecl) 560 << WhichKind 561 << NewParam->getDefaultArgRange(); 562 } 563 } 564 } 565 566 // DR1344: If a default argument is added outside a class definition and that 567 // default argument makes the function a special member function, the program 568 // is ill-formed. This can only happen for constructors. 569 if (isa<CXXConstructorDecl>(New) && 570 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 571 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 572 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 573 if (NewSM != OldSM) { 574 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 575 assert(NewParam->hasDefaultArg()); 576 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 577 << NewParam->getDefaultArgRange() << NewSM; 578 Diag(Old->getLocation(), diag::note_previous_declaration); 579 } 580 } 581 582 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 583 // template has a constexpr specifier then all its declarations shall 584 // contain the constexpr specifier. 585 if (New->isConstexpr() != Old->isConstexpr()) { 586 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 587 << New << New->isConstexpr(); 588 Diag(Old->getLocation(), diag::note_previous_declaration); 589 Invalid = true; 590 } 591 592 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 593 // argument expression, that declaration shall be a definition and shall be 594 // the only declaration of the function or function template in the 595 // translation unit. 596 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 597 functionDeclHasDefaultArgument(Old)) { 598 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 599 Diag(Old->getLocation(), diag::note_previous_declaration); 600 Invalid = true; 601 } 602 603 if (CheckEquivalentExceptionSpec(Old, New)) 604 Invalid = true; 605 606 return Invalid; 607} 608 609/// \brief Merge the exception specifications of two variable declarations. 610/// 611/// This is called when there's a redeclaration of a VarDecl. The function 612/// checks if the redeclaration might have an exception specification and 613/// validates compatibility and merges the specs if necessary. 614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 615 // Shortcut if exceptions are disabled. 616 if (!getLangOpts().CXXExceptions) 617 return; 618 619 assert(Context.hasSameType(New->getType(), Old->getType()) && 620 "Should only be called if types are otherwise the same."); 621 622 QualType NewType = New->getType(); 623 QualType OldType = Old->getType(); 624 625 // We're only interested in pointers and references to functions, as well 626 // as pointers to member functions. 627 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 628 NewType = R->getPointeeType(); 629 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 630 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 631 NewType = P->getPointeeType(); 632 OldType = OldType->getAs<PointerType>()->getPointeeType(); 633 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 634 NewType = M->getPointeeType(); 635 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 636 } 637 638 if (!NewType->isFunctionProtoType()) 639 return; 640 641 // There's lots of special cases for functions. For function pointers, system 642 // libraries are hopefully not as broken so that we don't need these 643 // workarounds. 644 if (CheckEquivalentExceptionSpec( 645 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 646 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 647 New->setInvalidDecl(); 648 } 649} 650 651/// CheckCXXDefaultArguments - Verify that the default arguments for a 652/// function declaration are well-formed according to C++ 653/// [dcl.fct.default]. 654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 655 unsigned NumParams = FD->getNumParams(); 656 unsigned p; 657 658 // Find first parameter with a default argument 659 for (p = 0; p < NumParams; ++p) { 660 ParmVarDecl *Param = FD->getParamDecl(p); 661 if (Param->hasDefaultArg()) 662 break; 663 } 664 665 // C++ [dcl.fct.default]p4: 666 // In a given function declaration, all parameters 667 // subsequent to a parameter with a default argument shall 668 // have default arguments supplied in this or previous 669 // declarations. A default argument shall not be redefined 670 // by a later declaration (not even to the same value). 671 unsigned LastMissingDefaultArg = 0; 672 for (; p < NumParams; ++p) { 673 ParmVarDecl *Param = FD->getParamDecl(p); 674 if (!Param->hasDefaultArg()) { 675 if (Param->isInvalidDecl()) 676 /* We already complained about this parameter. */; 677 else if (Param->getIdentifier()) 678 Diag(Param->getLocation(), 679 diag::err_param_default_argument_missing_name) 680 << Param->getIdentifier(); 681 else 682 Diag(Param->getLocation(), 683 diag::err_param_default_argument_missing); 684 685 LastMissingDefaultArg = p; 686 } 687 } 688 689 if (LastMissingDefaultArg > 0) { 690 // Some default arguments were missing. Clear out all of the 691 // default arguments up to (and including) the last missing 692 // default argument, so that we leave the function parameters 693 // in a semantically valid state. 694 for (p = 0; p <= LastMissingDefaultArg; ++p) { 695 ParmVarDecl *Param = FD->getParamDecl(p); 696 if (Param->hasDefaultArg()) { 697 Param->setDefaultArg(0); 698 } 699 } 700 } 701} 702 703// CheckConstexprParameterTypes - Check whether a function's parameter types 704// are all literal types. If so, return true. If not, produce a suitable 705// diagnostic and return false. 706static bool CheckConstexprParameterTypes(Sema &SemaRef, 707 const FunctionDecl *FD) { 708 unsigned ArgIndex = 0; 709 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 710 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 711 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 712 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 713 SourceLocation ParamLoc = PD->getLocation(); 714 if (!(*i)->isDependentType() && 715 SemaRef.RequireLiteralType(ParamLoc, *i, 716 diag::err_constexpr_non_literal_param, 717 ArgIndex+1, PD->getSourceRange(), 718 isa<CXXConstructorDecl>(FD))) 719 return false; 720 } 721 return true; 722} 723 724/// \brief Get diagnostic %select index for tag kind for 725/// record diagnostic message. 726/// WARNING: Indexes apply to particular diagnostics only! 727/// 728/// \returns diagnostic %select index. 729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 730 switch (Tag) { 731 case TTK_Struct: return 0; 732 case TTK_Interface: return 1; 733 case TTK_Class: return 2; 734 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 735 } 736} 737 738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 739// the requirements of a constexpr function definition or a constexpr 740// constructor definition. If so, return true. If not, produce appropriate 741// diagnostics and return false. 742// 743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 745 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 746 if (MD && MD->isInstance()) { 747 // C++11 [dcl.constexpr]p4: 748 // The definition of a constexpr constructor shall satisfy the following 749 // constraints: 750 // - the class shall not have any virtual base classes; 751 const CXXRecordDecl *RD = MD->getParent(); 752 if (RD->getNumVBases()) { 753 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 754 << isa<CXXConstructorDecl>(NewFD) 755 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 756 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 757 E = RD->vbases_end(); I != E; ++I) 758 Diag(I->getLocStart(), 759 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 760 return false; 761 } 762 } 763 764 if (!isa<CXXConstructorDecl>(NewFD)) { 765 // C++11 [dcl.constexpr]p3: 766 // The definition of a constexpr function shall satisfy the following 767 // constraints: 768 // - it shall not be virtual; 769 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 770 if (Method && Method->isVirtual()) { 771 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 772 773 // If it's not obvious why this function is virtual, find an overridden 774 // function which uses the 'virtual' keyword. 775 const CXXMethodDecl *WrittenVirtual = Method; 776 while (!WrittenVirtual->isVirtualAsWritten()) 777 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 778 if (WrittenVirtual != Method) 779 Diag(WrittenVirtual->getLocation(), 780 diag::note_overridden_virtual_function); 781 return false; 782 } 783 784 // - its return type shall be a literal type; 785 QualType RT = NewFD->getResultType(); 786 if (!RT->isDependentType() && 787 RequireLiteralType(NewFD->getLocation(), RT, 788 diag::err_constexpr_non_literal_return)) 789 return false; 790 } 791 792 // - each of its parameter types shall be a literal type; 793 if (!CheckConstexprParameterTypes(*this, NewFD)) 794 return false; 795 796 return true; 797} 798 799/// Check the given declaration statement is legal within a constexpr function 800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 801/// 802/// \return true if the body is OK (maybe only as an extension), false if we 803/// have diagnosed a problem. 804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 805 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 806 // C++11 [dcl.constexpr]p3 and p4: 807 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 808 // contain only 809 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 810 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 811 switch ((*DclIt)->getKind()) { 812 case Decl::StaticAssert: 813 case Decl::Using: 814 case Decl::UsingShadow: 815 case Decl::UsingDirective: 816 case Decl::UnresolvedUsingTypename: 817 case Decl::UnresolvedUsingValue: 818 // - static_assert-declarations 819 // - using-declarations, 820 // - using-directives, 821 continue; 822 823 case Decl::Typedef: 824 case Decl::TypeAlias: { 825 // - typedef declarations and alias-declarations that do not define 826 // classes or enumerations, 827 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 828 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 829 // Don't allow variably-modified types in constexpr functions. 830 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 831 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 832 << TL.getSourceRange() << TL.getType() 833 << isa<CXXConstructorDecl>(Dcl); 834 return false; 835 } 836 continue; 837 } 838 839 case Decl::Enum: 840 case Decl::CXXRecord: 841 // C++1y allows types to be defined, not just declared. 842 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 843 SemaRef.Diag(DS->getLocStart(), 844 SemaRef.getLangOpts().CPlusPlus1y 845 ? diag::warn_cxx11_compat_constexpr_type_definition 846 : diag::ext_constexpr_type_definition) 847 << isa<CXXConstructorDecl>(Dcl); 848 continue; 849 850 case Decl::EnumConstant: 851 case Decl::IndirectField: 852 case Decl::ParmVar: 853 // These can only appear with other declarations which are banned in 854 // C++11 and permitted in C++1y, so ignore them. 855 continue; 856 857 case Decl::Var: { 858 // C++1y [dcl.constexpr]p3 allows anything except: 859 // a definition of a variable of non-literal type or of static or 860 // thread storage duration or for which no initialization is performed. 861 VarDecl *VD = cast<VarDecl>(*DclIt); 862 if (VD->isThisDeclarationADefinition()) { 863 if (VD->isStaticLocal()) { 864 SemaRef.Diag(VD->getLocation(), 865 diag::err_constexpr_local_var_static) 866 << isa<CXXConstructorDecl>(Dcl) 867 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 868 return false; 869 } 870 if (!VD->getType()->isDependentType() && 871 SemaRef.RequireLiteralType( 872 VD->getLocation(), VD->getType(), 873 diag::err_constexpr_local_var_non_literal_type, 874 isa<CXXConstructorDecl>(Dcl))) 875 return false; 876 if (!VD->hasInit()) { 877 SemaRef.Diag(VD->getLocation(), 878 diag::err_constexpr_local_var_no_init) 879 << isa<CXXConstructorDecl>(Dcl); 880 return false; 881 } 882 } 883 SemaRef.Diag(VD->getLocation(), 884 SemaRef.getLangOpts().CPlusPlus1y 885 ? diag::warn_cxx11_compat_constexpr_local_var 886 : diag::ext_constexpr_local_var) 887 << isa<CXXConstructorDecl>(Dcl); 888 continue; 889 } 890 891 case Decl::NamespaceAlias: 892 case Decl::Function: 893 // These are disallowed in C++11 and permitted in C++1y. Allow them 894 // everywhere as an extension. 895 if (!Cxx1yLoc.isValid()) 896 Cxx1yLoc = DS->getLocStart(); 897 continue; 898 899 default: 900 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 901 << isa<CXXConstructorDecl>(Dcl); 902 return false; 903 } 904 } 905 906 return true; 907} 908 909/// Check that the given field is initialized within a constexpr constructor. 910/// 911/// \param Dcl The constexpr constructor being checked. 912/// \param Field The field being checked. This may be a member of an anonymous 913/// struct or union nested within the class being checked. 914/// \param Inits All declarations, including anonymous struct/union members and 915/// indirect members, for which any initialization was provided. 916/// \param Diagnosed Set to true if an error is produced. 917static void CheckConstexprCtorInitializer(Sema &SemaRef, 918 const FunctionDecl *Dcl, 919 FieldDecl *Field, 920 llvm::SmallSet<Decl*, 16> &Inits, 921 bool &Diagnosed) { 922 if (Field->isInvalidDecl()) 923 return; 924 925 if (Field->isUnnamedBitfield()) 926 return; 927 928 if (Field->isAnonymousStructOrUnion() && 929 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 930 return; 931 932 if (!Inits.count(Field)) { 933 if (!Diagnosed) { 934 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 935 Diagnosed = true; 936 } 937 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 938 } else if (Field->isAnonymousStructOrUnion()) { 939 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 940 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 941 I != E; ++I) 942 // If an anonymous union contains an anonymous struct of which any member 943 // is initialized, all members must be initialized. 944 if (!RD->isUnion() || Inits.count(*I)) 945 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 946 } 947} 948 949/// Check the provided statement is allowed in a constexpr function 950/// definition. 951static bool 952CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 953 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts, 954 SourceLocation &Cxx1yLoc) { 955 // - its function-body shall be [...] a compound-statement that contains only 956 switch (S->getStmtClass()) { 957 case Stmt::NullStmtClass: 958 // - null statements, 959 return true; 960 961 case Stmt::DeclStmtClass: 962 // - static_assert-declarations 963 // - using-declarations, 964 // - using-directives, 965 // - typedef declarations and alias-declarations that do not define 966 // classes or enumerations, 967 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 968 return false; 969 return true; 970 971 case Stmt::ReturnStmtClass: 972 // - and exactly one return statement; 973 if (isa<CXXConstructorDecl>(Dcl)) { 974 // C++1y allows return statements in constexpr constructors. 975 if (!Cxx1yLoc.isValid()) 976 Cxx1yLoc = S->getLocStart(); 977 return true; 978 } 979 980 ReturnStmts.push_back(S->getLocStart()); 981 return true; 982 983 case Stmt::CompoundStmtClass: { 984 // C++1y allows compound-statements. 985 if (!Cxx1yLoc.isValid()) 986 Cxx1yLoc = S->getLocStart(); 987 988 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 989 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 990 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 991 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 992 Cxx1yLoc)) 993 return false; 994 } 995 return true; 996 } 997 998 case Stmt::AttributedStmtClass: 999 if (!Cxx1yLoc.isValid()) 1000 Cxx1yLoc = S->getLocStart(); 1001 return true; 1002 1003 case Stmt::IfStmtClass: { 1004 // C++1y allows if-statements. 1005 if (!Cxx1yLoc.isValid()) 1006 Cxx1yLoc = S->getLocStart(); 1007 1008 IfStmt *If = cast<IfStmt>(S); 1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1010 Cxx1yLoc)) 1011 return false; 1012 if (If->getElse() && 1013 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1014 Cxx1yLoc)) 1015 return false; 1016 return true; 1017 } 1018 1019 case Stmt::WhileStmtClass: 1020 case Stmt::DoStmtClass: 1021 case Stmt::ForStmtClass: 1022 case Stmt::CXXForRangeStmtClass: 1023 case Stmt::ContinueStmtClass: 1024 // C++1y allows all of these. We don't allow them as extensions in C++11, 1025 // because they don't make sense without variable mutation. 1026 if (!SemaRef.getLangOpts().CPlusPlus1y) 1027 break; 1028 if (!Cxx1yLoc.isValid()) 1029 Cxx1yLoc = S->getLocStart(); 1030 for (Stmt::child_range Children = S->children(); Children; ++Children) 1031 if (*Children && 1032 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1033 Cxx1yLoc)) 1034 return false; 1035 return true; 1036 1037 case Stmt::SwitchStmtClass: 1038 case Stmt::CaseStmtClass: 1039 case Stmt::DefaultStmtClass: 1040 case Stmt::BreakStmtClass: 1041 // C++1y allows switch-statements, and since they don't need variable 1042 // mutation, we can reasonably allow them in C++11 as an extension. 1043 if (!Cxx1yLoc.isValid()) 1044 Cxx1yLoc = S->getLocStart(); 1045 for (Stmt::child_range Children = S->children(); Children; ++Children) 1046 if (*Children && 1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1048 Cxx1yLoc)) 1049 return false; 1050 return true; 1051 1052 default: 1053 if (!isa<Expr>(S)) 1054 break; 1055 1056 // C++1y allows expression-statements. 1057 if (!Cxx1yLoc.isValid()) 1058 Cxx1yLoc = S->getLocStart(); 1059 return true; 1060 } 1061 1062 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1063 << isa<CXXConstructorDecl>(Dcl); 1064 return false; 1065} 1066 1067/// Check the body for the given constexpr function declaration only contains 1068/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1069/// 1070/// \return true if the body is OK, false if we have diagnosed a problem. 1071bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1072 if (isa<CXXTryStmt>(Body)) { 1073 // C++11 [dcl.constexpr]p3: 1074 // The definition of a constexpr function shall satisfy the following 1075 // constraints: [...] 1076 // - its function-body shall be = delete, = default, or a 1077 // compound-statement 1078 // 1079 // C++11 [dcl.constexpr]p4: 1080 // In the definition of a constexpr constructor, [...] 1081 // - its function-body shall not be a function-try-block; 1082 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1083 << isa<CXXConstructorDecl>(Dcl); 1084 return false; 1085 } 1086 1087 SmallVector<SourceLocation, 4> ReturnStmts; 1088 1089 // - its function-body shall be [...] a compound-statement that contains only 1090 // [... list of cases ...] 1091 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1092 SourceLocation Cxx1yLoc; 1093 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1094 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1095 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1096 return false; 1097 } 1098 1099 if (Cxx1yLoc.isValid()) 1100 Diag(Cxx1yLoc, 1101 getLangOpts().CPlusPlus1y 1102 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1103 : diag::ext_constexpr_body_invalid_stmt) 1104 << isa<CXXConstructorDecl>(Dcl); 1105 1106 if (const CXXConstructorDecl *Constructor 1107 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1108 const CXXRecordDecl *RD = Constructor->getParent(); 1109 // DR1359: 1110 // - every non-variant non-static data member and base class sub-object 1111 // shall be initialized; 1112 // - if the class is a non-empty union, or for each non-empty anonymous 1113 // union member of a non-union class, exactly one non-static data member 1114 // shall be initialized; 1115 if (RD->isUnion()) { 1116 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1117 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1118 return false; 1119 } 1120 } else if (!Constructor->isDependentContext() && 1121 !Constructor->isDelegatingConstructor()) { 1122 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1123 1124 // Skip detailed checking if we have enough initializers, and we would 1125 // allow at most one initializer per member. 1126 bool AnyAnonStructUnionMembers = false; 1127 unsigned Fields = 0; 1128 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1129 E = RD->field_end(); I != E; ++I, ++Fields) { 1130 if (I->isAnonymousStructOrUnion()) { 1131 AnyAnonStructUnionMembers = true; 1132 break; 1133 } 1134 } 1135 if (AnyAnonStructUnionMembers || 1136 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1137 // Check initialization of non-static data members. Base classes are 1138 // always initialized so do not need to be checked. Dependent bases 1139 // might not have initializers in the member initializer list. 1140 llvm::SmallSet<Decl*, 16> Inits; 1141 for (CXXConstructorDecl::init_const_iterator 1142 I = Constructor->init_begin(), E = Constructor->init_end(); 1143 I != E; ++I) { 1144 if (FieldDecl *FD = (*I)->getMember()) 1145 Inits.insert(FD); 1146 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1147 Inits.insert(ID->chain_begin(), ID->chain_end()); 1148 } 1149 1150 bool Diagnosed = false; 1151 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1152 E = RD->field_end(); I != E; ++I) 1153 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1154 if (Diagnosed) 1155 return false; 1156 } 1157 } 1158 } else { 1159 if (ReturnStmts.empty()) { 1160 // C++1y doesn't require constexpr functions to contain a 'return' 1161 // statement. We still do, unless the return type is void, because 1162 // otherwise if there's no return statement, the function cannot 1163 // be used in a core constant expression. 1164 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1165 Diag(Dcl->getLocation(), 1166 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1167 : diag::err_constexpr_body_no_return); 1168 return OK; 1169 } 1170 if (ReturnStmts.size() > 1) { 1171 Diag(ReturnStmts.back(), 1172 getLangOpts().CPlusPlus1y 1173 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1174 : diag::ext_constexpr_body_multiple_return); 1175 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1176 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1177 } 1178 } 1179 1180 // C++11 [dcl.constexpr]p5: 1181 // if no function argument values exist such that the function invocation 1182 // substitution would produce a constant expression, the program is 1183 // ill-formed; no diagnostic required. 1184 // C++11 [dcl.constexpr]p3: 1185 // - every constructor call and implicit conversion used in initializing the 1186 // return value shall be one of those allowed in a constant expression. 1187 // C++11 [dcl.constexpr]p4: 1188 // - every constructor involved in initializing non-static data members and 1189 // base class sub-objects shall be a constexpr constructor. 1190 SmallVector<PartialDiagnosticAt, 8> Diags; 1191 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1192 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1193 << isa<CXXConstructorDecl>(Dcl); 1194 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1195 Diag(Diags[I].first, Diags[I].second); 1196 // Don't return false here: we allow this for compatibility in 1197 // system headers. 1198 } 1199 1200 return true; 1201} 1202 1203/// isCurrentClassName - Determine whether the identifier II is the 1204/// name of the class type currently being defined. In the case of 1205/// nested classes, this will only return true if II is the name of 1206/// the innermost class. 1207bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1208 const CXXScopeSpec *SS) { 1209 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1210 1211 CXXRecordDecl *CurDecl; 1212 if (SS && SS->isSet() && !SS->isInvalid()) { 1213 DeclContext *DC = computeDeclContext(*SS, true); 1214 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1215 } else 1216 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1217 1218 if (CurDecl && CurDecl->getIdentifier()) 1219 return &II == CurDecl->getIdentifier(); 1220 else 1221 return false; 1222} 1223 1224/// \brief Determine whether the given class is a base class of the given 1225/// class, including looking at dependent bases. 1226static bool findCircularInheritance(const CXXRecordDecl *Class, 1227 const CXXRecordDecl *Current) { 1228 SmallVector<const CXXRecordDecl*, 8> Queue; 1229 1230 Class = Class->getCanonicalDecl(); 1231 while (true) { 1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1233 E = Current->bases_end(); 1234 I != E; ++I) { 1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1236 if (!Base) 1237 continue; 1238 1239 Base = Base->getDefinition(); 1240 if (!Base) 1241 continue; 1242 1243 if (Base->getCanonicalDecl() == Class) 1244 return true; 1245 1246 Queue.push_back(Base); 1247 } 1248 1249 if (Queue.empty()) 1250 return false; 1251 1252 Current = Queue.back(); 1253 Queue.pop_back(); 1254 } 1255 1256 return false; 1257} 1258 1259/// \brief Check the validity of a C++ base class specifier. 1260/// 1261/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1262/// and returns NULL otherwise. 1263CXXBaseSpecifier * 1264Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1265 SourceRange SpecifierRange, 1266 bool Virtual, AccessSpecifier Access, 1267 TypeSourceInfo *TInfo, 1268 SourceLocation EllipsisLoc) { 1269 QualType BaseType = TInfo->getType(); 1270 1271 // C++ [class.union]p1: 1272 // A union shall not have base classes. 1273 if (Class->isUnion()) { 1274 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1275 << SpecifierRange; 1276 return 0; 1277 } 1278 1279 if (EllipsisLoc.isValid() && 1280 !TInfo->getType()->containsUnexpandedParameterPack()) { 1281 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1282 << TInfo->getTypeLoc().getSourceRange(); 1283 EllipsisLoc = SourceLocation(); 1284 } 1285 1286 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1287 1288 if (BaseType->isDependentType()) { 1289 // Make sure that we don't have circular inheritance among our dependent 1290 // bases. For non-dependent bases, the check for completeness below handles 1291 // this. 1292 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1293 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1294 ((BaseDecl = BaseDecl->getDefinition()) && 1295 findCircularInheritance(Class, BaseDecl))) { 1296 Diag(BaseLoc, diag::err_circular_inheritance) 1297 << BaseType << Context.getTypeDeclType(Class); 1298 1299 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1300 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1301 << BaseType; 1302 1303 return 0; 1304 } 1305 } 1306 1307 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1308 Class->getTagKind() == TTK_Class, 1309 Access, TInfo, EllipsisLoc); 1310 } 1311 1312 // Base specifiers must be record types. 1313 if (!BaseType->isRecordType()) { 1314 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1315 return 0; 1316 } 1317 1318 // C++ [class.union]p1: 1319 // A union shall not be used as a base class. 1320 if (BaseType->isUnionType()) { 1321 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1322 return 0; 1323 } 1324 1325 // C++ [class.derived]p2: 1326 // The class-name in a base-specifier shall not be an incompletely 1327 // defined class. 1328 if (RequireCompleteType(BaseLoc, BaseType, 1329 diag::err_incomplete_base_class, SpecifierRange)) { 1330 Class->setInvalidDecl(); 1331 return 0; 1332 } 1333 1334 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1335 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1336 assert(BaseDecl && "Record type has no declaration"); 1337 BaseDecl = BaseDecl->getDefinition(); 1338 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1339 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1340 assert(CXXBaseDecl && "Base type is not a C++ type"); 1341 1342 // C++ [class]p3: 1343 // If a class is marked final and it appears as a base-type-specifier in 1344 // base-clause, the program is ill-formed. 1345 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1346 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1347 << CXXBaseDecl->getDeclName(); 1348 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1349 << CXXBaseDecl->getDeclName(); 1350 return 0; 1351 } 1352 1353 if (BaseDecl->isInvalidDecl()) 1354 Class->setInvalidDecl(); 1355 1356 // Create the base specifier. 1357 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1358 Class->getTagKind() == TTK_Class, 1359 Access, TInfo, EllipsisLoc); 1360} 1361 1362/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1363/// one entry in the base class list of a class specifier, for 1364/// example: 1365/// class foo : public bar, virtual private baz { 1366/// 'public bar' and 'virtual private baz' are each base-specifiers. 1367BaseResult 1368Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1369 ParsedAttributes &Attributes, 1370 bool Virtual, AccessSpecifier Access, 1371 ParsedType basetype, SourceLocation BaseLoc, 1372 SourceLocation EllipsisLoc) { 1373 if (!classdecl) 1374 return true; 1375 1376 AdjustDeclIfTemplate(classdecl); 1377 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1378 if (!Class) 1379 return true; 1380 1381 // We do not support any C++11 attributes on base-specifiers yet. 1382 // Diagnose any attributes we see. 1383 if (!Attributes.empty()) { 1384 for (AttributeList *Attr = Attributes.getList(); Attr; 1385 Attr = Attr->getNext()) { 1386 if (Attr->isInvalid() || 1387 Attr->getKind() == AttributeList::IgnoredAttribute) 1388 continue; 1389 Diag(Attr->getLoc(), 1390 Attr->getKind() == AttributeList::UnknownAttribute 1391 ? diag::warn_unknown_attribute_ignored 1392 : diag::err_base_specifier_attribute) 1393 << Attr->getName(); 1394 } 1395 } 1396 1397 TypeSourceInfo *TInfo = 0; 1398 GetTypeFromParser(basetype, &TInfo); 1399 1400 if (EllipsisLoc.isInvalid() && 1401 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1402 UPPC_BaseType)) 1403 return true; 1404 1405 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1406 Virtual, Access, TInfo, 1407 EllipsisLoc)) 1408 return BaseSpec; 1409 else 1410 Class->setInvalidDecl(); 1411 1412 return true; 1413} 1414 1415/// \brief Performs the actual work of attaching the given base class 1416/// specifiers to a C++ class. 1417bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1418 unsigned NumBases) { 1419 if (NumBases == 0) 1420 return false; 1421 1422 // Used to keep track of which base types we have already seen, so 1423 // that we can properly diagnose redundant direct base types. Note 1424 // that the key is always the unqualified canonical type of the base 1425 // class. 1426 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1427 1428 // Copy non-redundant base specifiers into permanent storage. 1429 unsigned NumGoodBases = 0; 1430 bool Invalid = false; 1431 for (unsigned idx = 0; idx < NumBases; ++idx) { 1432 QualType NewBaseType 1433 = Context.getCanonicalType(Bases[idx]->getType()); 1434 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1435 1436 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1437 if (KnownBase) { 1438 // C++ [class.mi]p3: 1439 // A class shall not be specified as a direct base class of a 1440 // derived class more than once. 1441 Diag(Bases[idx]->getLocStart(), 1442 diag::err_duplicate_base_class) 1443 << KnownBase->getType() 1444 << Bases[idx]->getSourceRange(); 1445 1446 // Delete the duplicate base class specifier; we're going to 1447 // overwrite its pointer later. 1448 Context.Deallocate(Bases[idx]); 1449 1450 Invalid = true; 1451 } else { 1452 // Okay, add this new base class. 1453 KnownBase = Bases[idx]; 1454 Bases[NumGoodBases++] = Bases[idx]; 1455 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1456 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1457 if (Class->isInterface() && 1458 (!RD->isInterface() || 1459 KnownBase->getAccessSpecifier() != AS_public)) { 1460 // The Microsoft extension __interface does not permit bases that 1461 // are not themselves public interfaces. 1462 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1463 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1464 << RD->getSourceRange(); 1465 Invalid = true; 1466 } 1467 if (RD->hasAttr<WeakAttr>()) 1468 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1469 } 1470 } 1471 } 1472 1473 // Attach the remaining base class specifiers to the derived class. 1474 Class->setBases(Bases, NumGoodBases); 1475 1476 // Delete the remaining (good) base class specifiers, since their 1477 // data has been copied into the CXXRecordDecl. 1478 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1479 Context.Deallocate(Bases[idx]); 1480 1481 return Invalid; 1482} 1483 1484/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1485/// class, after checking whether there are any duplicate base 1486/// classes. 1487void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1488 unsigned NumBases) { 1489 if (!ClassDecl || !Bases || !NumBases) 1490 return; 1491 1492 AdjustDeclIfTemplate(ClassDecl); 1493 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1494} 1495 1496/// \brief Determine whether the type \p Derived is a C++ class that is 1497/// derived from the type \p Base. 1498bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1499 if (!getLangOpts().CPlusPlus) 1500 return false; 1501 1502 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1503 if (!DerivedRD) 1504 return false; 1505 1506 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1507 if (!BaseRD) 1508 return false; 1509 1510 // If either the base or the derived type is invalid, don't try to 1511 // check whether one is derived from the other. 1512 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1513 return false; 1514 1515 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1516 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1517} 1518 1519/// \brief Determine whether the type \p Derived is a C++ class that is 1520/// derived from the type \p Base. 1521bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1522 if (!getLangOpts().CPlusPlus) 1523 return false; 1524 1525 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1526 if (!DerivedRD) 1527 return false; 1528 1529 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1530 if (!BaseRD) 1531 return false; 1532 1533 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1534} 1535 1536void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1537 CXXCastPath &BasePathArray) { 1538 assert(BasePathArray.empty() && "Base path array must be empty!"); 1539 assert(Paths.isRecordingPaths() && "Must record paths!"); 1540 1541 const CXXBasePath &Path = Paths.front(); 1542 1543 // We first go backward and check if we have a virtual base. 1544 // FIXME: It would be better if CXXBasePath had the base specifier for 1545 // the nearest virtual base. 1546 unsigned Start = 0; 1547 for (unsigned I = Path.size(); I != 0; --I) { 1548 if (Path[I - 1].Base->isVirtual()) { 1549 Start = I - 1; 1550 break; 1551 } 1552 } 1553 1554 // Now add all bases. 1555 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1556 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1557} 1558 1559/// \brief Determine whether the given base path includes a virtual 1560/// base class. 1561bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1562 for (CXXCastPath::const_iterator B = BasePath.begin(), 1563 BEnd = BasePath.end(); 1564 B != BEnd; ++B) 1565 if ((*B)->isVirtual()) 1566 return true; 1567 1568 return false; 1569} 1570 1571/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1572/// conversion (where Derived and Base are class types) is 1573/// well-formed, meaning that the conversion is unambiguous (and 1574/// that all of the base classes are accessible). Returns true 1575/// and emits a diagnostic if the code is ill-formed, returns false 1576/// otherwise. Loc is the location where this routine should point to 1577/// if there is an error, and Range is the source range to highlight 1578/// if there is an error. 1579bool 1580Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1581 unsigned InaccessibleBaseID, 1582 unsigned AmbigiousBaseConvID, 1583 SourceLocation Loc, SourceRange Range, 1584 DeclarationName Name, 1585 CXXCastPath *BasePath) { 1586 // First, determine whether the path from Derived to Base is 1587 // ambiguous. This is slightly more expensive than checking whether 1588 // the Derived to Base conversion exists, because here we need to 1589 // explore multiple paths to determine if there is an ambiguity. 1590 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1591 /*DetectVirtual=*/false); 1592 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1593 assert(DerivationOkay && 1594 "Can only be used with a derived-to-base conversion"); 1595 (void)DerivationOkay; 1596 1597 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1598 if (InaccessibleBaseID) { 1599 // Check that the base class can be accessed. 1600 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1601 InaccessibleBaseID)) { 1602 case AR_inaccessible: 1603 return true; 1604 case AR_accessible: 1605 case AR_dependent: 1606 case AR_delayed: 1607 break; 1608 } 1609 } 1610 1611 // Build a base path if necessary. 1612 if (BasePath) 1613 BuildBasePathArray(Paths, *BasePath); 1614 return false; 1615 } 1616 1617 if (AmbigiousBaseConvID) { 1618 // We know that the derived-to-base conversion is ambiguous, and 1619 // we're going to produce a diagnostic. Perform the derived-to-base 1620 // search just one more time to compute all of the possible paths so 1621 // that we can print them out. This is more expensive than any of 1622 // the previous derived-to-base checks we've done, but at this point 1623 // performance isn't as much of an issue. 1624 Paths.clear(); 1625 Paths.setRecordingPaths(true); 1626 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1627 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1628 (void)StillOkay; 1629 1630 // Build up a textual representation of the ambiguous paths, e.g., 1631 // D -> B -> A, that will be used to illustrate the ambiguous 1632 // conversions in the diagnostic. We only print one of the paths 1633 // to each base class subobject. 1634 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1635 1636 Diag(Loc, AmbigiousBaseConvID) 1637 << Derived << Base << PathDisplayStr << Range << Name; 1638 } 1639 return true; 1640} 1641 1642bool 1643Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1644 SourceLocation Loc, SourceRange Range, 1645 CXXCastPath *BasePath, 1646 bool IgnoreAccess) { 1647 return CheckDerivedToBaseConversion(Derived, Base, 1648 IgnoreAccess ? 0 1649 : diag::err_upcast_to_inaccessible_base, 1650 diag::err_ambiguous_derived_to_base_conv, 1651 Loc, Range, DeclarationName(), 1652 BasePath); 1653} 1654 1655 1656/// @brief Builds a string representing ambiguous paths from a 1657/// specific derived class to different subobjects of the same base 1658/// class. 1659/// 1660/// This function builds a string that can be used in error messages 1661/// to show the different paths that one can take through the 1662/// inheritance hierarchy to go from the derived class to different 1663/// subobjects of a base class. The result looks something like this: 1664/// @code 1665/// struct D -> struct B -> struct A 1666/// struct D -> struct C -> struct A 1667/// @endcode 1668std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1669 std::string PathDisplayStr; 1670 std::set<unsigned> DisplayedPaths; 1671 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1672 Path != Paths.end(); ++Path) { 1673 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1674 // We haven't displayed a path to this particular base 1675 // class subobject yet. 1676 PathDisplayStr += "\n "; 1677 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1678 for (CXXBasePath::const_iterator Element = Path->begin(); 1679 Element != Path->end(); ++Element) 1680 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1681 } 1682 } 1683 1684 return PathDisplayStr; 1685} 1686 1687//===----------------------------------------------------------------------===// 1688// C++ class member Handling 1689//===----------------------------------------------------------------------===// 1690 1691/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1692bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1693 SourceLocation ASLoc, 1694 SourceLocation ColonLoc, 1695 AttributeList *Attrs) { 1696 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1697 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1698 ASLoc, ColonLoc); 1699 CurContext->addHiddenDecl(ASDecl); 1700 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1701} 1702 1703/// CheckOverrideControl - Check C++11 override control semantics. 1704void Sema::CheckOverrideControl(Decl *D) { 1705 if (D->isInvalidDecl()) 1706 return; 1707 1708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1709 1710 // Do we know which functions this declaration might be overriding? 1711 bool OverridesAreKnown = !MD || 1712 (!MD->getParent()->hasAnyDependentBases() && 1713 !MD->getType()->isDependentType()); 1714 1715 if (!MD || !MD->isVirtual()) { 1716 if (OverridesAreKnown) { 1717 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1718 Diag(OA->getLocation(), 1719 diag::override_keyword_only_allowed_on_virtual_member_functions) 1720 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1721 D->dropAttr<OverrideAttr>(); 1722 } 1723 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1724 Diag(FA->getLocation(), 1725 diag::override_keyword_only_allowed_on_virtual_member_functions) 1726 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1727 D->dropAttr<FinalAttr>(); 1728 } 1729 } 1730 return; 1731 } 1732 1733 if (!OverridesAreKnown) 1734 return; 1735 1736 // C++11 [class.virtual]p5: 1737 // If a virtual function is marked with the virt-specifier override and 1738 // does not override a member function of a base class, the program is 1739 // ill-formed. 1740 bool HasOverriddenMethods = 1741 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1742 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1743 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1744 << MD->getDeclName(); 1745} 1746 1747/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1748/// function overrides a virtual member function marked 'final', according to 1749/// C++11 [class.virtual]p4. 1750bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1751 const CXXMethodDecl *Old) { 1752 if (!Old->hasAttr<FinalAttr>()) 1753 return false; 1754 1755 Diag(New->getLocation(), diag::err_final_function_overridden) 1756 << New->getDeclName(); 1757 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1758 return true; 1759} 1760 1761static bool InitializationHasSideEffects(const FieldDecl &FD) { 1762 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1763 // FIXME: Destruction of ObjC lifetime types has side-effects. 1764 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1765 return !RD->isCompleteDefinition() || 1766 !RD->hasTrivialDefaultConstructor() || 1767 !RD->hasTrivialDestructor(); 1768 return false; 1769} 1770 1771static AttributeList *getMSPropertyAttr(AttributeList *list) { 1772 for (AttributeList* it = list; it != 0; it = it->getNext()) 1773 if (it->isDeclspecPropertyAttribute()) 1774 return it; 1775 return 0; 1776} 1777 1778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1780/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1781/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1782/// present (but parsing it has been deferred). 1783NamedDecl * 1784Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1785 MultiTemplateParamsArg TemplateParameterLists, 1786 Expr *BW, const VirtSpecifiers &VS, 1787 InClassInitStyle InitStyle) { 1788 const DeclSpec &DS = D.getDeclSpec(); 1789 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1790 DeclarationName Name = NameInfo.getName(); 1791 SourceLocation Loc = NameInfo.getLoc(); 1792 1793 // For anonymous bitfields, the location should point to the type. 1794 if (Loc.isInvalid()) 1795 Loc = D.getLocStart(); 1796 1797 Expr *BitWidth = static_cast<Expr*>(BW); 1798 1799 assert(isa<CXXRecordDecl>(CurContext)); 1800 assert(!DS.isFriendSpecified()); 1801 1802 bool isFunc = D.isDeclarationOfFunction(); 1803 1804 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1805 // The Microsoft extension __interface only permits public member functions 1806 // and prohibits constructors, destructors, operators, non-public member 1807 // functions, static methods and data members. 1808 unsigned InvalidDecl; 1809 bool ShowDeclName = true; 1810 if (!isFunc) 1811 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1812 else if (AS != AS_public) 1813 InvalidDecl = 2; 1814 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1815 InvalidDecl = 3; 1816 else switch (Name.getNameKind()) { 1817 case DeclarationName::CXXConstructorName: 1818 InvalidDecl = 4; 1819 ShowDeclName = false; 1820 break; 1821 1822 case DeclarationName::CXXDestructorName: 1823 InvalidDecl = 5; 1824 ShowDeclName = false; 1825 break; 1826 1827 case DeclarationName::CXXOperatorName: 1828 case DeclarationName::CXXConversionFunctionName: 1829 InvalidDecl = 6; 1830 break; 1831 1832 default: 1833 InvalidDecl = 0; 1834 break; 1835 } 1836 1837 if (InvalidDecl) { 1838 if (ShowDeclName) 1839 Diag(Loc, diag::err_invalid_member_in_interface) 1840 << (InvalidDecl-1) << Name; 1841 else 1842 Diag(Loc, diag::err_invalid_member_in_interface) 1843 << (InvalidDecl-1) << ""; 1844 return 0; 1845 } 1846 } 1847 1848 // C++ 9.2p6: A member shall not be declared to have automatic storage 1849 // duration (auto, register) or with the extern storage-class-specifier. 1850 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1851 // data members and cannot be applied to names declared const or static, 1852 // and cannot be applied to reference members. 1853 switch (DS.getStorageClassSpec()) { 1854 case DeclSpec::SCS_unspecified: 1855 case DeclSpec::SCS_typedef: 1856 case DeclSpec::SCS_static: 1857 break; 1858 case DeclSpec::SCS_mutable: 1859 if (isFunc) { 1860 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1861 1862 // FIXME: It would be nicer if the keyword was ignored only for this 1863 // declarator. Otherwise we could get follow-up errors. 1864 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1865 } 1866 break; 1867 default: 1868 Diag(DS.getStorageClassSpecLoc(), 1869 diag::err_storageclass_invalid_for_member); 1870 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1871 break; 1872 } 1873 1874 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1875 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1876 !isFunc); 1877 1878 if (DS.isConstexprSpecified() && isInstField) { 1879 SemaDiagnosticBuilder B = 1880 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1881 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1882 if (InitStyle == ICIS_NoInit) { 1883 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1884 D.getMutableDeclSpec().ClearConstexprSpec(); 1885 const char *PrevSpec; 1886 unsigned DiagID; 1887 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1888 PrevSpec, DiagID, getLangOpts()); 1889 (void)Failed; 1890 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1891 } else { 1892 B << 1; 1893 const char *PrevSpec; 1894 unsigned DiagID; 1895 if (D.getMutableDeclSpec().SetStorageClassSpec( 1896 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1897 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1898 "This is the only DeclSpec that should fail to be applied"); 1899 B << 1; 1900 } else { 1901 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1902 isInstField = false; 1903 } 1904 } 1905 } 1906 1907 NamedDecl *Member; 1908 if (isInstField) { 1909 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1910 1911 // Data members must have identifiers for names. 1912 if (!Name.isIdentifier()) { 1913 Diag(Loc, diag::err_bad_variable_name) 1914 << Name; 1915 return 0; 1916 } 1917 1918 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1919 1920 // Member field could not be with "template" keyword. 1921 // So TemplateParameterLists should be empty in this case. 1922 if (TemplateParameterLists.size()) { 1923 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1924 if (TemplateParams->size()) { 1925 // There is no such thing as a member field template. 1926 Diag(D.getIdentifierLoc(), diag::err_template_member) 1927 << II 1928 << SourceRange(TemplateParams->getTemplateLoc(), 1929 TemplateParams->getRAngleLoc()); 1930 } else { 1931 // There is an extraneous 'template<>' for this member. 1932 Diag(TemplateParams->getTemplateLoc(), 1933 diag::err_template_member_noparams) 1934 << II 1935 << SourceRange(TemplateParams->getTemplateLoc(), 1936 TemplateParams->getRAngleLoc()); 1937 } 1938 return 0; 1939 } 1940 1941 if (SS.isSet() && !SS.isInvalid()) { 1942 // The user provided a superfluous scope specifier inside a class 1943 // definition: 1944 // 1945 // class X { 1946 // int X::member; 1947 // }; 1948 if (DeclContext *DC = computeDeclContext(SS, false)) 1949 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1950 else 1951 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1952 << Name << SS.getRange(); 1953 1954 SS.clear(); 1955 } 1956 1957 AttributeList *MSPropertyAttr = 1958 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 1959 if (MSPropertyAttr) { 1960 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1961 BitWidth, InitStyle, AS, MSPropertyAttr); 1962 if (!Member) 1963 return 0; 1964 isInstField = false; 1965 } else { 1966 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1967 BitWidth, InitStyle, AS); 1968 assert(Member && "HandleField never returns null"); 1969 } 1970 } else { 1971 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1972 1973 Member = HandleDeclarator(S, D, TemplateParameterLists); 1974 if (!Member) 1975 return 0; 1976 1977 // Non-instance-fields can't have a bitfield. 1978 if (BitWidth) { 1979 if (Member->isInvalidDecl()) { 1980 // don't emit another diagnostic. 1981 } else if (isa<VarDecl>(Member)) { 1982 // C++ 9.6p3: A bit-field shall not be a static member. 1983 // "static member 'A' cannot be a bit-field" 1984 Diag(Loc, diag::err_static_not_bitfield) 1985 << Name << BitWidth->getSourceRange(); 1986 } else if (isa<TypedefDecl>(Member)) { 1987 // "typedef member 'x' cannot be a bit-field" 1988 Diag(Loc, diag::err_typedef_not_bitfield) 1989 << Name << BitWidth->getSourceRange(); 1990 } else { 1991 // A function typedef ("typedef int f(); f a;"). 1992 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1993 Diag(Loc, diag::err_not_integral_type_bitfield) 1994 << Name << cast<ValueDecl>(Member)->getType() 1995 << BitWidth->getSourceRange(); 1996 } 1997 1998 BitWidth = 0; 1999 Member->setInvalidDecl(); 2000 } 2001 2002 Member->setAccess(AS); 2003 2004 // If we have declared a member function template, set the access of the 2005 // templated declaration as well. 2006 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2007 FunTmpl->getTemplatedDecl()->setAccess(AS); 2008 } 2009 2010 if (VS.isOverrideSpecified()) 2011 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 2012 if (VS.isFinalSpecified()) 2013 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 2014 2015 if (VS.getLastLocation().isValid()) { 2016 // Update the end location of a method that has a virt-specifiers. 2017 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2018 MD->setRangeEnd(VS.getLastLocation()); 2019 } 2020 2021 CheckOverrideControl(Member); 2022 2023 assert((Name || isInstField) && "No identifier for non-field ?"); 2024 2025 if (isInstField) { 2026 FieldDecl *FD = cast<FieldDecl>(Member); 2027 FieldCollector->Add(FD); 2028 2029 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2030 FD->getLocation()) 2031 != DiagnosticsEngine::Ignored) { 2032 // Remember all explicit private FieldDecls that have a name, no side 2033 // effects and are not part of a dependent type declaration. 2034 if (!FD->isImplicit() && FD->getDeclName() && 2035 FD->getAccess() == AS_private && 2036 !FD->hasAttr<UnusedAttr>() && 2037 !FD->getParent()->isDependentContext() && 2038 !InitializationHasSideEffects(*FD)) 2039 UnusedPrivateFields.insert(FD); 2040 } 2041 } 2042 2043 return Member; 2044} 2045 2046namespace { 2047 class UninitializedFieldVisitor 2048 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2049 Sema &S; 2050 ValueDecl *VD; 2051 public: 2052 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2053 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2054 S(S) { 2055 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2056 this->VD = IFD->getAnonField(); 2057 else 2058 this->VD = VD; 2059 } 2060 2061 void HandleExpr(Expr *E) { 2062 if (!E) return; 2063 2064 // Expressions like x(x) sometimes lack the surrounding expressions 2065 // but need to be checked anyways. 2066 HandleValue(E); 2067 Visit(E); 2068 } 2069 2070 void HandleValue(Expr *E) { 2071 E = E->IgnoreParens(); 2072 2073 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2074 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2075 return; 2076 2077 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2078 // or union. 2079 MemberExpr *FieldME = ME; 2080 2081 Expr *Base = E; 2082 while (isa<MemberExpr>(Base)) { 2083 ME = cast<MemberExpr>(Base); 2084 2085 if (isa<VarDecl>(ME->getMemberDecl())) 2086 return; 2087 2088 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2089 if (!FD->isAnonymousStructOrUnion()) 2090 FieldME = ME; 2091 2092 Base = ME->getBase(); 2093 } 2094 2095 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2096 unsigned diag = VD->getType()->isReferenceType() 2097 ? diag::warn_reference_field_is_uninit 2098 : diag::warn_field_is_uninit; 2099 S.Diag(FieldME->getExprLoc(), diag) << VD; 2100 } 2101 return; 2102 } 2103 2104 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2105 HandleValue(CO->getTrueExpr()); 2106 HandleValue(CO->getFalseExpr()); 2107 return; 2108 } 2109 2110 if (BinaryConditionalOperator *BCO = 2111 dyn_cast<BinaryConditionalOperator>(E)) { 2112 HandleValue(BCO->getCommon()); 2113 HandleValue(BCO->getFalseExpr()); 2114 return; 2115 } 2116 2117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2118 switch (BO->getOpcode()) { 2119 default: 2120 return; 2121 case(BO_PtrMemD): 2122 case(BO_PtrMemI): 2123 HandleValue(BO->getLHS()); 2124 return; 2125 case(BO_Comma): 2126 HandleValue(BO->getRHS()); 2127 return; 2128 } 2129 } 2130 } 2131 2132 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2133 if (E->getCastKind() == CK_LValueToRValue) 2134 HandleValue(E->getSubExpr()); 2135 2136 Inherited::VisitImplicitCastExpr(E); 2137 } 2138 2139 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2140 Expr *Callee = E->getCallee(); 2141 if (isa<MemberExpr>(Callee)) 2142 HandleValue(Callee); 2143 2144 Inherited::VisitCXXMemberCallExpr(E); 2145 } 2146 }; 2147 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2148 ValueDecl *VD) { 2149 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2150 } 2151} // namespace 2152 2153/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2154/// in-class initializer for a non-static C++ class member, and after 2155/// instantiating an in-class initializer in a class template. Such actions 2156/// are deferred until the class is complete. 2157void 2158Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2159 Expr *InitExpr) { 2160 FieldDecl *FD = cast<FieldDecl>(D); 2161 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2162 "must set init style when field is created"); 2163 2164 if (!InitExpr) { 2165 FD->setInvalidDecl(); 2166 FD->removeInClassInitializer(); 2167 return; 2168 } 2169 2170 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2171 FD->setInvalidDecl(); 2172 FD->removeInClassInitializer(); 2173 return; 2174 } 2175 2176 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 2177 != DiagnosticsEngine::Ignored) { 2178 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 2179 } 2180 2181 ExprResult Init = InitExpr; 2182 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2183 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2184 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2185 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2186 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2187 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2188 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2189 if (Init.isInvalid()) { 2190 FD->setInvalidDecl(); 2191 return; 2192 } 2193 } 2194 2195 // C++11 [class.base.init]p7: 2196 // The initialization of each base and member constitutes a 2197 // full-expression. 2198 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2199 if (Init.isInvalid()) { 2200 FD->setInvalidDecl(); 2201 return; 2202 } 2203 2204 InitExpr = Init.release(); 2205 2206 FD->setInClassInitializer(InitExpr); 2207} 2208 2209/// \brief Find the direct and/or virtual base specifiers that 2210/// correspond to the given base type, for use in base initialization 2211/// within a constructor. 2212static bool FindBaseInitializer(Sema &SemaRef, 2213 CXXRecordDecl *ClassDecl, 2214 QualType BaseType, 2215 const CXXBaseSpecifier *&DirectBaseSpec, 2216 const CXXBaseSpecifier *&VirtualBaseSpec) { 2217 // First, check for a direct base class. 2218 DirectBaseSpec = 0; 2219 for (CXXRecordDecl::base_class_const_iterator Base 2220 = ClassDecl->bases_begin(); 2221 Base != ClassDecl->bases_end(); ++Base) { 2222 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2223 // We found a direct base of this type. That's what we're 2224 // initializing. 2225 DirectBaseSpec = &*Base; 2226 break; 2227 } 2228 } 2229 2230 // Check for a virtual base class. 2231 // FIXME: We might be able to short-circuit this if we know in advance that 2232 // there are no virtual bases. 2233 VirtualBaseSpec = 0; 2234 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2235 // We haven't found a base yet; search the class hierarchy for a 2236 // virtual base class. 2237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2238 /*DetectVirtual=*/false); 2239 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2240 BaseType, Paths)) { 2241 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2242 Path != Paths.end(); ++Path) { 2243 if (Path->back().Base->isVirtual()) { 2244 VirtualBaseSpec = Path->back().Base; 2245 break; 2246 } 2247 } 2248 } 2249 } 2250 2251 return DirectBaseSpec || VirtualBaseSpec; 2252} 2253 2254/// \brief Handle a C++ member initializer using braced-init-list syntax. 2255MemInitResult 2256Sema::ActOnMemInitializer(Decl *ConstructorD, 2257 Scope *S, 2258 CXXScopeSpec &SS, 2259 IdentifierInfo *MemberOrBase, 2260 ParsedType TemplateTypeTy, 2261 const DeclSpec &DS, 2262 SourceLocation IdLoc, 2263 Expr *InitList, 2264 SourceLocation EllipsisLoc) { 2265 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2266 DS, IdLoc, InitList, 2267 EllipsisLoc); 2268} 2269 2270/// \brief Handle a C++ member initializer using parentheses syntax. 2271MemInitResult 2272Sema::ActOnMemInitializer(Decl *ConstructorD, 2273 Scope *S, 2274 CXXScopeSpec &SS, 2275 IdentifierInfo *MemberOrBase, 2276 ParsedType TemplateTypeTy, 2277 const DeclSpec &DS, 2278 SourceLocation IdLoc, 2279 SourceLocation LParenLoc, 2280 ArrayRef<Expr *> Args, 2281 SourceLocation RParenLoc, 2282 SourceLocation EllipsisLoc) { 2283 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2284 Args, RParenLoc); 2285 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2286 DS, IdLoc, List, EllipsisLoc); 2287} 2288 2289namespace { 2290 2291// Callback to only accept typo corrections that can be a valid C++ member 2292// intializer: either a non-static field member or a base class. 2293class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2294 public: 2295 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2296 : ClassDecl(ClassDecl) {} 2297 2298 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2299 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2300 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2301 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2302 else 2303 return isa<TypeDecl>(ND); 2304 } 2305 return false; 2306 } 2307 2308 private: 2309 CXXRecordDecl *ClassDecl; 2310}; 2311 2312} 2313 2314/// \brief Handle a C++ member initializer. 2315MemInitResult 2316Sema::BuildMemInitializer(Decl *ConstructorD, 2317 Scope *S, 2318 CXXScopeSpec &SS, 2319 IdentifierInfo *MemberOrBase, 2320 ParsedType TemplateTypeTy, 2321 const DeclSpec &DS, 2322 SourceLocation IdLoc, 2323 Expr *Init, 2324 SourceLocation EllipsisLoc) { 2325 if (!ConstructorD) 2326 return true; 2327 2328 AdjustDeclIfTemplate(ConstructorD); 2329 2330 CXXConstructorDecl *Constructor 2331 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2332 if (!Constructor) { 2333 // The user wrote a constructor initializer on a function that is 2334 // not a C++ constructor. Ignore the error for now, because we may 2335 // have more member initializers coming; we'll diagnose it just 2336 // once in ActOnMemInitializers. 2337 return true; 2338 } 2339 2340 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2341 2342 // C++ [class.base.init]p2: 2343 // Names in a mem-initializer-id are looked up in the scope of the 2344 // constructor's class and, if not found in that scope, are looked 2345 // up in the scope containing the constructor's definition. 2346 // [Note: if the constructor's class contains a member with the 2347 // same name as a direct or virtual base class of the class, a 2348 // mem-initializer-id naming the member or base class and composed 2349 // of a single identifier refers to the class member. A 2350 // mem-initializer-id for the hidden base class may be specified 2351 // using a qualified name. ] 2352 if (!SS.getScopeRep() && !TemplateTypeTy) { 2353 // Look for a member, first. 2354 DeclContext::lookup_result Result 2355 = ClassDecl->lookup(MemberOrBase); 2356 if (!Result.empty()) { 2357 ValueDecl *Member; 2358 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2359 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2360 if (EllipsisLoc.isValid()) 2361 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2362 << MemberOrBase 2363 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2364 2365 return BuildMemberInitializer(Member, Init, IdLoc); 2366 } 2367 } 2368 } 2369 // It didn't name a member, so see if it names a class. 2370 QualType BaseType; 2371 TypeSourceInfo *TInfo = 0; 2372 2373 if (TemplateTypeTy) { 2374 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2375 } else if (DS.getTypeSpecType() == TST_decltype) { 2376 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2377 } else { 2378 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2379 LookupParsedName(R, S, &SS); 2380 2381 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2382 if (!TyD) { 2383 if (R.isAmbiguous()) return true; 2384 2385 // We don't want access-control diagnostics here. 2386 R.suppressDiagnostics(); 2387 2388 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2389 bool NotUnknownSpecialization = false; 2390 DeclContext *DC = computeDeclContext(SS, false); 2391 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2392 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2393 2394 if (!NotUnknownSpecialization) { 2395 // When the scope specifier can refer to a member of an unknown 2396 // specialization, we take it as a type name. 2397 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2398 SS.getWithLocInContext(Context), 2399 *MemberOrBase, IdLoc); 2400 if (BaseType.isNull()) 2401 return true; 2402 2403 R.clear(); 2404 R.setLookupName(MemberOrBase); 2405 } 2406 } 2407 2408 // If no results were found, try to correct typos. 2409 TypoCorrection Corr; 2410 MemInitializerValidatorCCC Validator(ClassDecl); 2411 if (R.empty() && BaseType.isNull() && 2412 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2413 Validator, ClassDecl))) { 2414 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2415 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2416 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2417 // We have found a non-static data member with a similar 2418 // name to what was typed; complain and initialize that 2419 // member. 2420 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2421 << MemberOrBase << true << CorrectedQuotedStr 2422 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2423 Diag(Member->getLocation(), diag::note_previous_decl) 2424 << CorrectedQuotedStr; 2425 2426 return BuildMemberInitializer(Member, Init, IdLoc); 2427 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2428 const CXXBaseSpecifier *DirectBaseSpec; 2429 const CXXBaseSpecifier *VirtualBaseSpec; 2430 if (FindBaseInitializer(*this, ClassDecl, 2431 Context.getTypeDeclType(Type), 2432 DirectBaseSpec, VirtualBaseSpec)) { 2433 // We have found a direct or virtual base class with a 2434 // similar name to what was typed; complain and initialize 2435 // that base class. 2436 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2437 << MemberOrBase << false << CorrectedQuotedStr 2438 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2439 2440 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2441 : VirtualBaseSpec; 2442 Diag(BaseSpec->getLocStart(), 2443 diag::note_base_class_specified_here) 2444 << BaseSpec->getType() 2445 << BaseSpec->getSourceRange(); 2446 2447 TyD = Type; 2448 } 2449 } 2450 } 2451 2452 if (!TyD && BaseType.isNull()) { 2453 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2454 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2455 return true; 2456 } 2457 } 2458 2459 if (BaseType.isNull()) { 2460 BaseType = Context.getTypeDeclType(TyD); 2461 if (SS.isSet()) { 2462 NestedNameSpecifier *Qualifier = 2463 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2464 2465 // FIXME: preserve source range information 2466 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2467 } 2468 } 2469 } 2470 2471 if (!TInfo) 2472 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2473 2474 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2475} 2476 2477/// Checks a member initializer expression for cases where reference (or 2478/// pointer) members are bound to by-value parameters (or their addresses). 2479static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2480 Expr *Init, 2481 SourceLocation IdLoc) { 2482 QualType MemberTy = Member->getType(); 2483 2484 // We only handle pointers and references currently. 2485 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2486 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2487 return; 2488 2489 const bool IsPointer = MemberTy->isPointerType(); 2490 if (IsPointer) { 2491 if (const UnaryOperator *Op 2492 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2493 // The only case we're worried about with pointers requires taking the 2494 // address. 2495 if (Op->getOpcode() != UO_AddrOf) 2496 return; 2497 2498 Init = Op->getSubExpr(); 2499 } else { 2500 // We only handle address-of expression initializers for pointers. 2501 return; 2502 } 2503 } 2504 2505 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2506 // We only warn when referring to a non-reference parameter declaration. 2507 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2508 if (!Parameter || Parameter->getType()->isReferenceType()) 2509 return; 2510 2511 S.Diag(Init->getExprLoc(), 2512 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2513 : diag::warn_bind_ref_member_to_parameter) 2514 << Member << Parameter << Init->getSourceRange(); 2515 } else { 2516 // Other initializers are fine. 2517 return; 2518 } 2519 2520 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2521 << (unsigned)IsPointer; 2522} 2523 2524MemInitResult 2525Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2526 SourceLocation IdLoc) { 2527 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2528 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2529 assert((DirectMember || IndirectMember) && 2530 "Member must be a FieldDecl or IndirectFieldDecl"); 2531 2532 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2533 return true; 2534 2535 if (Member->isInvalidDecl()) 2536 return true; 2537 2538 // Diagnose value-uses of fields to initialize themselves, e.g. 2539 // foo(foo) 2540 // where foo is not also a parameter to the constructor. 2541 // TODO: implement -Wuninitialized and fold this into that framework. 2542 MultiExprArg Args; 2543 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2544 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2545 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2546 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2547 } else { 2548 // Template instantiation doesn't reconstruct ParenListExprs for us. 2549 Args = Init; 2550 } 2551 2552 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2553 != DiagnosticsEngine::Ignored) 2554 for (unsigned i = 0, e = Args.size(); i != e; ++i) 2555 // FIXME: Warn about the case when other fields are used before being 2556 // initialized. For example, let this field be the i'th field. When 2557 // initializing the i'th field, throw a warning if any of the >= i'th 2558 // fields are used, as they are not yet initialized. 2559 // Right now we are only handling the case where the i'th field uses 2560 // itself in its initializer. 2561 // Also need to take into account that some fields may be initialized by 2562 // in-class initializers, see C++11 [class.base.init]p9. 2563 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2564 2565 SourceRange InitRange = Init->getSourceRange(); 2566 2567 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2568 // Can't check initialization for a member of dependent type or when 2569 // any of the arguments are type-dependent expressions. 2570 DiscardCleanupsInEvaluationContext(); 2571 } else { 2572 bool InitList = false; 2573 if (isa<InitListExpr>(Init)) { 2574 InitList = true; 2575 Args = Init; 2576 } 2577 2578 // Initialize the member. 2579 InitializedEntity MemberEntity = 2580 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2581 : InitializedEntity::InitializeMember(IndirectMember, 0); 2582 InitializationKind Kind = 2583 InitList ? InitializationKind::CreateDirectList(IdLoc) 2584 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2585 InitRange.getEnd()); 2586 2587 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2588 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2589 if (MemberInit.isInvalid()) 2590 return true; 2591 2592 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2593 2594 // C++11 [class.base.init]p7: 2595 // The initialization of each base and member constitutes a 2596 // full-expression. 2597 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2598 if (MemberInit.isInvalid()) 2599 return true; 2600 2601 Init = MemberInit.get(); 2602 } 2603 2604 if (DirectMember) { 2605 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2606 InitRange.getBegin(), Init, 2607 InitRange.getEnd()); 2608 } else { 2609 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2610 InitRange.getBegin(), Init, 2611 InitRange.getEnd()); 2612 } 2613} 2614 2615MemInitResult 2616Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2617 CXXRecordDecl *ClassDecl) { 2618 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2619 if (!LangOpts.CPlusPlus11) 2620 return Diag(NameLoc, diag::err_delegating_ctor) 2621 << TInfo->getTypeLoc().getLocalSourceRange(); 2622 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2623 2624 bool InitList = true; 2625 MultiExprArg Args = Init; 2626 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2627 InitList = false; 2628 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2629 } 2630 2631 SourceRange InitRange = Init->getSourceRange(); 2632 // Initialize the object. 2633 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2634 QualType(ClassDecl->getTypeForDecl(), 0)); 2635 InitializationKind Kind = 2636 InitList ? InitializationKind::CreateDirectList(NameLoc) 2637 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2638 InitRange.getEnd()); 2639 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2640 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2641 Args, 0); 2642 if (DelegationInit.isInvalid()) 2643 return true; 2644 2645 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2646 "Delegating constructor with no target?"); 2647 2648 // C++11 [class.base.init]p7: 2649 // The initialization of each base and member constitutes a 2650 // full-expression. 2651 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2652 InitRange.getBegin()); 2653 if (DelegationInit.isInvalid()) 2654 return true; 2655 2656 // If we are in a dependent context, template instantiation will 2657 // perform this type-checking again. Just save the arguments that we 2658 // received in a ParenListExpr. 2659 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2660 // of the information that we have about the base 2661 // initializer. However, deconstructing the ASTs is a dicey process, 2662 // and this approach is far more likely to get the corner cases right. 2663 if (CurContext->isDependentContext()) 2664 DelegationInit = Owned(Init); 2665 2666 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2667 DelegationInit.takeAs<Expr>(), 2668 InitRange.getEnd()); 2669} 2670 2671MemInitResult 2672Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2673 Expr *Init, CXXRecordDecl *ClassDecl, 2674 SourceLocation EllipsisLoc) { 2675 SourceLocation BaseLoc 2676 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2677 2678 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2679 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2680 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2681 2682 // C++ [class.base.init]p2: 2683 // [...] Unless the mem-initializer-id names a nonstatic data 2684 // member of the constructor's class or a direct or virtual base 2685 // of that class, the mem-initializer is ill-formed. A 2686 // mem-initializer-list can initialize a base class using any 2687 // name that denotes that base class type. 2688 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2689 2690 SourceRange InitRange = Init->getSourceRange(); 2691 if (EllipsisLoc.isValid()) { 2692 // This is a pack expansion. 2693 if (!BaseType->containsUnexpandedParameterPack()) { 2694 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2695 << SourceRange(BaseLoc, InitRange.getEnd()); 2696 2697 EllipsisLoc = SourceLocation(); 2698 } 2699 } else { 2700 // Check for any unexpanded parameter packs. 2701 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2702 return true; 2703 2704 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2705 return true; 2706 } 2707 2708 // Check for direct and virtual base classes. 2709 const CXXBaseSpecifier *DirectBaseSpec = 0; 2710 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2711 if (!Dependent) { 2712 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2713 BaseType)) 2714 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2715 2716 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2717 VirtualBaseSpec); 2718 2719 // C++ [base.class.init]p2: 2720 // Unless the mem-initializer-id names a nonstatic data member of the 2721 // constructor's class or a direct or virtual base of that class, the 2722 // mem-initializer is ill-formed. 2723 if (!DirectBaseSpec && !VirtualBaseSpec) { 2724 // If the class has any dependent bases, then it's possible that 2725 // one of those types will resolve to the same type as 2726 // BaseType. Therefore, just treat this as a dependent base 2727 // class initialization. FIXME: Should we try to check the 2728 // initialization anyway? It seems odd. 2729 if (ClassDecl->hasAnyDependentBases()) 2730 Dependent = true; 2731 else 2732 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2733 << BaseType << Context.getTypeDeclType(ClassDecl) 2734 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2735 } 2736 } 2737 2738 if (Dependent) { 2739 DiscardCleanupsInEvaluationContext(); 2740 2741 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2742 /*IsVirtual=*/false, 2743 InitRange.getBegin(), Init, 2744 InitRange.getEnd(), EllipsisLoc); 2745 } 2746 2747 // C++ [base.class.init]p2: 2748 // If a mem-initializer-id is ambiguous because it designates both 2749 // a direct non-virtual base class and an inherited virtual base 2750 // class, the mem-initializer is ill-formed. 2751 if (DirectBaseSpec && VirtualBaseSpec) 2752 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2753 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2754 2755 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2756 if (!BaseSpec) 2757 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2758 2759 // Initialize the base. 2760 bool InitList = true; 2761 MultiExprArg Args = Init; 2762 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2763 InitList = false; 2764 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2765 } 2766 2767 InitializedEntity BaseEntity = 2768 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2769 InitializationKind Kind = 2770 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2771 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2772 InitRange.getEnd()); 2773 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2774 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2775 if (BaseInit.isInvalid()) 2776 return true; 2777 2778 // C++11 [class.base.init]p7: 2779 // The initialization of each base and member constitutes a 2780 // full-expression. 2781 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2782 if (BaseInit.isInvalid()) 2783 return true; 2784 2785 // If we are in a dependent context, template instantiation will 2786 // perform this type-checking again. Just save the arguments that we 2787 // received in a ParenListExpr. 2788 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2789 // of the information that we have about the base 2790 // initializer. However, deconstructing the ASTs is a dicey process, 2791 // and this approach is far more likely to get the corner cases right. 2792 if (CurContext->isDependentContext()) 2793 BaseInit = Owned(Init); 2794 2795 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2796 BaseSpec->isVirtual(), 2797 InitRange.getBegin(), 2798 BaseInit.takeAs<Expr>(), 2799 InitRange.getEnd(), EllipsisLoc); 2800} 2801 2802// Create a static_cast\<T&&>(expr). 2803static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2804 if (T.isNull()) T = E->getType(); 2805 QualType TargetType = SemaRef.BuildReferenceType( 2806 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2807 SourceLocation ExprLoc = E->getLocStart(); 2808 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2809 TargetType, ExprLoc); 2810 2811 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2812 SourceRange(ExprLoc, ExprLoc), 2813 E->getSourceRange()).take(); 2814} 2815 2816/// ImplicitInitializerKind - How an implicit base or member initializer should 2817/// initialize its base or member. 2818enum ImplicitInitializerKind { 2819 IIK_Default, 2820 IIK_Copy, 2821 IIK_Move, 2822 IIK_Inherit 2823}; 2824 2825static bool 2826BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2827 ImplicitInitializerKind ImplicitInitKind, 2828 CXXBaseSpecifier *BaseSpec, 2829 bool IsInheritedVirtualBase, 2830 CXXCtorInitializer *&CXXBaseInit) { 2831 InitializedEntity InitEntity 2832 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2833 IsInheritedVirtualBase); 2834 2835 ExprResult BaseInit; 2836 2837 switch (ImplicitInitKind) { 2838 case IIK_Inherit: { 2839 const CXXRecordDecl *Inherited = 2840 Constructor->getInheritedConstructor()->getParent(); 2841 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2842 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2843 // C++11 [class.inhctor]p8: 2844 // Each expression in the expression-list is of the form 2845 // static_cast<T&&>(p), where p is the name of the corresponding 2846 // constructor parameter and T is the declared type of p. 2847 SmallVector<Expr*, 16> Args; 2848 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2849 ParmVarDecl *PD = Constructor->getParamDecl(I); 2850 ExprResult ArgExpr = 2851 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2852 VK_LValue, SourceLocation()); 2853 if (ArgExpr.isInvalid()) 2854 return true; 2855 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2856 } 2857 2858 InitializationKind InitKind = InitializationKind::CreateDirect( 2859 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2860 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2861 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2862 break; 2863 } 2864 } 2865 // Fall through. 2866 case IIK_Default: { 2867 InitializationKind InitKind 2868 = InitializationKind::CreateDefault(Constructor->getLocation()); 2869 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2870 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2871 break; 2872 } 2873 2874 case IIK_Move: 2875 case IIK_Copy: { 2876 bool Moving = ImplicitInitKind == IIK_Move; 2877 ParmVarDecl *Param = Constructor->getParamDecl(0); 2878 QualType ParamType = Param->getType().getNonReferenceType(); 2879 2880 Expr *CopyCtorArg = 2881 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2882 SourceLocation(), Param, false, 2883 Constructor->getLocation(), ParamType, 2884 VK_LValue, 0); 2885 2886 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2887 2888 // Cast to the base class to avoid ambiguities. 2889 QualType ArgTy = 2890 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2891 ParamType.getQualifiers()); 2892 2893 if (Moving) { 2894 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2895 } 2896 2897 CXXCastPath BasePath; 2898 BasePath.push_back(BaseSpec); 2899 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2900 CK_UncheckedDerivedToBase, 2901 Moving ? VK_XValue : VK_LValue, 2902 &BasePath).take(); 2903 2904 InitializationKind InitKind 2905 = InitializationKind::CreateDirect(Constructor->getLocation(), 2906 SourceLocation(), SourceLocation()); 2907 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 2908 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 2909 break; 2910 } 2911 } 2912 2913 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2914 if (BaseInit.isInvalid()) 2915 return true; 2916 2917 CXXBaseInit = 2918 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2919 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2920 SourceLocation()), 2921 BaseSpec->isVirtual(), 2922 SourceLocation(), 2923 BaseInit.takeAs<Expr>(), 2924 SourceLocation(), 2925 SourceLocation()); 2926 2927 return false; 2928} 2929 2930static bool RefersToRValueRef(Expr *MemRef) { 2931 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2932 return Referenced->getType()->isRValueReferenceType(); 2933} 2934 2935static bool 2936BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2937 ImplicitInitializerKind ImplicitInitKind, 2938 FieldDecl *Field, IndirectFieldDecl *Indirect, 2939 CXXCtorInitializer *&CXXMemberInit) { 2940 if (Field->isInvalidDecl()) 2941 return true; 2942 2943 SourceLocation Loc = Constructor->getLocation(); 2944 2945 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2946 bool Moving = ImplicitInitKind == IIK_Move; 2947 ParmVarDecl *Param = Constructor->getParamDecl(0); 2948 QualType ParamType = Param->getType().getNonReferenceType(); 2949 2950 // Suppress copying zero-width bitfields. 2951 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2952 return false; 2953 2954 Expr *MemberExprBase = 2955 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2956 SourceLocation(), Param, false, 2957 Loc, ParamType, VK_LValue, 0); 2958 2959 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2960 2961 if (Moving) { 2962 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2963 } 2964 2965 // Build a reference to this field within the parameter. 2966 CXXScopeSpec SS; 2967 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2968 Sema::LookupMemberName); 2969 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2970 : cast<ValueDecl>(Field), AS_public); 2971 MemberLookup.resolveKind(); 2972 ExprResult CtorArg 2973 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2974 ParamType, Loc, 2975 /*IsArrow=*/false, 2976 SS, 2977 /*TemplateKWLoc=*/SourceLocation(), 2978 /*FirstQualifierInScope=*/0, 2979 MemberLookup, 2980 /*TemplateArgs=*/0); 2981 if (CtorArg.isInvalid()) 2982 return true; 2983 2984 // C++11 [class.copy]p15: 2985 // - if a member m has rvalue reference type T&&, it is direct-initialized 2986 // with static_cast<T&&>(x.m); 2987 if (RefersToRValueRef(CtorArg.get())) { 2988 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2989 } 2990 2991 // When the field we are copying is an array, create index variables for 2992 // each dimension of the array. We use these index variables to subscript 2993 // the source array, and other clients (e.g., CodeGen) will perform the 2994 // necessary iteration with these index variables. 2995 SmallVector<VarDecl *, 4> IndexVariables; 2996 QualType BaseType = Field->getType(); 2997 QualType SizeType = SemaRef.Context.getSizeType(); 2998 bool InitializingArray = false; 2999 while (const ConstantArrayType *Array 3000 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3001 InitializingArray = true; 3002 // Create the iteration variable for this array index. 3003 IdentifierInfo *IterationVarName = 0; 3004 { 3005 SmallString<8> Str; 3006 llvm::raw_svector_ostream OS(Str); 3007 OS << "__i" << IndexVariables.size(); 3008 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3009 } 3010 VarDecl *IterationVar 3011 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3012 IterationVarName, SizeType, 3013 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3014 SC_None); 3015 IndexVariables.push_back(IterationVar); 3016 3017 // Create a reference to the iteration variable. 3018 ExprResult IterationVarRef 3019 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3020 assert(!IterationVarRef.isInvalid() && 3021 "Reference to invented variable cannot fail!"); 3022 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3023 assert(!IterationVarRef.isInvalid() && 3024 "Conversion of invented variable cannot fail!"); 3025 3026 // Subscript the array with this iteration variable. 3027 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3028 IterationVarRef.take(), 3029 Loc); 3030 if (CtorArg.isInvalid()) 3031 return true; 3032 3033 BaseType = Array->getElementType(); 3034 } 3035 3036 // The array subscript expression is an lvalue, which is wrong for moving. 3037 if (Moving && InitializingArray) 3038 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3039 3040 // Construct the entity that we will be initializing. For an array, this 3041 // will be first element in the array, which may require several levels 3042 // of array-subscript entities. 3043 SmallVector<InitializedEntity, 4> Entities; 3044 Entities.reserve(1 + IndexVariables.size()); 3045 if (Indirect) 3046 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3047 else 3048 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3049 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3050 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3051 0, 3052 Entities.back())); 3053 3054 // Direct-initialize to use the copy constructor. 3055 InitializationKind InitKind = 3056 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3057 3058 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3059 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3060 3061 ExprResult MemberInit 3062 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3063 MultiExprArg(&CtorArgE, 1)); 3064 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3065 if (MemberInit.isInvalid()) 3066 return true; 3067 3068 if (Indirect) { 3069 assert(IndexVariables.size() == 0 && 3070 "Indirect field improperly initialized"); 3071 CXXMemberInit 3072 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3073 Loc, Loc, 3074 MemberInit.takeAs<Expr>(), 3075 Loc); 3076 } else 3077 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3078 Loc, MemberInit.takeAs<Expr>(), 3079 Loc, 3080 IndexVariables.data(), 3081 IndexVariables.size()); 3082 return false; 3083 } 3084 3085 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3086 "Unhandled implicit init kind!"); 3087 3088 QualType FieldBaseElementType = 3089 SemaRef.Context.getBaseElementType(Field->getType()); 3090 3091 if (FieldBaseElementType->isRecordType()) { 3092 InitializedEntity InitEntity 3093 = Indirect? InitializedEntity::InitializeMember(Indirect) 3094 : InitializedEntity::InitializeMember(Field); 3095 InitializationKind InitKind = 3096 InitializationKind::CreateDefault(Loc); 3097 3098 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3099 ExprResult MemberInit = 3100 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3101 3102 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3103 if (MemberInit.isInvalid()) 3104 return true; 3105 3106 if (Indirect) 3107 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3108 Indirect, Loc, 3109 Loc, 3110 MemberInit.get(), 3111 Loc); 3112 else 3113 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3114 Field, Loc, Loc, 3115 MemberInit.get(), 3116 Loc); 3117 return false; 3118 } 3119 3120 if (!Field->getParent()->isUnion()) { 3121 if (FieldBaseElementType->isReferenceType()) { 3122 SemaRef.Diag(Constructor->getLocation(), 3123 diag::err_uninitialized_member_in_ctor) 3124 << (int)Constructor->isImplicit() 3125 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3126 << 0 << Field->getDeclName(); 3127 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3128 return true; 3129 } 3130 3131 if (FieldBaseElementType.isConstQualified()) { 3132 SemaRef.Diag(Constructor->getLocation(), 3133 diag::err_uninitialized_member_in_ctor) 3134 << (int)Constructor->isImplicit() 3135 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3136 << 1 << Field->getDeclName(); 3137 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3138 return true; 3139 } 3140 } 3141 3142 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3143 FieldBaseElementType->isObjCRetainableType() && 3144 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3145 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3146 // ARC: 3147 // Default-initialize Objective-C pointers to NULL. 3148 CXXMemberInit 3149 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3150 Loc, Loc, 3151 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3152 Loc); 3153 return false; 3154 } 3155 3156 // Nothing to initialize. 3157 CXXMemberInit = 0; 3158 return false; 3159} 3160 3161namespace { 3162struct BaseAndFieldInfo { 3163 Sema &S; 3164 CXXConstructorDecl *Ctor; 3165 bool AnyErrorsInInits; 3166 ImplicitInitializerKind IIK; 3167 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3168 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3169 3170 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3171 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3172 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3173 if (Generated && Ctor->isCopyConstructor()) 3174 IIK = IIK_Copy; 3175 else if (Generated && Ctor->isMoveConstructor()) 3176 IIK = IIK_Move; 3177 else if (Ctor->getInheritedConstructor()) 3178 IIK = IIK_Inherit; 3179 else 3180 IIK = IIK_Default; 3181 } 3182 3183 bool isImplicitCopyOrMove() const { 3184 switch (IIK) { 3185 case IIK_Copy: 3186 case IIK_Move: 3187 return true; 3188 3189 case IIK_Default: 3190 case IIK_Inherit: 3191 return false; 3192 } 3193 3194 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3195 } 3196 3197 bool addFieldInitializer(CXXCtorInitializer *Init) { 3198 AllToInit.push_back(Init); 3199 3200 // Check whether this initializer makes the field "used". 3201 if (Init->getInit()->HasSideEffects(S.Context)) 3202 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3203 3204 return false; 3205 } 3206}; 3207} 3208 3209/// \brief Determine whether the given indirect field declaration is somewhere 3210/// within an anonymous union. 3211static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3212 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3213 CEnd = F->chain_end(); 3214 C != CEnd; ++C) 3215 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3216 if (Record->isUnion()) 3217 return true; 3218 3219 return false; 3220} 3221 3222/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3223/// array type. 3224static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3225 if (T->isIncompleteArrayType()) 3226 return true; 3227 3228 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3229 if (!ArrayT->getSize()) 3230 return true; 3231 3232 T = ArrayT->getElementType(); 3233 } 3234 3235 return false; 3236} 3237 3238static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3239 FieldDecl *Field, 3240 IndirectFieldDecl *Indirect = 0) { 3241 if (Field->isInvalidDecl()) 3242 return false; 3243 3244 // Overwhelmingly common case: we have a direct initializer for this field. 3245 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3246 return Info.addFieldInitializer(Init); 3247 3248 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3249 // has a brace-or-equal-initializer, the entity is initialized as specified 3250 // in [dcl.init]. 3251 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3252 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3253 Info.Ctor->getLocation(), Field); 3254 CXXCtorInitializer *Init; 3255 if (Indirect) 3256 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3257 SourceLocation(), 3258 SourceLocation(), DIE, 3259 SourceLocation()); 3260 else 3261 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3262 SourceLocation(), 3263 SourceLocation(), DIE, 3264 SourceLocation()); 3265 return Info.addFieldInitializer(Init); 3266 } 3267 3268 // Don't build an implicit initializer for union members if none was 3269 // explicitly specified. 3270 if (Field->getParent()->isUnion() || 3271 (Indirect && isWithinAnonymousUnion(Indirect))) 3272 return false; 3273 3274 // Don't initialize incomplete or zero-length arrays. 3275 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3276 return false; 3277 3278 // Don't try to build an implicit initializer if there were semantic 3279 // errors in any of the initializers (and therefore we might be 3280 // missing some that the user actually wrote). 3281 if (Info.AnyErrorsInInits) 3282 return false; 3283 3284 CXXCtorInitializer *Init = 0; 3285 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3286 Indirect, Init)) 3287 return true; 3288 3289 if (!Init) 3290 return false; 3291 3292 return Info.addFieldInitializer(Init); 3293} 3294 3295bool 3296Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3297 CXXCtorInitializer *Initializer) { 3298 assert(Initializer->isDelegatingInitializer()); 3299 Constructor->setNumCtorInitializers(1); 3300 CXXCtorInitializer **initializer = 3301 new (Context) CXXCtorInitializer*[1]; 3302 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3303 Constructor->setCtorInitializers(initializer); 3304 3305 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3306 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3307 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3308 } 3309 3310 DelegatingCtorDecls.push_back(Constructor); 3311 3312 return false; 3313} 3314 3315bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3316 ArrayRef<CXXCtorInitializer *> Initializers) { 3317 if (Constructor->isDependentContext()) { 3318 // Just store the initializers as written, they will be checked during 3319 // instantiation. 3320 if (!Initializers.empty()) { 3321 Constructor->setNumCtorInitializers(Initializers.size()); 3322 CXXCtorInitializer **baseOrMemberInitializers = 3323 new (Context) CXXCtorInitializer*[Initializers.size()]; 3324 memcpy(baseOrMemberInitializers, Initializers.data(), 3325 Initializers.size() * sizeof(CXXCtorInitializer*)); 3326 Constructor->setCtorInitializers(baseOrMemberInitializers); 3327 } 3328 3329 // Let template instantiation know whether we had errors. 3330 if (AnyErrors) 3331 Constructor->setInvalidDecl(); 3332 3333 return false; 3334 } 3335 3336 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3337 3338 // We need to build the initializer AST according to order of construction 3339 // and not what user specified in the Initializers list. 3340 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3341 if (!ClassDecl) 3342 return true; 3343 3344 bool HadError = false; 3345 3346 for (unsigned i = 0; i < Initializers.size(); i++) { 3347 CXXCtorInitializer *Member = Initializers[i]; 3348 3349 if (Member->isBaseInitializer()) 3350 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3351 else 3352 Info.AllBaseFields[Member->getAnyMember()] = Member; 3353 } 3354 3355 // Keep track of the direct virtual bases. 3356 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3357 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3358 E = ClassDecl->bases_end(); I != E; ++I) { 3359 if (I->isVirtual()) 3360 DirectVBases.insert(I); 3361 } 3362 3363 // Push virtual bases before others. 3364 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3365 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3366 3367 if (CXXCtorInitializer *Value 3368 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3369 // [class.base.init]p7, per DR257: 3370 // A mem-initializer where the mem-initializer-id names a virtual base 3371 // class is ignored during execution of a constructor of any class that 3372 // is not the most derived class. 3373 if (ClassDecl->isAbstract()) { 3374 // FIXME: Provide a fixit to remove the base specifier. This requires 3375 // tracking the location of the associated comma for a base specifier. 3376 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3377 << VBase->getType() << ClassDecl; 3378 DiagnoseAbstractType(ClassDecl); 3379 } 3380 3381 Info.AllToInit.push_back(Value); 3382 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3383 // [class.base.init]p8, per DR257: 3384 // If a given [...] base class is not named by a mem-initializer-id 3385 // [...] and the entity is not a virtual base class of an abstract 3386 // class, then [...] the entity is default-initialized. 3387 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3388 CXXCtorInitializer *CXXBaseInit; 3389 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3390 VBase, IsInheritedVirtualBase, 3391 CXXBaseInit)) { 3392 HadError = true; 3393 continue; 3394 } 3395 3396 Info.AllToInit.push_back(CXXBaseInit); 3397 } 3398 } 3399 3400 // Non-virtual bases. 3401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3402 E = ClassDecl->bases_end(); Base != E; ++Base) { 3403 // Virtuals are in the virtual base list and already constructed. 3404 if (Base->isVirtual()) 3405 continue; 3406 3407 if (CXXCtorInitializer *Value 3408 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3409 Info.AllToInit.push_back(Value); 3410 } else if (!AnyErrors) { 3411 CXXCtorInitializer *CXXBaseInit; 3412 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3413 Base, /*IsInheritedVirtualBase=*/false, 3414 CXXBaseInit)) { 3415 HadError = true; 3416 continue; 3417 } 3418 3419 Info.AllToInit.push_back(CXXBaseInit); 3420 } 3421 } 3422 3423 // Fields. 3424 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3425 MemEnd = ClassDecl->decls_end(); 3426 Mem != MemEnd; ++Mem) { 3427 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3428 // C++ [class.bit]p2: 3429 // A declaration for a bit-field that omits the identifier declares an 3430 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3431 // initialized. 3432 if (F->isUnnamedBitfield()) 3433 continue; 3434 3435 // If we're not generating the implicit copy/move constructor, then we'll 3436 // handle anonymous struct/union fields based on their individual 3437 // indirect fields. 3438 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3439 continue; 3440 3441 if (CollectFieldInitializer(*this, Info, F)) 3442 HadError = true; 3443 continue; 3444 } 3445 3446 // Beyond this point, we only consider default initialization. 3447 if (Info.isImplicitCopyOrMove()) 3448 continue; 3449 3450 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3451 if (F->getType()->isIncompleteArrayType()) { 3452 assert(ClassDecl->hasFlexibleArrayMember() && 3453 "Incomplete array type is not valid"); 3454 continue; 3455 } 3456 3457 // Initialize each field of an anonymous struct individually. 3458 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3459 HadError = true; 3460 3461 continue; 3462 } 3463 } 3464 3465 unsigned NumInitializers = Info.AllToInit.size(); 3466 if (NumInitializers > 0) { 3467 Constructor->setNumCtorInitializers(NumInitializers); 3468 CXXCtorInitializer **baseOrMemberInitializers = 3469 new (Context) CXXCtorInitializer*[NumInitializers]; 3470 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3471 NumInitializers * sizeof(CXXCtorInitializer*)); 3472 Constructor->setCtorInitializers(baseOrMemberInitializers); 3473 3474 // Constructors implicitly reference the base and member 3475 // destructors. 3476 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3477 Constructor->getParent()); 3478 } 3479 3480 return HadError; 3481} 3482 3483static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3484 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3485 const RecordDecl *RD = RT->getDecl(); 3486 if (RD->isAnonymousStructOrUnion()) { 3487 for (RecordDecl::field_iterator Field = RD->field_begin(), 3488 E = RD->field_end(); Field != E; ++Field) 3489 PopulateKeysForFields(*Field, IdealInits); 3490 return; 3491 } 3492 } 3493 IdealInits.push_back(Field); 3494} 3495 3496static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3497 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3498} 3499 3500static void *GetKeyForMember(ASTContext &Context, 3501 CXXCtorInitializer *Member) { 3502 if (!Member->isAnyMemberInitializer()) 3503 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3504 3505 return Member->getAnyMember(); 3506} 3507 3508static void DiagnoseBaseOrMemInitializerOrder( 3509 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3510 ArrayRef<CXXCtorInitializer *> Inits) { 3511 if (Constructor->getDeclContext()->isDependentContext()) 3512 return; 3513 3514 // Don't check initializers order unless the warning is enabled at the 3515 // location of at least one initializer. 3516 bool ShouldCheckOrder = false; 3517 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3518 CXXCtorInitializer *Init = Inits[InitIndex]; 3519 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3520 Init->getSourceLocation()) 3521 != DiagnosticsEngine::Ignored) { 3522 ShouldCheckOrder = true; 3523 break; 3524 } 3525 } 3526 if (!ShouldCheckOrder) 3527 return; 3528 3529 // Build the list of bases and members in the order that they'll 3530 // actually be initialized. The explicit initializers should be in 3531 // this same order but may be missing things. 3532 SmallVector<const void*, 32> IdealInitKeys; 3533 3534 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3535 3536 // 1. Virtual bases. 3537 for (CXXRecordDecl::base_class_const_iterator VBase = 3538 ClassDecl->vbases_begin(), 3539 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3540 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3541 3542 // 2. Non-virtual bases. 3543 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3544 E = ClassDecl->bases_end(); Base != E; ++Base) { 3545 if (Base->isVirtual()) 3546 continue; 3547 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3548 } 3549 3550 // 3. Direct fields. 3551 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3552 E = ClassDecl->field_end(); Field != E; ++Field) { 3553 if (Field->isUnnamedBitfield()) 3554 continue; 3555 3556 PopulateKeysForFields(*Field, IdealInitKeys); 3557 } 3558 3559 unsigned NumIdealInits = IdealInitKeys.size(); 3560 unsigned IdealIndex = 0; 3561 3562 CXXCtorInitializer *PrevInit = 0; 3563 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3564 CXXCtorInitializer *Init = Inits[InitIndex]; 3565 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3566 3567 // Scan forward to try to find this initializer in the idealized 3568 // initializers list. 3569 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3570 if (InitKey == IdealInitKeys[IdealIndex]) 3571 break; 3572 3573 // If we didn't find this initializer, it must be because we 3574 // scanned past it on a previous iteration. That can only 3575 // happen if we're out of order; emit a warning. 3576 if (IdealIndex == NumIdealInits && PrevInit) { 3577 Sema::SemaDiagnosticBuilder D = 3578 SemaRef.Diag(PrevInit->getSourceLocation(), 3579 diag::warn_initializer_out_of_order); 3580 3581 if (PrevInit->isAnyMemberInitializer()) 3582 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3583 else 3584 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3585 3586 if (Init->isAnyMemberInitializer()) 3587 D << 0 << Init->getAnyMember()->getDeclName(); 3588 else 3589 D << 1 << Init->getTypeSourceInfo()->getType(); 3590 3591 // Move back to the initializer's location in the ideal list. 3592 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3593 if (InitKey == IdealInitKeys[IdealIndex]) 3594 break; 3595 3596 assert(IdealIndex != NumIdealInits && 3597 "initializer not found in initializer list"); 3598 } 3599 3600 PrevInit = Init; 3601 } 3602} 3603 3604namespace { 3605bool CheckRedundantInit(Sema &S, 3606 CXXCtorInitializer *Init, 3607 CXXCtorInitializer *&PrevInit) { 3608 if (!PrevInit) { 3609 PrevInit = Init; 3610 return false; 3611 } 3612 3613 if (FieldDecl *Field = Init->getAnyMember()) 3614 S.Diag(Init->getSourceLocation(), 3615 diag::err_multiple_mem_initialization) 3616 << Field->getDeclName() 3617 << Init->getSourceRange(); 3618 else { 3619 const Type *BaseClass = Init->getBaseClass(); 3620 assert(BaseClass && "neither field nor base"); 3621 S.Diag(Init->getSourceLocation(), 3622 diag::err_multiple_base_initialization) 3623 << QualType(BaseClass, 0) 3624 << Init->getSourceRange(); 3625 } 3626 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3627 << 0 << PrevInit->getSourceRange(); 3628 3629 return true; 3630} 3631 3632typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3633typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3634 3635bool CheckRedundantUnionInit(Sema &S, 3636 CXXCtorInitializer *Init, 3637 RedundantUnionMap &Unions) { 3638 FieldDecl *Field = Init->getAnyMember(); 3639 RecordDecl *Parent = Field->getParent(); 3640 NamedDecl *Child = Field; 3641 3642 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3643 if (Parent->isUnion()) { 3644 UnionEntry &En = Unions[Parent]; 3645 if (En.first && En.first != Child) { 3646 S.Diag(Init->getSourceLocation(), 3647 diag::err_multiple_mem_union_initialization) 3648 << Field->getDeclName() 3649 << Init->getSourceRange(); 3650 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3651 << 0 << En.second->getSourceRange(); 3652 return true; 3653 } 3654 if (!En.first) { 3655 En.first = Child; 3656 En.second = Init; 3657 } 3658 if (!Parent->isAnonymousStructOrUnion()) 3659 return false; 3660 } 3661 3662 Child = Parent; 3663 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3664 } 3665 3666 return false; 3667} 3668} 3669 3670/// ActOnMemInitializers - Handle the member initializers for a constructor. 3671void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3672 SourceLocation ColonLoc, 3673 ArrayRef<CXXCtorInitializer*> MemInits, 3674 bool AnyErrors) { 3675 if (!ConstructorDecl) 3676 return; 3677 3678 AdjustDeclIfTemplate(ConstructorDecl); 3679 3680 CXXConstructorDecl *Constructor 3681 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3682 3683 if (!Constructor) { 3684 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3685 return; 3686 } 3687 3688 // Mapping for the duplicate initializers check. 3689 // For member initializers, this is keyed with a FieldDecl*. 3690 // For base initializers, this is keyed with a Type*. 3691 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3692 3693 // Mapping for the inconsistent anonymous-union initializers check. 3694 RedundantUnionMap MemberUnions; 3695 3696 bool HadError = false; 3697 for (unsigned i = 0; i < MemInits.size(); i++) { 3698 CXXCtorInitializer *Init = MemInits[i]; 3699 3700 // Set the source order index. 3701 Init->setSourceOrder(i); 3702 3703 if (Init->isAnyMemberInitializer()) { 3704 FieldDecl *Field = Init->getAnyMember(); 3705 if (CheckRedundantInit(*this, Init, Members[Field]) || 3706 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3707 HadError = true; 3708 } else if (Init->isBaseInitializer()) { 3709 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3710 if (CheckRedundantInit(*this, Init, Members[Key])) 3711 HadError = true; 3712 } else { 3713 assert(Init->isDelegatingInitializer()); 3714 // This must be the only initializer 3715 if (MemInits.size() != 1) { 3716 Diag(Init->getSourceLocation(), 3717 diag::err_delegating_initializer_alone) 3718 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3719 // We will treat this as being the only initializer. 3720 } 3721 SetDelegatingInitializer(Constructor, MemInits[i]); 3722 // Return immediately as the initializer is set. 3723 return; 3724 } 3725 } 3726 3727 if (HadError) 3728 return; 3729 3730 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3731 3732 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3733} 3734 3735void 3736Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3737 CXXRecordDecl *ClassDecl) { 3738 // Ignore dependent contexts. Also ignore unions, since their members never 3739 // have destructors implicitly called. 3740 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3741 return; 3742 3743 // FIXME: all the access-control diagnostics are positioned on the 3744 // field/base declaration. That's probably good; that said, the 3745 // user might reasonably want to know why the destructor is being 3746 // emitted, and we currently don't say. 3747 3748 // Non-static data members. 3749 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3750 E = ClassDecl->field_end(); I != E; ++I) { 3751 FieldDecl *Field = *I; 3752 if (Field->isInvalidDecl()) 3753 continue; 3754 3755 // Don't destroy incomplete or zero-length arrays. 3756 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3757 continue; 3758 3759 QualType FieldType = Context.getBaseElementType(Field->getType()); 3760 3761 const RecordType* RT = FieldType->getAs<RecordType>(); 3762 if (!RT) 3763 continue; 3764 3765 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3766 if (FieldClassDecl->isInvalidDecl()) 3767 continue; 3768 if (FieldClassDecl->hasIrrelevantDestructor()) 3769 continue; 3770 // The destructor for an implicit anonymous union member is never invoked. 3771 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3772 continue; 3773 3774 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3775 assert(Dtor && "No dtor found for FieldClassDecl!"); 3776 CheckDestructorAccess(Field->getLocation(), Dtor, 3777 PDiag(diag::err_access_dtor_field) 3778 << Field->getDeclName() 3779 << FieldType); 3780 3781 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3782 DiagnoseUseOfDecl(Dtor, Location); 3783 } 3784 3785 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3786 3787 // Bases. 3788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3789 E = ClassDecl->bases_end(); Base != E; ++Base) { 3790 // Bases are always records in a well-formed non-dependent class. 3791 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3792 3793 // Remember direct virtual bases. 3794 if (Base->isVirtual()) 3795 DirectVirtualBases.insert(RT); 3796 3797 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3798 // If our base class is invalid, we probably can't get its dtor anyway. 3799 if (BaseClassDecl->isInvalidDecl()) 3800 continue; 3801 if (BaseClassDecl->hasIrrelevantDestructor()) 3802 continue; 3803 3804 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3805 assert(Dtor && "No dtor found for BaseClassDecl!"); 3806 3807 // FIXME: caret should be on the start of the class name 3808 CheckDestructorAccess(Base->getLocStart(), Dtor, 3809 PDiag(diag::err_access_dtor_base) 3810 << Base->getType() 3811 << Base->getSourceRange(), 3812 Context.getTypeDeclType(ClassDecl)); 3813 3814 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3815 DiagnoseUseOfDecl(Dtor, Location); 3816 } 3817 3818 // Virtual bases. 3819 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3820 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3821 3822 // Bases are always records in a well-formed non-dependent class. 3823 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3824 3825 // Ignore direct virtual bases. 3826 if (DirectVirtualBases.count(RT)) 3827 continue; 3828 3829 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3830 // If our base class is invalid, we probably can't get its dtor anyway. 3831 if (BaseClassDecl->isInvalidDecl()) 3832 continue; 3833 if (BaseClassDecl->hasIrrelevantDestructor()) 3834 continue; 3835 3836 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3837 assert(Dtor && "No dtor found for BaseClassDecl!"); 3838 if (CheckDestructorAccess( 3839 ClassDecl->getLocation(), Dtor, 3840 PDiag(diag::err_access_dtor_vbase) 3841 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 3842 Context.getTypeDeclType(ClassDecl)) == 3843 AR_accessible) { 3844 CheckDerivedToBaseConversion( 3845 Context.getTypeDeclType(ClassDecl), VBase->getType(), 3846 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 3847 SourceRange(), DeclarationName(), 0); 3848 } 3849 3850 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3851 DiagnoseUseOfDecl(Dtor, Location); 3852 } 3853} 3854 3855void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3856 if (!CDtorDecl) 3857 return; 3858 3859 if (CXXConstructorDecl *Constructor 3860 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3861 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3862} 3863 3864bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3865 unsigned DiagID, AbstractDiagSelID SelID) { 3866 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3867 unsigned DiagID; 3868 AbstractDiagSelID SelID; 3869 3870 public: 3871 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3872 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3873 3874 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3875 if (Suppressed) return; 3876 if (SelID == -1) 3877 S.Diag(Loc, DiagID) << T; 3878 else 3879 S.Diag(Loc, DiagID) << SelID << T; 3880 } 3881 } Diagnoser(DiagID, SelID); 3882 3883 return RequireNonAbstractType(Loc, T, Diagnoser); 3884} 3885 3886bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3887 TypeDiagnoser &Diagnoser) { 3888 if (!getLangOpts().CPlusPlus) 3889 return false; 3890 3891 if (const ArrayType *AT = Context.getAsArrayType(T)) 3892 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3893 3894 if (const PointerType *PT = T->getAs<PointerType>()) { 3895 // Find the innermost pointer type. 3896 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3897 PT = T; 3898 3899 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3900 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3901 } 3902 3903 const RecordType *RT = T->getAs<RecordType>(); 3904 if (!RT) 3905 return false; 3906 3907 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3908 3909 // We can't answer whether something is abstract until it has a 3910 // definition. If it's currently being defined, we'll walk back 3911 // over all the declarations when we have a full definition. 3912 const CXXRecordDecl *Def = RD->getDefinition(); 3913 if (!Def || Def->isBeingDefined()) 3914 return false; 3915 3916 if (!RD->isAbstract()) 3917 return false; 3918 3919 Diagnoser.diagnose(*this, Loc, T); 3920 DiagnoseAbstractType(RD); 3921 3922 return true; 3923} 3924 3925void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3926 // Check if we've already emitted the list of pure virtual functions 3927 // for this class. 3928 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3929 return; 3930 3931 // If the diagnostic is suppressed, don't emit the notes. We're only 3932 // going to emit them once, so try to attach them to a diagnostic we're 3933 // actually going to show. 3934 if (Diags.isLastDiagnosticIgnored()) 3935 return; 3936 3937 CXXFinalOverriderMap FinalOverriders; 3938 RD->getFinalOverriders(FinalOverriders); 3939 3940 // Keep a set of seen pure methods so we won't diagnose the same method 3941 // more than once. 3942 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3943 3944 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3945 MEnd = FinalOverriders.end(); 3946 M != MEnd; 3947 ++M) { 3948 for (OverridingMethods::iterator SO = M->second.begin(), 3949 SOEnd = M->second.end(); 3950 SO != SOEnd; ++SO) { 3951 // C++ [class.abstract]p4: 3952 // A class is abstract if it contains or inherits at least one 3953 // pure virtual function for which the final overrider is pure 3954 // virtual. 3955 3956 // 3957 if (SO->second.size() != 1) 3958 continue; 3959 3960 if (!SO->second.front().Method->isPure()) 3961 continue; 3962 3963 if (!SeenPureMethods.insert(SO->second.front().Method)) 3964 continue; 3965 3966 Diag(SO->second.front().Method->getLocation(), 3967 diag::note_pure_virtual_function) 3968 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3969 } 3970 } 3971 3972 if (!PureVirtualClassDiagSet) 3973 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3974 PureVirtualClassDiagSet->insert(RD); 3975} 3976 3977namespace { 3978struct AbstractUsageInfo { 3979 Sema &S; 3980 CXXRecordDecl *Record; 3981 CanQualType AbstractType; 3982 bool Invalid; 3983 3984 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3985 : S(S), Record(Record), 3986 AbstractType(S.Context.getCanonicalType( 3987 S.Context.getTypeDeclType(Record))), 3988 Invalid(false) {} 3989 3990 void DiagnoseAbstractType() { 3991 if (Invalid) return; 3992 S.DiagnoseAbstractType(Record); 3993 Invalid = true; 3994 } 3995 3996 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3997}; 3998 3999struct CheckAbstractUsage { 4000 AbstractUsageInfo &Info; 4001 const NamedDecl *Ctx; 4002 4003 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4004 : Info(Info), Ctx(Ctx) {} 4005 4006 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4007 switch (TL.getTypeLocClass()) { 4008#define ABSTRACT_TYPELOC(CLASS, PARENT) 4009#define TYPELOC(CLASS, PARENT) \ 4010 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4011#include "clang/AST/TypeLocNodes.def" 4012 } 4013 } 4014 4015 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4016 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 4017 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4018 if (!TL.getArg(I)) 4019 continue; 4020 4021 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 4022 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4023 } 4024 } 4025 4026 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4027 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4028 } 4029 4030 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4031 // Visit the type parameters from a permissive context. 4032 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4033 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4034 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4035 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4036 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4037 // TODO: other template argument types? 4038 } 4039 } 4040 4041 // Visit pointee types from a permissive context. 4042#define CheckPolymorphic(Type) \ 4043 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4044 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4045 } 4046 CheckPolymorphic(PointerTypeLoc) 4047 CheckPolymorphic(ReferenceTypeLoc) 4048 CheckPolymorphic(MemberPointerTypeLoc) 4049 CheckPolymorphic(BlockPointerTypeLoc) 4050 CheckPolymorphic(AtomicTypeLoc) 4051 4052 /// Handle all the types we haven't given a more specific 4053 /// implementation for above. 4054 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4055 // Every other kind of type that we haven't called out already 4056 // that has an inner type is either (1) sugar or (2) contains that 4057 // inner type in some way as a subobject. 4058 if (TypeLoc Next = TL.getNextTypeLoc()) 4059 return Visit(Next, Sel); 4060 4061 // If there's no inner type and we're in a permissive context, 4062 // don't diagnose. 4063 if (Sel == Sema::AbstractNone) return; 4064 4065 // Check whether the type matches the abstract type. 4066 QualType T = TL.getType(); 4067 if (T->isArrayType()) { 4068 Sel = Sema::AbstractArrayType; 4069 T = Info.S.Context.getBaseElementType(T); 4070 } 4071 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4072 if (CT != Info.AbstractType) return; 4073 4074 // It matched; do some magic. 4075 if (Sel == Sema::AbstractArrayType) { 4076 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4077 << T << TL.getSourceRange(); 4078 } else { 4079 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4080 << Sel << T << TL.getSourceRange(); 4081 } 4082 Info.DiagnoseAbstractType(); 4083 } 4084}; 4085 4086void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4087 Sema::AbstractDiagSelID Sel) { 4088 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4089} 4090 4091} 4092 4093/// Check for invalid uses of an abstract type in a method declaration. 4094static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4095 CXXMethodDecl *MD) { 4096 // No need to do the check on definitions, which require that 4097 // the return/param types be complete. 4098 if (MD->doesThisDeclarationHaveABody()) 4099 return; 4100 4101 // For safety's sake, just ignore it if we don't have type source 4102 // information. This should never happen for non-implicit methods, 4103 // but... 4104 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4105 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4106} 4107 4108/// Check for invalid uses of an abstract type within a class definition. 4109static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4110 CXXRecordDecl *RD) { 4111 for (CXXRecordDecl::decl_iterator 4112 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4113 Decl *D = *I; 4114 if (D->isImplicit()) continue; 4115 4116 // Methods and method templates. 4117 if (isa<CXXMethodDecl>(D)) { 4118 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4119 } else if (isa<FunctionTemplateDecl>(D)) { 4120 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4121 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4122 4123 // Fields and static variables. 4124 } else if (isa<FieldDecl>(D)) { 4125 FieldDecl *FD = cast<FieldDecl>(D); 4126 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4127 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4128 } else if (isa<VarDecl>(D)) { 4129 VarDecl *VD = cast<VarDecl>(D); 4130 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4131 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4132 4133 // Nested classes and class templates. 4134 } else if (isa<CXXRecordDecl>(D)) { 4135 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4136 } else if (isa<ClassTemplateDecl>(D)) { 4137 CheckAbstractClassUsage(Info, 4138 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4139 } 4140 } 4141} 4142 4143/// \brief Perform semantic checks on a class definition that has been 4144/// completing, introducing implicitly-declared members, checking for 4145/// abstract types, etc. 4146void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4147 if (!Record) 4148 return; 4149 4150 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4151 AbstractUsageInfo Info(*this, Record); 4152 CheckAbstractClassUsage(Info, Record); 4153 } 4154 4155 // If this is not an aggregate type and has no user-declared constructor, 4156 // complain about any non-static data members of reference or const scalar 4157 // type, since they will never get initializers. 4158 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4159 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4160 !Record->isLambda()) { 4161 bool Complained = false; 4162 for (RecordDecl::field_iterator F = Record->field_begin(), 4163 FEnd = Record->field_end(); 4164 F != FEnd; ++F) { 4165 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4166 continue; 4167 4168 if (F->getType()->isReferenceType() || 4169 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4170 if (!Complained) { 4171 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4172 << Record->getTagKind() << Record; 4173 Complained = true; 4174 } 4175 4176 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4177 << F->getType()->isReferenceType() 4178 << F->getDeclName(); 4179 } 4180 } 4181 } 4182 4183 if (Record->isDynamicClass() && !Record->isDependentType()) 4184 DynamicClasses.push_back(Record); 4185 4186 if (Record->getIdentifier()) { 4187 // C++ [class.mem]p13: 4188 // If T is the name of a class, then each of the following shall have a 4189 // name different from T: 4190 // - every member of every anonymous union that is a member of class T. 4191 // 4192 // C++ [class.mem]p14: 4193 // In addition, if class T has a user-declared constructor (12.1), every 4194 // non-static data member of class T shall have a name different from T. 4195 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4196 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4197 ++I) { 4198 NamedDecl *D = *I; 4199 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4200 isa<IndirectFieldDecl>(D)) { 4201 Diag(D->getLocation(), diag::err_member_name_of_class) 4202 << D->getDeclName(); 4203 break; 4204 } 4205 } 4206 } 4207 4208 // Warn if the class has virtual methods but non-virtual public destructor. 4209 if (Record->isPolymorphic() && !Record->isDependentType()) { 4210 CXXDestructorDecl *dtor = Record->getDestructor(); 4211 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4212 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4213 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4214 } 4215 4216 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4217 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4218 DiagnoseAbstractType(Record); 4219 } 4220 4221 if (!Record->isDependentType()) { 4222 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4223 MEnd = Record->method_end(); 4224 M != MEnd; ++M) { 4225 // See if a method overloads virtual methods in a base 4226 // class without overriding any. 4227 if (!M->isStatic()) 4228 DiagnoseHiddenVirtualMethods(Record, *M); 4229 4230 // Check whether the explicitly-defaulted special members are valid. 4231 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4232 CheckExplicitlyDefaultedSpecialMember(*M); 4233 4234 // For an explicitly defaulted or deleted special member, we defer 4235 // determining triviality until the class is complete. That time is now! 4236 if (!M->isImplicit() && !M->isUserProvided()) { 4237 CXXSpecialMember CSM = getSpecialMember(*M); 4238 if (CSM != CXXInvalid) { 4239 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4240 4241 // Inform the class that we've finished declaring this member. 4242 Record->finishedDefaultedOrDeletedMember(*M); 4243 } 4244 } 4245 } 4246 } 4247 4248 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4249 // function that is not a constructor declares that member function to be 4250 // const. [...] The class of which that function is a member shall be 4251 // a literal type. 4252 // 4253 // If the class has virtual bases, any constexpr members will already have 4254 // been diagnosed by the checks performed on the member declaration, so 4255 // suppress this (less useful) diagnostic. 4256 // 4257 // We delay this until we know whether an explicitly-defaulted (or deleted) 4258 // destructor for the class is trivial. 4259 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4260 !Record->isLiteral() && !Record->getNumVBases()) { 4261 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4262 MEnd = Record->method_end(); 4263 M != MEnd; ++M) { 4264 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4265 switch (Record->getTemplateSpecializationKind()) { 4266 case TSK_ImplicitInstantiation: 4267 case TSK_ExplicitInstantiationDeclaration: 4268 case TSK_ExplicitInstantiationDefinition: 4269 // If a template instantiates to a non-literal type, but its members 4270 // instantiate to constexpr functions, the template is technically 4271 // ill-formed, but we allow it for sanity. 4272 continue; 4273 4274 case TSK_Undeclared: 4275 case TSK_ExplicitSpecialization: 4276 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4277 diag::err_constexpr_method_non_literal); 4278 break; 4279 } 4280 4281 // Only produce one error per class. 4282 break; 4283 } 4284 } 4285 } 4286 4287 // Declare inheriting constructors. We do this eagerly here because: 4288 // - The standard requires an eager diagnostic for conflicting inheriting 4289 // constructors from different classes. 4290 // - The lazy declaration of the other implicit constructors is so as to not 4291 // waste space and performance on classes that are not meant to be 4292 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4293 // have inheriting constructors. 4294 DeclareInheritingConstructors(Record); 4295} 4296 4297/// Is the special member function which would be selected to perform the 4298/// specified operation on the specified class type a constexpr constructor? 4299static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4300 Sema::CXXSpecialMember CSM, 4301 bool ConstArg) { 4302 Sema::SpecialMemberOverloadResult *SMOR = 4303 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4304 false, false, false, false); 4305 if (!SMOR || !SMOR->getMethod()) 4306 // A constructor we wouldn't select can't be "involved in initializing" 4307 // anything. 4308 return true; 4309 return SMOR->getMethod()->isConstexpr(); 4310} 4311 4312/// Determine whether the specified special member function would be constexpr 4313/// if it were implicitly defined. 4314static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4315 Sema::CXXSpecialMember CSM, 4316 bool ConstArg) { 4317 if (!S.getLangOpts().CPlusPlus11) 4318 return false; 4319 4320 // C++11 [dcl.constexpr]p4: 4321 // In the definition of a constexpr constructor [...] 4322 bool Ctor = true; 4323 switch (CSM) { 4324 case Sema::CXXDefaultConstructor: 4325 // Since default constructor lookup is essentially trivial (and cannot 4326 // involve, for instance, template instantiation), we compute whether a 4327 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4328 // 4329 // This is important for performance; we need to know whether the default 4330 // constructor is constexpr to determine whether the type is a literal type. 4331 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4332 4333 case Sema::CXXCopyConstructor: 4334 case Sema::CXXMoveConstructor: 4335 // For copy or move constructors, we need to perform overload resolution. 4336 break; 4337 4338 case Sema::CXXCopyAssignment: 4339 case Sema::CXXMoveAssignment: 4340 if (!S.getLangOpts().CPlusPlus1y) 4341 return false; 4342 // In C++1y, we need to perform overload resolution. 4343 Ctor = false; 4344 break; 4345 4346 case Sema::CXXDestructor: 4347 case Sema::CXXInvalid: 4348 return false; 4349 } 4350 4351 // -- if the class is a non-empty union, or for each non-empty anonymous 4352 // union member of a non-union class, exactly one non-static data member 4353 // shall be initialized; [DR1359] 4354 // 4355 // If we squint, this is guaranteed, since exactly one non-static data member 4356 // will be initialized (if the constructor isn't deleted), we just don't know 4357 // which one. 4358 if (Ctor && ClassDecl->isUnion()) 4359 return true; 4360 4361 // -- the class shall not have any virtual base classes; 4362 if (Ctor && ClassDecl->getNumVBases()) 4363 return false; 4364 4365 // C++1y [class.copy]p26: 4366 // -- [the class] is a literal type, and 4367 if (!Ctor && !ClassDecl->isLiteral()) 4368 return false; 4369 4370 // -- every constructor involved in initializing [...] base class 4371 // sub-objects shall be a constexpr constructor; 4372 // -- the assignment operator selected to copy/move each direct base 4373 // class is a constexpr function, and 4374 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4375 BEnd = ClassDecl->bases_end(); 4376 B != BEnd; ++B) { 4377 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4378 if (!BaseType) continue; 4379 4380 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4381 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4382 return false; 4383 } 4384 4385 // -- every constructor involved in initializing non-static data members 4386 // [...] shall be a constexpr constructor; 4387 // -- every non-static data member and base class sub-object shall be 4388 // initialized 4389 // -- for each non-stastic data member of X that is of class type (or array 4390 // thereof), the assignment operator selected to copy/move that member is 4391 // a constexpr function 4392 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4393 FEnd = ClassDecl->field_end(); 4394 F != FEnd; ++F) { 4395 if (F->isInvalidDecl()) 4396 continue; 4397 if (const RecordType *RecordTy = 4398 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4399 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4400 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4401 return false; 4402 } 4403 } 4404 4405 // All OK, it's constexpr! 4406 return true; 4407} 4408 4409static Sema::ImplicitExceptionSpecification 4410computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4411 switch (S.getSpecialMember(MD)) { 4412 case Sema::CXXDefaultConstructor: 4413 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4414 case Sema::CXXCopyConstructor: 4415 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4416 case Sema::CXXCopyAssignment: 4417 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4418 case Sema::CXXMoveConstructor: 4419 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4420 case Sema::CXXMoveAssignment: 4421 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4422 case Sema::CXXDestructor: 4423 return S.ComputeDefaultedDtorExceptionSpec(MD); 4424 case Sema::CXXInvalid: 4425 break; 4426 } 4427 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4428 "only special members have implicit exception specs"); 4429 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4430} 4431 4432static void 4433updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4434 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4435 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4436 ExceptSpec.getEPI(EPI); 4437 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4438 FPT->getArgTypes(), EPI)); 4439} 4440 4441void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4442 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4443 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4444 return; 4445 4446 // Evaluate the exception specification. 4447 ImplicitExceptionSpecification ExceptSpec = 4448 computeImplicitExceptionSpec(*this, Loc, MD); 4449 4450 // Update the type of the special member to use it. 4451 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4452 4453 // A user-provided destructor can be defined outside the class. When that 4454 // happens, be sure to update the exception specification on both 4455 // declarations. 4456 const FunctionProtoType *CanonicalFPT = 4457 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4458 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4459 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4460 CanonicalFPT, ExceptSpec); 4461} 4462 4463void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4464 CXXRecordDecl *RD = MD->getParent(); 4465 CXXSpecialMember CSM = getSpecialMember(MD); 4466 4467 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4468 "not an explicitly-defaulted special member"); 4469 4470 // Whether this was the first-declared instance of the constructor. 4471 // This affects whether we implicitly add an exception spec and constexpr. 4472 bool First = MD == MD->getCanonicalDecl(); 4473 4474 bool HadError = false; 4475 4476 // C++11 [dcl.fct.def.default]p1: 4477 // A function that is explicitly defaulted shall 4478 // -- be a special member function (checked elsewhere), 4479 // -- have the same type (except for ref-qualifiers, and except that a 4480 // copy operation can take a non-const reference) as an implicit 4481 // declaration, and 4482 // -- not have default arguments. 4483 unsigned ExpectedParams = 1; 4484 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4485 ExpectedParams = 0; 4486 if (MD->getNumParams() != ExpectedParams) { 4487 // This also checks for default arguments: a copy or move constructor with a 4488 // default argument is classified as a default constructor, and assignment 4489 // operations and destructors can't have default arguments. 4490 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4491 << CSM << MD->getSourceRange(); 4492 HadError = true; 4493 } else if (MD->isVariadic()) { 4494 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4495 << CSM << MD->getSourceRange(); 4496 HadError = true; 4497 } 4498 4499 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4500 4501 bool CanHaveConstParam = false; 4502 if (CSM == CXXCopyConstructor) 4503 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4504 else if (CSM == CXXCopyAssignment) 4505 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4506 4507 QualType ReturnType = Context.VoidTy; 4508 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4509 // Check for return type matching. 4510 ReturnType = Type->getResultType(); 4511 QualType ExpectedReturnType = 4512 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4513 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4514 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4515 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4516 HadError = true; 4517 } 4518 4519 // A defaulted special member cannot have cv-qualifiers. 4520 if (Type->getTypeQuals()) { 4521 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4522 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4523 HadError = true; 4524 } 4525 } 4526 4527 // Check for parameter type matching. 4528 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4529 bool HasConstParam = false; 4530 if (ExpectedParams && ArgType->isReferenceType()) { 4531 // Argument must be reference to possibly-const T. 4532 QualType ReferentType = ArgType->getPointeeType(); 4533 HasConstParam = ReferentType.isConstQualified(); 4534 4535 if (ReferentType.isVolatileQualified()) { 4536 Diag(MD->getLocation(), 4537 diag::err_defaulted_special_member_volatile_param) << CSM; 4538 HadError = true; 4539 } 4540 4541 if (HasConstParam && !CanHaveConstParam) { 4542 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4543 Diag(MD->getLocation(), 4544 diag::err_defaulted_special_member_copy_const_param) 4545 << (CSM == CXXCopyAssignment); 4546 // FIXME: Explain why this special member can't be const. 4547 } else { 4548 Diag(MD->getLocation(), 4549 diag::err_defaulted_special_member_move_const_param) 4550 << (CSM == CXXMoveAssignment); 4551 } 4552 HadError = true; 4553 } 4554 } else if (ExpectedParams) { 4555 // A copy assignment operator can take its argument by value, but a 4556 // defaulted one cannot. 4557 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4558 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4559 HadError = true; 4560 } 4561 4562 // C++11 [dcl.fct.def.default]p2: 4563 // An explicitly-defaulted function may be declared constexpr only if it 4564 // would have been implicitly declared as constexpr, 4565 // Do not apply this rule to members of class templates, since core issue 1358 4566 // makes such functions always instantiate to constexpr functions. For 4567 // functions which cannot be constexpr (for non-constructors in C++11 and for 4568 // destructors in C++1y), this is checked elsewhere. 4569 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4570 HasConstParam); 4571 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4572 : isa<CXXConstructorDecl>(MD)) && 4573 MD->isConstexpr() && !Constexpr && 4574 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4575 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4576 // FIXME: Explain why the special member can't be constexpr. 4577 HadError = true; 4578 } 4579 4580 // and may have an explicit exception-specification only if it is compatible 4581 // with the exception-specification on the implicit declaration. 4582 if (Type->hasExceptionSpec()) { 4583 // Delay the check if this is the first declaration of the special member, 4584 // since we may not have parsed some necessary in-class initializers yet. 4585 if (First) { 4586 // If the exception specification needs to be instantiated, do so now, 4587 // before we clobber it with an EST_Unevaluated specification below. 4588 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4589 InstantiateExceptionSpec(MD->getLocStart(), MD); 4590 Type = MD->getType()->getAs<FunctionProtoType>(); 4591 } 4592 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4593 } else 4594 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4595 } 4596 4597 // If a function is explicitly defaulted on its first declaration, 4598 if (First) { 4599 // -- it is implicitly considered to be constexpr if the implicit 4600 // definition would be, 4601 MD->setConstexpr(Constexpr); 4602 4603 // -- it is implicitly considered to have the same exception-specification 4604 // as if it had been implicitly declared, 4605 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4606 EPI.ExceptionSpecType = EST_Unevaluated; 4607 EPI.ExceptionSpecDecl = MD; 4608 MD->setType(Context.getFunctionType(ReturnType, 4609 ArrayRef<QualType>(&ArgType, 4610 ExpectedParams), 4611 EPI)); 4612 } 4613 4614 if (ShouldDeleteSpecialMember(MD, CSM)) { 4615 if (First) { 4616 SetDeclDeleted(MD, MD->getLocation()); 4617 } else { 4618 // C++11 [dcl.fct.def.default]p4: 4619 // [For a] user-provided explicitly-defaulted function [...] if such a 4620 // function is implicitly defined as deleted, the program is ill-formed. 4621 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4622 HadError = true; 4623 } 4624 } 4625 4626 if (HadError) 4627 MD->setInvalidDecl(); 4628} 4629 4630/// Check whether the exception specification provided for an 4631/// explicitly-defaulted special member matches the exception specification 4632/// that would have been generated for an implicit special member, per 4633/// C++11 [dcl.fct.def.default]p2. 4634void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4635 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4636 // Compute the implicit exception specification. 4637 FunctionProtoType::ExtProtoInfo EPI; 4638 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4639 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4640 Context.getFunctionType(Context.VoidTy, None, EPI)); 4641 4642 // Ensure that it matches. 4643 CheckEquivalentExceptionSpec( 4644 PDiag(diag::err_incorrect_defaulted_exception_spec) 4645 << getSpecialMember(MD), PDiag(), 4646 ImplicitType, SourceLocation(), 4647 SpecifiedType, MD->getLocation()); 4648} 4649 4650void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4651 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4652 I != N; ++I) 4653 CheckExplicitlyDefaultedMemberExceptionSpec( 4654 DelayedDefaultedMemberExceptionSpecs[I].first, 4655 DelayedDefaultedMemberExceptionSpecs[I].second); 4656 4657 DelayedDefaultedMemberExceptionSpecs.clear(); 4658} 4659 4660namespace { 4661struct SpecialMemberDeletionInfo { 4662 Sema &S; 4663 CXXMethodDecl *MD; 4664 Sema::CXXSpecialMember CSM; 4665 bool Diagnose; 4666 4667 // Properties of the special member, computed for convenience. 4668 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4669 SourceLocation Loc; 4670 4671 bool AllFieldsAreConst; 4672 4673 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4674 Sema::CXXSpecialMember CSM, bool Diagnose) 4675 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4676 IsConstructor(false), IsAssignment(false), IsMove(false), 4677 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4678 AllFieldsAreConst(true) { 4679 switch (CSM) { 4680 case Sema::CXXDefaultConstructor: 4681 case Sema::CXXCopyConstructor: 4682 IsConstructor = true; 4683 break; 4684 case Sema::CXXMoveConstructor: 4685 IsConstructor = true; 4686 IsMove = true; 4687 break; 4688 case Sema::CXXCopyAssignment: 4689 IsAssignment = true; 4690 break; 4691 case Sema::CXXMoveAssignment: 4692 IsAssignment = true; 4693 IsMove = true; 4694 break; 4695 case Sema::CXXDestructor: 4696 break; 4697 case Sema::CXXInvalid: 4698 llvm_unreachable("invalid special member kind"); 4699 } 4700 4701 if (MD->getNumParams()) { 4702 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4703 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4704 } 4705 } 4706 4707 bool inUnion() const { return MD->getParent()->isUnion(); } 4708 4709 /// Look up the corresponding special member in the given class. 4710 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4711 unsigned Quals) { 4712 unsigned TQ = MD->getTypeQualifiers(); 4713 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4714 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4715 Quals = 0; 4716 return S.LookupSpecialMember(Class, CSM, 4717 ConstArg || (Quals & Qualifiers::Const), 4718 VolatileArg || (Quals & Qualifiers::Volatile), 4719 MD->getRefQualifier() == RQ_RValue, 4720 TQ & Qualifiers::Const, 4721 TQ & Qualifiers::Volatile); 4722 } 4723 4724 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4725 4726 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4727 bool shouldDeleteForField(FieldDecl *FD); 4728 bool shouldDeleteForAllConstMembers(); 4729 4730 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4731 unsigned Quals); 4732 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4733 Sema::SpecialMemberOverloadResult *SMOR, 4734 bool IsDtorCallInCtor); 4735 4736 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4737}; 4738} 4739 4740/// Is the given special member inaccessible when used on the given 4741/// sub-object. 4742bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4743 CXXMethodDecl *target) { 4744 /// If we're operating on a base class, the object type is the 4745 /// type of this special member. 4746 QualType objectTy; 4747 AccessSpecifier access = target->getAccess(); 4748 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4749 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4750 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4751 4752 // If we're operating on a field, the object type is the type of the field. 4753 } else { 4754 objectTy = S.Context.getTypeDeclType(target->getParent()); 4755 } 4756 4757 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4758} 4759 4760/// Check whether we should delete a special member due to the implicit 4761/// definition containing a call to a special member of a subobject. 4762bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4763 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4764 bool IsDtorCallInCtor) { 4765 CXXMethodDecl *Decl = SMOR->getMethod(); 4766 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4767 4768 int DiagKind = -1; 4769 4770 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4771 DiagKind = !Decl ? 0 : 1; 4772 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4773 DiagKind = 2; 4774 else if (!isAccessible(Subobj, Decl)) 4775 DiagKind = 3; 4776 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4777 !Decl->isTrivial()) { 4778 // A member of a union must have a trivial corresponding special member. 4779 // As a weird special case, a destructor call from a union's constructor 4780 // must be accessible and non-deleted, but need not be trivial. Such a 4781 // destructor is never actually called, but is semantically checked as 4782 // if it were. 4783 DiagKind = 4; 4784 } 4785 4786 if (DiagKind == -1) 4787 return false; 4788 4789 if (Diagnose) { 4790 if (Field) { 4791 S.Diag(Field->getLocation(), 4792 diag::note_deleted_special_member_class_subobject) 4793 << CSM << MD->getParent() << /*IsField*/true 4794 << Field << DiagKind << IsDtorCallInCtor; 4795 } else { 4796 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4797 S.Diag(Base->getLocStart(), 4798 diag::note_deleted_special_member_class_subobject) 4799 << CSM << MD->getParent() << /*IsField*/false 4800 << Base->getType() << DiagKind << IsDtorCallInCtor; 4801 } 4802 4803 if (DiagKind == 1) 4804 S.NoteDeletedFunction(Decl); 4805 // FIXME: Explain inaccessibility if DiagKind == 3. 4806 } 4807 4808 return true; 4809} 4810 4811/// Check whether we should delete a special member function due to having a 4812/// direct or virtual base class or non-static data member of class type M. 4813bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4814 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4815 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4816 4817 // C++11 [class.ctor]p5: 4818 // -- any direct or virtual base class, or non-static data member with no 4819 // brace-or-equal-initializer, has class type M (or array thereof) and 4820 // either M has no default constructor or overload resolution as applied 4821 // to M's default constructor results in an ambiguity or in a function 4822 // that is deleted or inaccessible 4823 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4824 // -- a direct or virtual base class B that cannot be copied/moved because 4825 // overload resolution, as applied to B's corresponding special member, 4826 // results in an ambiguity or a function that is deleted or inaccessible 4827 // from the defaulted special member 4828 // C++11 [class.dtor]p5: 4829 // -- any direct or virtual base class [...] has a type with a destructor 4830 // that is deleted or inaccessible 4831 if (!(CSM == Sema::CXXDefaultConstructor && 4832 Field && Field->hasInClassInitializer()) && 4833 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4834 return true; 4835 4836 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4837 // -- any direct or virtual base class or non-static data member has a 4838 // type with a destructor that is deleted or inaccessible 4839 if (IsConstructor) { 4840 Sema::SpecialMemberOverloadResult *SMOR = 4841 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4842 false, false, false, false, false); 4843 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4844 return true; 4845 } 4846 4847 return false; 4848} 4849 4850/// Check whether we should delete a special member function due to the class 4851/// having a particular direct or virtual base class. 4852bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4853 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4854 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4855} 4856 4857/// Check whether we should delete a special member function due to the class 4858/// having a particular non-static data member. 4859bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4860 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4861 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4862 4863 if (CSM == Sema::CXXDefaultConstructor) { 4864 // For a default constructor, all references must be initialized in-class 4865 // and, if a union, it must have a non-const member. 4866 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4867 if (Diagnose) 4868 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4869 << MD->getParent() << FD << FieldType << /*Reference*/0; 4870 return true; 4871 } 4872 // C++11 [class.ctor]p5: any non-variant non-static data member of 4873 // const-qualified type (or array thereof) with no 4874 // brace-or-equal-initializer does not have a user-provided default 4875 // constructor. 4876 if (!inUnion() && FieldType.isConstQualified() && 4877 !FD->hasInClassInitializer() && 4878 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4879 if (Diagnose) 4880 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4881 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4882 return true; 4883 } 4884 4885 if (inUnion() && !FieldType.isConstQualified()) 4886 AllFieldsAreConst = false; 4887 } else if (CSM == Sema::CXXCopyConstructor) { 4888 // For a copy constructor, data members must not be of rvalue reference 4889 // type. 4890 if (FieldType->isRValueReferenceType()) { 4891 if (Diagnose) 4892 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4893 << MD->getParent() << FD << FieldType; 4894 return true; 4895 } 4896 } else if (IsAssignment) { 4897 // For an assignment operator, data members must not be of reference type. 4898 if (FieldType->isReferenceType()) { 4899 if (Diagnose) 4900 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4901 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4902 return true; 4903 } 4904 if (!FieldRecord && FieldType.isConstQualified()) { 4905 // C++11 [class.copy]p23: 4906 // -- a non-static data member of const non-class type (or array thereof) 4907 if (Diagnose) 4908 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4909 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4910 return true; 4911 } 4912 } 4913 4914 if (FieldRecord) { 4915 // Some additional restrictions exist on the variant members. 4916 if (!inUnion() && FieldRecord->isUnion() && 4917 FieldRecord->isAnonymousStructOrUnion()) { 4918 bool AllVariantFieldsAreConst = true; 4919 4920 // FIXME: Handle anonymous unions declared within anonymous unions. 4921 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4922 UE = FieldRecord->field_end(); 4923 UI != UE; ++UI) { 4924 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4925 4926 if (!UnionFieldType.isConstQualified()) 4927 AllVariantFieldsAreConst = false; 4928 4929 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4930 if (UnionFieldRecord && 4931 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4932 UnionFieldType.getCVRQualifiers())) 4933 return true; 4934 } 4935 4936 // At least one member in each anonymous union must be non-const 4937 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4938 FieldRecord->field_begin() != FieldRecord->field_end()) { 4939 if (Diagnose) 4940 S.Diag(FieldRecord->getLocation(), 4941 diag::note_deleted_default_ctor_all_const) 4942 << MD->getParent() << /*anonymous union*/1; 4943 return true; 4944 } 4945 4946 // Don't check the implicit member of the anonymous union type. 4947 // This is technically non-conformant, but sanity demands it. 4948 return false; 4949 } 4950 4951 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4952 FieldType.getCVRQualifiers())) 4953 return true; 4954 } 4955 4956 return false; 4957} 4958 4959/// C++11 [class.ctor] p5: 4960/// A defaulted default constructor for a class X is defined as deleted if 4961/// X is a union and all of its variant members are of const-qualified type. 4962bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4963 // This is a silly definition, because it gives an empty union a deleted 4964 // default constructor. Don't do that. 4965 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4966 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4967 if (Diagnose) 4968 S.Diag(MD->getParent()->getLocation(), 4969 diag::note_deleted_default_ctor_all_const) 4970 << MD->getParent() << /*not anonymous union*/0; 4971 return true; 4972 } 4973 return false; 4974} 4975 4976/// Determine whether a defaulted special member function should be defined as 4977/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4978/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4979bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4980 bool Diagnose) { 4981 if (MD->isInvalidDecl()) 4982 return false; 4983 CXXRecordDecl *RD = MD->getParent(); 4984 assert(!RD->isDependentType() && "do deletion after instantiation"); 4985 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4986 return false; 4987 4988 // C++11 [expr.lambda.prim]p19: 4989 // The closure type associated with a lambda-expression has a 4990 // deleted (8.4.3) default constructor and a deleted copy 4991 // assignment operator. 4992 if (RD->isLambda() && 4993 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4994 if (Diagnose) 4995 Diag(RD->getLocation(), diag::note_lambda_decl); 4996 return true; 4997 } 4998 4999 // For an anonymous struct or union, the copy and assignment special members 5000 // will never be used, so skip the check. For an anonymous union declared at 5001 // namespace scope, the constructor and destructor are used. 5002 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5003 RD->isAnonymousStructOrUnion()) 5004 return false; 5005 5006 // C++11 [class.copy]p7, p18: 5007 // If the class definition declares a move constructor or move assignment 5008 // operator, an implicitly declared copy constructor or copy assignment 5009 // operator is defined as deleted. 5010 if (MD->isImplicit() && 5011 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5012 CXXMethodDecl *UserDeclaredMove = 0; 5013 5014 // In Microsoft mode, a user-declared move only causes the deletion of the 5015 // corresponding copy operation, not both copy operations. 5016 if (RD->hasUserDeclaredMoveConstructor() && 5017 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 5018 if (!Diagnose) return true; 5019 5020 // Find any user-declared move constructor. 5021 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 5022 E = RD->ctor_end(); I != E; ++I) { 5023 if (I->isMoveConstructor()) { 5024 UserDeclaredMove = *I; 5025 break; 5026 } 5027 } 5028 assert(UserDeclaredMove); 5029 } else if (RD->hasUserDeclaredMoveAssignment() && 5030 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 5031 if (!Diagnose) return true; 5032 5033 // Find any user-declared move assignment operator. 5034 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5035 E = RD->method_end(); I != E; ++I) { 5036 if (I->isMoveAssignmentOperator()) { 5037 UserDeclaredMove = *I; 5038 break; 5039 } 5040 } 5041 assert(UserDeclaredMove); 5042 } 5043 5044 if (UserDeclaredMove) { 5045 Diag(UserDeclaredMove->getLocation(), 5046 diag::note_deleted_copy_user_declared_move) 5047 << (CSM == CXXCopyAssignment) << RD 5048 << UserDeclaredMove->isMoveAssignmentOperator(); 5049 return true; 5050 } 5051 } 5052 5053 // Do access control from the special member function 5054 ContextRAII MethodContext(*this, MD); 5055 5056 // C++11 [class.dtor]p5: 5057 // -- for a virtual destructor, lookup of the non-array deallocation function 5058 // results in an ambiguity or in a function that is deleted or inaccessible 5059 if (CSM == CXXDestructor && MD->isVirtual()) { 5060 FunctionDecl *OperatorDelete = 0; 5061 DeclarationName Name = 5062 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5063 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5064 OperatorDelete, false)) { 5065 if (Diagnose) 5066 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5067 return true; 5068 } 5069 } 5070 5071 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5072 5073 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5074 BE = RD->bases_end(); BI != BE; ++BI) 5075 if (!BI->isVirtual() && 5076 SMI.shouldDeleteForBase(BI)) 5077 return true; 5078 5079 // Per DR1611, do not consider virtual bases of constructors of abstract 5080 // classes, since we are not going to construct them. 5081 if (!RD->isAbstract() || !SMI.IsConstructor) { 5082 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5083 BE = RD->vbases_end(); 5084 BI != BE; ++BI) 5085 if (SMI.shouldDeleteForBase(BI)) 5086 return true; 5087 } 5088 5089 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5090 FE = RD->field_end(); FI != FE; ++FI) 5091 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5092 SMI.shouldDeleteForField(*FI)) 5093 return true; 5094 5095 if (SMI.shouldDeleteForAllConstMembers()) 5096 return true; 5097 5098 return false; 5099} 5100 5101/// Perform lookup for a special member of the specified kind, and determine 5102/// whether it is trivial. If the triviality can be determined without the 5103/// lookup, skip it. This is intended for use when determining whether a 5104/// special member of a containing object is trivial, and thus does not ever 5105/// perform overload resolution for default constructors. 5106/// 5107/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5108/// member that was most likely to be intended to be trivial, if any. 5109static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5110 Sema::CXXSpecialMember CSM, unsigned Quals, 5111 CXXMethodDecl **Selected) { 5112 if (Selected) 5113 *Selected = 0; 5114 5115 switch (CSM) { 5116 case Sema::CXXInvalid: 5117 llvm_unreachable("not a special member"); 5118 5119 case Sema::CXXDefaultConstructor: 5120 // C++11 [class.ctor]p5: 5121 // A default constructor is trivial if: 5122 // - all the [direct subobjects] have trivial default constructors 5123 // 5124 // Note, no overload resolution is performed in this case. 5125 if (RD->hasTrivialDefaultConstructor()) 5126 return true; 5127 5128 if (Selected) { 5129 // If there's a default constructor which could have been trivial, dig it 5130 // out. Otherwise, if there's any user-provided default constructor, point 5131 // to that as an example of why there's not a trivial one. 5132 CXXConstructorDecl *DefCtor = 0; 5133 if (RD->needsImplicitDefaultConstructor()) 5134 S.DeclareImplicitDefaultConstructor(RD); 5135 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5136 CE = RD->ctor_end(); CI != CE; ++CI) { 5137 if (!CI->isDefaultConstructor()) 5138 continue; 5139 DefCtor = *CI; 5140 if (!DefCtor->isUserProvided()) 5141 break; 5142 } 5143 5144 *Selected = DefCtor; 5145 } 5146 5147 return false; 5148 5149 case Sema::CXXDestructor: 5150 // C++11 [class.dtor]p5: 5151 // A destructor is trivial if: 5152 // - all the direct [subobjects] have trivial destructors 5153 if (RD->hasTrivialDestructor()) 5154 return true; 5155 5156 if (Selected) { 5157 if (RD->needsImplicitDestructor()) 5158 S.DeclareImplicitDestructor(RD); 5159 *Selected = RD->getDestructor(); 5160 } 5161 5162 return false; 5163 5164 case Sema::CXXCopyConstructor: 5165 // C++11 [class.copy]p12: 5166 // A copy constructor is trivial if: 5167 // - the constructor selected to copy each direct [subobject] is trivial 5168 if (RD->hasTrivialCopyConstructor()) { 5169 if (Quals == Qualifiers::Const) 5170 // We must either select the trivial copy constructor or reach an 5171 // ambiguity; no need to actually perform overload resolution. 5172 return true; 5173 } else if (!Selected) { 5174 return false; 5175 } 5176 // In C++98, we are not supposed to perform overload resolution here, but we 5177 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5178 // cases like B as having a non-trivial copy constructor: 5179 // struct A { template<typename T> A(T&); }; 5180 // struct B { mutable A a; }; 5181 goto NeedOverloadResolution; 5182 5183 case Sema::CXXCopyAssignment: 5184 // C++11 [class.copy]p25: 5185 // A copy assignment operator is trivial if: 5186 // - the assignment operator selected to copy each direct [subobject] is 5187 // trivial 5188 if (RD->hasTrivialCopyAssignment()) { 5189 if (Quals == Qualifiers::Const) 5190 return true; 5191 } else if (!Selected) { 5192 return false; 5193 } 5194 // In C++98, we are not supposed to perform overload resolution here, but we 5195 // treat that as a language defect. 5196 goto NeedOverloadResolution; 5197 5198 case Sema::CXXMoveConstructor: 5199 case Sema::CXXMoveAssignment: 5200 NeedOverloadResolution: 5201 Sema::SpecialMemberOverloadResult *SMOR = 5202 S.LookupSpecialMember(RD, CSM, 5203 Quals & Qualifiers::Const, 5204 Quals & Qualifiers::Volatile, 5205 /*RValueThis*/false, /*ConstThis*/false, 5206 /*VolatileThis*/false); 5207 5208 // The standard doesn't describe how to behave if the lookup is ambiguous. 5209 // We treat it as not making the member non-trivial, just like the standard 5210 // mandates for the default constructor. This should rarely matter, because 5211 // the member will also be deleted. 5212 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5213 return true; 5214 5215 if (!SMOR->getMethod()) { 5216 assert(SMOR->getKind() == 5217 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5218 return false; 5219 } 5220 5221 // We deliberately don't check if we found a deleted special member. We're 5222 // not supposed to! 5223 if (Selected) 5224 *Selected = SMOR->getMethod(); 5225 return SMOR->getMethod()->isTrivial(); 5226 } 5227 5228 llvm_unreachable("unknown special method kind"); 5229} 5230 5231static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5232 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5233 CI != CE; ++CI) 5234 if (!CI->isImplicit()) 5235 return *CI; 5236 5237 // Look for constructor templates. 5238 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5239 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5240 if (CXXConstructorDecl *CD = 5241 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5242 return CD; 5243 } 5244 5245 return 0; 5246} 5247 5248/// The kind of subobject we are checking for triviality. The values of this 5249/// enumeration are used in diagnostics. 5250enum TrivialSubobjectKind { 5251 /// The subobject is a base class. 5252 TSK_BaseClass, 5253 /// The subobject is a non-static data member. 5254 TSK_Field, 5255 /// The object is actually the complete object. 5256 TSK_CompleteObject 5257}; 5258 5259/// Check whether the special member selected for a given type would be trivial. 5260static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5261 QualType SubType, 5262 Sema::CXXSpecialMember CSM, 5263 TrivialSubobjectKind Kind, 5264 bool Diagnose) { 5265 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5266 if (!SubRD) 5267 return true; 5268 5269 CXXMethodDecl *Selected; 5270 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5271 Diagnose ? &Selected : 0)) 5272 return true; 5273 5274 if (Diagnose) { 5275 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5276 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5277 << Kind << SubType.getUnqualifiedType(); 5278 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5279 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5280 } else if (!Selected) 5281 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5282 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5283 else if (Selected->isUserProvided()) { 5284 if (Kind == TSK_CompleteObject) 5285 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5286 << Kind << SubType.getUnqualifiedType() << CSM; 5287 else { 5288 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5289 << Kind << SubType.getUnqualifiedType() << CSM; 5290 S.Diag(Selected->getLocation(), diag::note_declared_at); 5291 } 5292 } else { 5293 if (Kind != TSK_CompleteObject) 5294 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5295 << Kind << SubType.getUnqualifiedType() << CSM; 5296 5297 // Explain why the defaulted or deleted special member isn't trivial. 5298 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5299 } 5300 } 5301 5302 return false; 5303} 5304 5305/// Check whether the members of a class type allow a special member to be 5306/// trivial. 5307static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5308 Sema::CXXSpecialMember CSM, 5309 bool ConstArg, bool Diagnose) { 5310 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5311 FE = RD->field_end(); FI != FE; ++FI) { 5312 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5313 continue; 5314 5315 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5316 5317 // Pretend anonymous struct or union members are members of this class. 5318 if (FI->isAnonymousStructOrUnion()) { 5319 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5320 CSM, ConstArg, Diagnose)) 5321 return false; 5322 continue; 5323 } 5324 5325 // C++11 [class.ctor]p5: 5326 // A default constructor is trivial if [...] 5327 // -- no non-static data member of its class has a 5328 // brace-or-equal-initializer 5329 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5330 if (Diagnose) 5331 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5332 return false; 5333 } 5334 5335 // Objective C ARC 4.3.5: 5336 // [...] nontrivally ownership-qualified types are [...] not trivially 5337 // default constructible, copy constructible, move constructible, copy 5338 // assignable, move assignable, or destructible [...] 5339 if (S.getLangOpts().ObjCAutoRefCount && 5340 FieldType.hasNonTrivialObjCLifetime()) { 5341 if (Diagnose) 5342 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5343 << RD << FieldType.getObjCLifetime(); 5344 return false; 5345 } 5346 5347 if (ConstArg && !FI->isMutable()) 5348 FieldType.addConst(); 5349 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5350 TSK_Field, Diagnose)) 5351 return false; 5352 } 5353 5354 return true; 5355} 5356 5357/// Diagnose why the specified class does not have a trivial special member of 5358/// the given kind. 5359void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5360 QualType Ty = Context.getRecordType(RD); 5361 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5362 Ty.addConst(); 5363 5364 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5365 TSK_CompleteObject, /*Diagnose*/true); 5366} 5367 5368/// Determine whether a defaulted or deleted special member function is trivial, 5369/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5370/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5371bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5372 bool Diagnose) { 5373 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5374 5375 CXXRecordDecl *RD = MD->getParent(); 5376 5377 bool ConstArg = false; 5378 5379 // C++11 [class.copy]p12, p25: 5380 // A [special member] is trivial if its declared parameter type is the same 5381 // as if it had been implicitly declared [...] 5382 switch (CSM) { 5383 case CXXDefaultConstructor: 5384 case CXXDestructor: 5385 // Trivial default constructors and destructors cannot have parameters. 5386 break; 5387 5388 case CXXCopyConstructor: 5389 case CXXCopyAssignment: { 5390 // Trivial copy operations always have const, non-volatile parameter types. 5391 ConstArg = true; 5392 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5393 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5394 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5395 if (Diagnose) 5396 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5397 << Param0->getSourceRange() << Param0->getType() 5398 << Context.getLValueReferenceType( 5399 Context.getRecordType(RD).withConst()); 5400 return false; 5401 } 5402 break; 5403 } 5404 5405 case CXXMoveConstructor: 5406 case CXXMoveAssignment: { 5407 // Trivial move operations always have non-cv-qualified parameters. 5408 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5409 const RValueReferenceType *RT = 5410 Param0->getType()->getAs<RValueReferenceType>(); 5411 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5412 if (Diagnose) 5413 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5414 << Param0->getSourceRange() << Param0->getType() 5415 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5416 return false; 5417 } 5418 break; 5419 } 5420 5421 case CXXInvalid: 5422 llvm_unreachable("not a special member"); 5423 } 5424 5425 // FIXME: We require that the parameter-declaration-clause is equivalent to 5426 // that of an implicit declaration, not just that the declared parameter type 5427 // matches, in order to prevent absuridities like a function simultaneously 5428 // being a trivial copy constructor and a non-trivial default constructor. 5429 // This issue has not yet been assigned a core issue number. 5430 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5431 if (Diagnose) 5432 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5433 diag::note_nontrivial_default_arg) 5434 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5435 return false; 5436 } 5437 if (MD->isVariadic()) { 5438 if (Diagnose) 5439 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5440 return false; 5441 } 5442 5443 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5444 // A copy/move [constructor or assignment operator] is trivial if 5445 // -- the [member] selected to copy/move each direct base class subobject 5446 // is trivial 5447 // 5448 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5449 // A [default constructor or destructor] is trivial if 5450 // -- all the direct base classes have trivial [default constructors or 5451 // destructors] 5452 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5453 BE = RD->bases_end(); BI != BE; ++BI) 5454 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5455 ConstArg ? BI->getType().withConst() 5456 : BI->getType(), 5457 CSM, TSK_BaseClass, Diagnose)) 5458 return false; 5459 5460 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5461 // A copy/move [constructor or assignment operator] for a class X is 5462 // trivial if 5463 // -- for each non-static data member of X that is of class type (or array 5464 // thereof), the constructor selected to copy/move that member is 5465 // trivial 5466 // 5467 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5468 // A [default constructor or destructor] is trivial if 5469 // -- for all of the non-static data members of its class that are of class 5470 // type (or array thereof), each such class has a trivial [default 5471 // constructor or destructor] 5472 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5473 return false; 5474 5475 // C++11 [class.dtor]p5: 5476 // A destructor is trivial if [...] 5477 // -- the destructor is not virtual 5478 if (CSM == CXXDestructor && MD->isVirtual()) { 5479 if (Diagnose) 5480 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5481 return false; 5482 } 5483 5484 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5485 // A [special member] for class X is trivial if [...] 5486 // -- class X has no virtual functions and no virtual base classes 5487 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5488 if (!Diagnose) 5489 return false; 5490 5491 if (RD->getNumVBases()) { 5492 // Check for virtual bases. We already know that the corresponding 5493 // member in all bases is trivial, so vbases must all be direct. 5494 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5495 assert(BS.isVirtual()); 5496 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5497 return false; 5498 } 5499 5500 // Must have a virtual method. 5501 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5502 ME = RD->method_end(); MI != ME; ++MI) { 5503 if (MI->isVirtual()) { 5504 SourceLocation MLoc = MI->getLocStart(); 5505 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5506 return false; 5507 } 5508 } 5509 5510 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5511 } 5512 5513 // Looks like it's trivial! 5514 return true; 5515} 5516 5517/// \brief Data used with FindHiddenVirtualMethod 5518namespace { 5519 struct FindHiddenVirtualMethodData { 5520 Sema *S; 5521 CXXMethodDecl *Method; 5522 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5523 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5524 }; 5525} 5526 5527/// \brief Check whether any most overriden method from MD in Methods 5528static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5529 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5530 if (MD->size_overridden_methods() == 0) 5531 return Methods.count(MD->getCanonicalDecl()); 5532 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5533 E = MD->end_overridden_methods(); 5534 I != E; ++I) 5535 if (CheckMostOverridenMethods(*I, Methods)) 5536 return true; 5537 return false; 5538} 5539 5540/// \brief Member lookup function that determines whether a given C++ 5541/// method overloads virtual methods in a base class without overriding any, 5542/// to be used with CXXRecordDecl::lookupInBases(). 5543static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5544 CXXBasePath &Path, 5545 void *UserData) { 5546 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5547 5548 FindHiddenVirtualMethodData &Data 5549 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5550 5551 DeclarationName Name = Data.Method->getDeclName(); 5552 assert(Name.getNameKind() == DeclarationName::Identifier); 5553 5554 bool foundSameNameMethod = false; 5555 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5556 for (Path.Decls = BaseRecord->lookup(Name); 5557 !Path.Decls.empty(); 5558 Path.Decls = Path.Decls.slice(1)) { 5559 NamedDecl *D = Path.Decls.front(); 5560 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5561 MD = MD->getCanonicalDecl(); 5562 foundSameNameMethod = true; 5563 // Interested only in hidden virtual methods. 5564 if (!MD->isVirtual()) 5565 continue; 5566 // If the method we are checking overrides a method from its base 5567 // don't warn about the other overloaded methods. 5568 if (!Data.S->IsOverload(Data.Method, MD, false)) 5569 return true; 5570 // Collect the overload only if its hidden. 5571 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5572 overloadedMethods.push_back(MD); 5573 } 5574 } 5575 5576 if (foundSameNameMethod) 5577 Data.OverloadedMethods.append(overloadedMethods.begin(), 5578 overloadedMethods.end()); 5579 return foundSameNameMethod; 5580} 5581 5582/// \brief Add the most overriden methods from MD to Methods 5583static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5584 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5585 if (MD->size_overridden_methods() == 0) 5586 Methods.insert(MD->getCanonicalDecl()); 5587 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5588 E = MD->end_overridden_methods(); 5589 I != E; ++I) 5590 AddMostOverridenMethods(*I, Methods); 5591} 5592 5593/// \brief See if a method overloads virtual methods in a base class without 5594/// overriding any. 5595void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5596 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5597 MD->getLocation()) == DiagnosticsEngine::Ignored) 5598 return; 5599 if (!MD->getDeclName().isIdentifier()) 5600 return; 5601 5602 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5603 /*bool RecordPaths=*/false, 5604 /*bool DetectVirtual=*/false); 5605 FindHiddenVirtualMethodData Data; 5606 Data.Method = MD; 5607 Data.S = this; 5608 5609 // Keep the base methods that were overriden or introduced in the subclass 5610 // by 'using' in a set. A base method not in this set is hidden. 5611 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5612 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5613 NamedDecl *ND = *I; 5614 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5615 ND = shad->getTargetDecl(); 5616 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5617 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5618 } 5619 5620 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5621 !Data.OverloadedMethods.empty()) { 5622 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5623 << MD << (Data.OverloadedMethods.size() > 1); 5624 5625 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5626 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5627 PartialDiagnostic PD = PDiag( 5628 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5629 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5630 Diag(overloadedMD->getLocation(), PD); 5631 } 5632 } 5633} 5634 5635void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5636 Decl *TagDecl, 5637 SourceLocation LBrac, 5638 SourceLocation RBrac, 5639 AttributeList *AttrList) { 5640 if (!TagDecl) 5641 return; 5642 5643 AdjustDeclIfTemplate(TagDecl); 5644 5645 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5646 if (l->getKind() != AttributeList::AT_Visibility) 5647 continue; 5648 l->setInvalid(); 5649 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5650 l->getName(); 5651 } 5652 5653 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5654 // strict aliasing violation! 5655 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5656 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5657 5658 CheckCompletedCXXClass( 5659 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5660} 5661 5662/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5663/// special functions, such as the default constructor, copy 5664/// constructor, or destructor, to the given C++ class (C++ 5665/// [special]p1). This routine can only be executed just before the 5666/// definition of the class is complete. 5667void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5668 if (!ClassDecl->hasUserDeclaredConstructor()) 5669 ++ASTContext::NumImplicitDefaultConstructors; 5670 5671 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5672 ++ASTContext::NumImplicitCopyConstructors; 5673 5674 // If the properties or semantics of the copy constructor couldn't be 5675 // determined while the class was being declared, force a declaration 5676 // of it now. 5677 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5678 DeclareImplicitCopyConstructor(ClassDecl); 5679 } 5680 5681 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5682 ++ASTContext::NumImplicitMoveConstructors; 5683 5684 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5685 DeclareImplicitMoveConstructor(ClassDecl); 5686 } 5687 5688 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5689 ++ASTContext::NumImplicitCopyAssignmentOperators; 5690 5691 // If we have a dynamic class, then the copy assignment operator may be 5692 // virtual, so we have to declare it immediately. This ensures that, e.g., 5693 // it shows up in the right place in the vtable and that we diagnose 5694 // problems with the implicit exception specification. 5695 if (ClassDecl->isDynamicClass() || 5696 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5697 DeclareImplicitCopyAssignment(ClassDecl); 5698 } 5699 5700 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5701 ++ASTContext::NumImplicitMoveAssignmentOperators; 5702 5703 // Likewise for the move assignment operator. 5704 if (ClassDecl->isDynamicClass() || 5705 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5706 DeclareImplicitMoveAssignment(ClassDecl); 5707 } 5708 5709 if (!ClassDecl->hasUserDeclaredDestructor()) { 5710 ++ASTContext::NumImplicitDestructors; 5711 5712 // If we have a dynamic class, then the destructor may be virtual, so we 5713 // have to declare the destructor immediately. This ensures that, e.g., it 5714 // shows up in the right place in the vtable and that we diagnose problems 5715 // with the implicit exception specification. 5716 if (ClassDecl->isDynamicClass() || 5717 ClassDecl->needsOverloadResolutionForDestructor()) 5718 DeclareImplicitDestructor(ClassDecl); 5719 } 5720} 5721 5722void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5723 if (!D) 5724 return; 5725 5726 int NumParamList = D->getNumTemplateParameterLists(); 5727 for (int i = 0; i < NumParamList; i++) { 5728 TemplateParameterList* Params = D->getTemplateParameterList(i); 5729 for (TemplateParameterList::iterator Param = Params->begin(), 5730 ParamEnd = Params->end(); 5731 Param != ParamEnd; ++Param) { 5732 NamedDecl *Named = cast<NamedDecl>(*Param); 5733 if (Named->getDeclName()) { 5734 S->AddDecl(Named); 5735 IdResolver.AddDecl(Named); 5736 } 5737 } 5738 } 5739} 5740 5741void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5742 if (!D) 5743 return; 5744 5745 TemplateParameterList *Params = 0; 5746 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5747 Params = Template->getTemplateParameters(); 5748 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5749 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5750 Params = PartialSpec->getTemplateParameters(); 5751 else 5752 return; 5753 5754 for (TemplateParameterList::iterator Param = Params->begin(), 5755 ParamEnd = Params->end(); 5756 Param != ParamEnd; ++Param) { 5757 NamedDecl *Named = cast<NamedDecl>(*Param); 5758 if (Named->getDeclName()) { 5759 S->AddDecl(Named); 5760 IdResolver.AddDecl(Named); 5761 } 5762 } 5763} 5764 5765void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5766 if (!RecordD) return; 5767 AdjustDeclIfTemplate(RecordD); 5768 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5769 PushDeclContext(S, Record); 5770} 5771 5772void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5773 if (!RecordD) return; 5774 PopDeclContext(); 5775} 5776 5777/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5778/// parsing a top-level (non-nested) C++ class, and we are now 5779/// parsing those parts of the given Method declaration that could 5780/// not be parsed earlier (C++ [class.mem]p2), such as default 5781/// arguments. This action should enter the scope of the given 5782/// Method declaration as if we had just parsed the qualified method 5783/// name. However, it should not bring the parameters into scope; 5784/// that will be performed by ActOnDelayedCXXMethodParameter. 5785void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5786} 5787 5788/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5789/// C++ method declaration. We're (re-)introducing the given 5790/// function parameter into scope for use in parsing later parts of 5791/// the method declaration. For example, we could see an 5792/// ActOnParamDefaultArgument event for this parameter. 5793void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5794 if (!ParamD) 5795 return; 5796 5797 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5798 5799 // If this parameter has an unparsed default argument, clear it out 5800 // to make way for the parsed default argument. 5801 if (Param->hasUnparsedDefaultArg()) 5802 Param->setDefaultArg(0); 5803 5804 S->AddDecl(Param); 5805 if (Param->getDeclName()) 5806 IdResolver.AddDecl(Param); 5807} 5808 5809/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5810/// processing the delayed method declaration for Method. The method 5811/// declaration is now considered finished. There may be a separate 5812/// ActOnStartOfFunctionDef action later (not necessarily 5813/// immediately!) for this method, if it was also defined inside the 5814/// class body. 5815void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5816 if (!MethodD) 5817 return; 5818 5819 AdjustDeclIfTemplate(MethodD); 5820 5821 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5822 5823 // Now that we have our default arguments, check the constructor 5824 // again. It could produce additional diagnostics or affect whether 5825 // the class has implicitly-declared destructors, among other 5826 // things. 5827 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5828 CheckConstructor(Constructor); 5829 5830 // Check the default arguments, which we may have added. 5831 if (!Method->isInvalidDecl()) 5832 CheckCXXDefaultArguments(Method); 5833} 5834 5835/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5836/// the well-formedness of the constructor declarator @p D with type @p 5837/// R. If there are any errors in the declarator, this routine will 5838/// emit diagnostics and set the invalid bit to true. In any case, the type 5839/// will be updated to reflect a well-formed type for the constructor and 5840/// returned. 5841QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5842 StorageClass &SC) { 5843 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5844 5845 // C++ [class.ctor]p3: 5846 // A constructor shall not be virtual (10.3) or static (9.4). A 5847 // constructor can be invoked for a const, volatile or const 5848 // volatile object. A constructor shall not be declared const, 5849 // volatile, or const volatile (9.3.2). 5850 if (isVirtual) { 5851 if (!D.isInvalidType()) 5852 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5853 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5854 << SourceRange(D.getIdentifierLoc()); 5855 D.setInvalidType(); 5856 } 5857 if (SC == SC_Static) { 5858 if (!D.isInvalidType()) 5859 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5860 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5861 << SourceRange(D.getIdentifierLoc()); 5862 D.setInvalidType(); 5863 SC = SC_None; 5864 } 5865 5866 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5867 if (FTI.TypeQuals != 0) { 5868 if (FTI.TypeQuals & Qualifiers::Const) 5869 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5870 << "const" << SourceRange(D.getIdentifierLoc()); 5871 if (FTI.TypeQuals & Qualifiers::Volatile) 5872 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5873 << "volatile" << SourceRange(D.getIdentifierLoc()); 5874 if (FTI.TypeQuals & Qualifiers::Restrict) 5875 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5876 << "restrict" << SourceRange(D.getIdentifierLoc()); 5877 D.setInvalidType(); 5878 } 5879 5880 // C++0x [class.ctor]p4: 5881 // A constructor shall not be declared with a ref-qualifier. 5882 if (FTI.hasRefQualifier()) { 5883 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5884 << FTI.RefQualifierIsLValueRef 5885 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5886 D.setInvalidType(); 5887 } 5888 5889 // Rebuild the function type "R" without any type qualifiers (in 5890 // case any of the errors above fired) and with "void" as the 5891 // return type, since constructors don't have return types. 5892 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5893 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5894 return R; 5895 5896 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5897 EPI.TypeQuals = 0; 5898 EPI.RefQualifier = RQ_None; 5899 5900 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5901} 5902 5903/// CheckConstructor - Checks a fully-formed constructor for 5904/// well-formedness, issuing any diagnostics required. Returns true if 5905/// the constructor declarator is invalid. 5906void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5907 CXXRecordDecl *ClassDecl 5908 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5909 if (!ClassDecl) 5910 return Constructor->setInvalidDecl(); 5911 5912 // C++ [class.copy]p3: 5913 // A declaration of a constructor for a class X is ill-formed if 5914 // its first parameter is of type (optionally cv-qualified) X and 5915 // either there are no other parameters or else all other 5916 // parameters have default arguments. 5917 if (!Constructor->isInvalidDecl() && 5918 ((Constructor->getNumParams() == 1) || 5919 (Constructor->getNumParams() > 1 && 5920 Constructor->getParamDecl(1)->hasDefaultArg())) && 5921 Constructor->getTemplateSpecializationKind() 5922 != TSK_ImplicitInstantiation) { 5923 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5924 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5925 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5926 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5927 const char *ConstRef 5928 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5929 : " const &"; 5930 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5931 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5932 5933 // FIXME: Rather that making the constructor invalid, we should endeavor 5934 // to fix the type. 5935 Constructor->setInvalidDecl(); 5936 } 5937 } 5938} 5939 5940/// CheckDestructor - Checks a fully-formed destructor definition for 5941/// well-formedness, issuing any diagnostics required. Returns true 5942/// on error. 5943bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5944 CXXRecordDecl *RD = Destructor->getParent(); 5945 5946 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 5947 SourceLocation Loc; 5948 5949 if (!Destructor->isImplicit()) 5950 Loc = Destructor->getLocation(); 5951 else 5952 Loc = RD->getLocation(); 5953 5954 // If we have a virtual destructor, look up the deallocation function 5955 FunctionDecl *OperatorDelete = 0; 5956 DeclarationName Name = 5957 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5958 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5959 return true; 5960 5961 MarkFunctionReferenced(Loc, OperatorDelete); 5962 5963 Destructor->setOperatorDelete(OperatorDelete); 5964 } 5965 5966 return false; 5967} 5968 5969static inline bool 5970FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5971 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5972 FTI.ArgInfo[0].Param && 5973 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5974} 5975 5976/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5977/// the well-formednes of the destructor declarator @p D with type @p 5978/// R. If there are any errors in the declarator, this routine will 5979/// emit diagnostics and set the declarator to invalid. Even if this happens, 5980/// will be updated to reflect a well-formed type for the destructor and 5981/// returned. 5982QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5983 StorageClass& SC) { 5984 // C++ [class.dtor]p1: 5985 // [...] A typedef-name that names a class is a class-name 5986 // (7.1.3); however, a typedef-name that names a class shall not 5987 // be used as the identifier in the declarator for a destructor 5988 // declaration. 5989 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5990 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5991 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5992 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5993 else if (const TemplateSpecializationType *TST = 5994 DeclaratorType->getAs<TemplateSpecializationType>()) 5995 if (TST->isTypeAlias()) 5996 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5997 << DeclaratorType << 1; 5998 5999 // C++ [class.dtor]p2: 6000 // A destructor is used to destroy objects of its class type. A 6001 // destructor takes no parameters, and no return type can be 6002 // specified for it (not even void). The address of a destructor 6003 // shall not be taken. A destructor shall not be static. A 6004 // destructor can be invoked for a const, volatile or const 6005 // volatile object. A destructor shall not be declared const, 6006 // volatile or const volatile (9.3.2). 6007 if (SC == SC_Static) { 6008 if (!D.isInvalidType()) 6009 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6010 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6011 << SourceRange(D.getIdentifierLoc()) 6012 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6013 6014 SC = SC_None; 6015 } 6016 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6017 // Destructors don't have return types, but the parser will 6018 // happily parse something like: 6019 // 6020 // class X { 6021 // float ~X(); 6022 // }; 6023 // 6024 // The return type will be eliminated later. 6025 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6026 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6027 << SourceRange(D.getIdentifierLoc()); 6028 } 6029 6030 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6031 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6032 if (FTI.TypeQuals & Qualifiers::Const) 6033 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6034 << "const" << SourceRange(D.getIdentifierLoc()); 6035 if (FTI.TypeQuals & Qualifiers::Volatile) 6036 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6037 << "volatile" << SourceRange(D.getIdentifierLoc()); 6038 if (FTI.TypeQuals & Qualifiers::Restrict) 6039 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6040 << "restrict" << SourceRange(D.getIdentifierLoc()); 6041 D.setInvalidType(); 6042 } 6043 6044 // C++0x [class.dtor]p2: 6045 // A destructor shall not be declared with a ref-qualifier. 6046 if (FTI.hasRefQualifier()) { 6047 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6048 << FTI.RefQualifierIsLValueRef 6049 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6050 D.setInvalidType(); 6051 } 6052 6053 // Make sure we don't have any parameters. 6054 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6055 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6056 6057 // Delete the parameters. 6058 FTI.freeArgs(); 6059 D.setInvalidType(); 6060 } 6061 6062 // Make sure the destructor isn't variadic. 6063 if (FTI.isVariadic) { 6064 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6065 D.setInvalidType(); 6066 } 6067 6068 // Rebuild the function type "R" without any type qualifiers or 6069 // parameters (in case any of the errors above fired) and with 6070 // "void" as the return type, since destructors don't have return 6071 // types. 6072 if (!D.isInvalidType()) 6073 return R; 6074 6075 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6076 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6077 EPI.Variadic = false; 6078 EPI.TypeQuals = 0; 6079 EPI.RefQualifier = RQ_None; 6080 return Context.getFunctionType(Context.VoidTy, None, EPI); 6081} 6082 6083/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6084/// well-formednes of the conversion function declarator @p D with 6085/// type @p R. If there are any errors in the declarator, this routine 6086/// will emit diagnostics and return true. Otherwise, it will return 6087/// false. Either way, the type @p R will be updated to reflect a 6088/// well-formed type for the conversion operator. 6089void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6090 StorageClass& SC) { 6091 // C++ [class.conv.fct]p1: 6092 // Neither parameter types nor return type can be specified. The 6093 // type of a conversion function (8.3.5) is "function taking no 6094 // parameter returning conversion-type-id." 6095 if (SC == SC_Static) { 6096 if (!D.isInvalidType()) 6097 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6098 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6099 << D.getName().getSourceRange(); 6100 D.setInvalidType(); 6101 SC = SC_None; 6102 } 6103 6104 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6105 6106 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6107 // Conversion functions don't have return types, but the parser will 6108 // happily parse something like: 6109 // 6110 // class X { 6111 // float operator bool(); 6112 // }; 6113 // 6114 // The return type will be changed later anyway. 6115 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6116 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6117 << SourceRange(D.getIdentifierLoc()); 6118 D.setInvalidType(); 6119 } 6120 6121 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6122 6123 // Make sure we don't have any parameters. 6124 if (Proto->getNumArgs() > 0) { 6125 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6126 6127 // Delete the parameters. 6128 D.getFunctionTypeInfo().freeArgs(); 6129 D.setInvalidType(); 6130 } else if (Proto->isVariadic()) { 6131 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6132 D.setInvalidType(); 6133 } 6134 6135 // Diagnose "&operator bool()" and other such nonsense. This 6136 // is actually a gcc extension which we don't support. 6137 if (Proto->getResultType() != ConvType) { 6138 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6139 << Proto->getResultType(); 6140 D.setInvalidType(); 6141 ConvType = Proto->getResultType(); 6142 } 6143 6144 // C++ [class.conv.fct]p4: 6145 // The conversion-type-id shall not represent a function type nor 6146 // an array type. 6147 if (ConvType->isArrayType()) { 6148 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6149 ConvType = Context.getPointerType(ConvType); 6150 D.setInvalidType(); 6151 } else if (ConvType->isFunctionType()) { 6152 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6153 ConvType = Context.getPointerType(ConvType); 6154 D.setInvalidType(); 6155 } 6156 6157 // Rebuild the function type "R" without any parameters (in case any 6158 // of the errors above fired) and with the conversion type as the 6159 // return type. 6160 if (D.isInvalidType()) 6161 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6162 6163 // C++0x explicit conversion operators. 6164 if (D.getDeclSpec().isExplicitSpecified()) 6165 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6166 getLangOpts().CPlusPlus11 ? 6167 diag::warn_cxx98_compat_explicit_conversion_functions : 6168 diag::ext_explicit_conversion_functions) 6169 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6170} 6171 6172/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6173/// the declaration of the given C++ conversion function. This routine 6174/// is responsible for recording the conversion function in the C++ 6175/// class, if possible. 6176Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6177 assert(Conversion && "Expected to receive a conversion function declaration"); 6178 6179 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6180 6181 // Make sure we aren't redeclaring the conversion function. 6182 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6183 6184 // C++ [class.conv.fct]p1: 6185 // [...] A conversion function is never used to convert a 6186 // (possibly cv-qualified) object to the (possibly cv-qualified) 6187 // same object type (or a reference to it), to a (possibly 6188 // cv-qualified) base class of that type (or a reference to it), 6189 // or to (possibly cv-qualified) void. 6190 // FIXME: Suppress this warning if the conversion function ends up being a 6191 // virtual function that overrides a virtual function in a base class. 6192 QualType ClassType 6193 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6194 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6195 ConvType = ConvTypeRef->getPointeeType(); 6196 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6197 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6198 /* Suppress diagnostics for instantiations. */; 6199 else if (ConvType->isRecordType()) { 6200 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6201 if (ConvType == ClassType) 6202 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6203 << ClassType; 6204 else if (IsDerivedFrom(ClassType, ConvType)) 6205 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6206 << ClassType << ConvType; 6207 } else if (ConvType->isVoidType()) { 6208 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6209 << ClassType << ConvType; 6210 } 6211 6212 if (FunctionTemplateDecl *ConversionTemplate 6213 = Conversion->getDescribedFunctionTemplate()) 6214 return ConversionTemplate; 6215 6216 return Conversion; 6217} 6218 6219//===----------------------------------------------------------------------===// 6220// Namespace Handling 6221//===----------------------------------------------------------------------===// 6222 6223/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6224/// reopened. 6225static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6226 SourceLocation Loc, 6227 IdentifierInfo *II, bool *IsInline, 6228 NamespaceDecl *PrevNS) { 6229 assert(*IsInline != PrevNS->isInline()); 6230 6231 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6232 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6233 // inline namespaces, with the intention of bringing names into namespace std. 6234 // 6235 // We support this just well enough to get that case working; this is not 6236 // sufficient to support reopening namespaces as inline in general. 6237 if (*IsInline && II && II->getName().startswith("__atomic") && 6238 S.getSourceManager().isInSystemHeader(Loc)) { 6239 // Mark all prior declarations of the namespace as inline. 6240 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6241 NS = NS->getPreviousDecl()) 6242 NS->setInline(*IsInline); 6243 // Patch up the lookup table for the containing namespace. This isn't really 6244 // correct, but it's good enough for this particular case. 6245 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6246 E = PrevNS->decls_end(); I != E; ++I) 6247 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6248 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6249 return; 6250 } 6251 6252 if (PrevNS->isInline()) 6253 // The user probably just forgot the 'inline', so suggest that it 6254 // be added back. 6255 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6256 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6257 else 6258 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6259 << IsInline; 6260 6261 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6262 *IsInline = PrevNS->isInline(); 6263} 6264 6265/// ActOnStartNamespaceDef - This is called at the start of a namespace 6266/// definition. 6267Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6268 SourceLocation InlineLoc, 6269 SourceLocation NamespaceLoc, 6270 SourceLocation IdentLoc, 6271 IdentifierInfo *II, 6272 SourceLocation LBrace, 6273 AttributeList *AttrList) { 6274 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6275 // For anonymous namespace, take the location of the left brace. 6276 SourceLocation Loc = II ? IdentLoc : LBrace; 6277 bool IsInline = InlineLoc.isValid(); 6278 bool IsInvalid = false; 6279 bool IsStd = false; 6280 bool AddToKnown = false; 6281 Scope *DeclRegionScope = NamespcScope->getParent(); 6282 6283 NamespaceDecl *PrevNS = 0; 6284 if (II) { 6285 // C++ [namespace.def]p2: 6286 // The identifier in an original-namespace-definition shall not 6287 // have been previously defined in the declarative region in 6288 // which the original-namespace-definition appears. The 6289 // identifier in an original-namespace-definition is the name of 6290 // the namespace. Subsequently in that declarative region, it is 6291 // treated as an original-namespace-name. 6292 // 6293 // Since namespace names are unique in their scope, and we don't 6294 // look through using directives, just look for any ordinary names. 6295 6296 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6297 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6298 Decl::IDNS_Namespace; 6299 NamedDecl *PrevDecl = 0; 6300 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6301 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6302 ++I) { 6303 if ((*I)->getIdentifierNamespace() & IDNS) { 6304 PrevDecl = *I; 6305 break; 6306 } 6307 } 6308 6309 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6310 6311 if (PrevNS) { 6312 // This is an extended namespace definition. 6313 if (IsInline != PrevNS->isInline()) 6314 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6315 &IsInline, PrevNS); 6316 } else if (PrevDecl) { 6317 // This is an invalid name redefinition. 6318 Diag(Loc, diag::err_redefinition_different_kind) 6319 << II; 6320 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6321 IsInvalid = true; 6322 // Continue on to push Namespc as current DeclContext and return it. 6323 } else if (II->isStr("std") && 6324 CurContext->getRedeclContext()->isTranslationUnit()) { 6325 // This is the first "real" definition of the namespace "std", so update 6326 // our cache of the "std" namespace to point at this definition. 6327 PrevNS = getStdNamespace(); 6328 IsStd = true; 6329 AddToKnown = !IsInline; 6330 } else { 6331 // We've seen this namespace for the first time. 6332 AddToKnown = !IsInline; 6333 } 6334 } else { 6335 // Anonymous namespaces. 6336 6337 // Determine whether the parent already has an anonymous namespace. 6338 DeclContext *Parent = CurContext->getRedeclContext(); 6339 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6340 PrevNS = TU->getAnonymousNamespace(); 6341 } else { 6342 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6343 PrevNS = ND->getAnonymousNamespace(); 6344 } 6345 6346 if (PrevNS && IsInline != PrevNS->isInline()) 6347 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6348 &IsInline, PrevNS); 6349 } 6350 6351 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6352 StartLoc, Loc, II, PrevNS); 6353 if (IsInvalid) 6354 Namespc->setInvalidDecl(); 6355 6356 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6357 6358 // FIXME: Should we be merging attributes? 6359 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6360 PushNamespaceVisibilityAttr(Attr, Loc); 6361 6362 if (IsStd) 6363 StdNamespace = Namespc; 6364 if (AddToKnown) 6365 KnownNamespaces[Namespc] = false; 6366 6367 if (II) { 6368 PushOnScopeChains(Namespc, DeclRegionScope); 6369 } else { 6370 // Link the anonymous namespace into its parent. 6371 DeclContext *Parent = CurContext->getRedeclContext(); 6372 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6373 TU->setAnonymousNamespace(Namespc); 6374 } else { 6375 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6376 } 6377 6378 CurContext->addDecl(Namespc); 6379 6380 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6381 // behaves as if it were replaced by 6382 // namespace unique { /* empty body */ } 6383 // using namespace unique; 6384 // namespace unique { namespace-body } 6385 // where all occurrences of 'unique' in a translation unit are 6386 // replaced by the same identifier and this identifier differs 6387 // from all other identifiers in the entire program. 6388 6389 // We just create the namespace with an empty name and then add an 6390 // implicit using declaration, just like the standard suggests. 6391 // 6392 // CodeGen enforces the "universally unique" aspect by giving all 6393 // declarations semantically contained within an anonymous 6394 // namespace internal linkage. 6395 6396 if (!PrevNS) { 6397 UsingDirectiveDecl* UD 6398 = UsingDirectiveDecl::Create(Context, Parent, 6399 /* 'using' */ LBrace, 6400 /* 'namespace' */ SourceLocation(), 6401 /* qualifier */ NestedNameSpecifierLoc(), 6402 /* identifier */ SourceLocation(), 6403 Namespc, 6404 /* Ancestor */ Parent); 6405 UD->setImplicit(); 6406 Parent->addDecl(UD); 6407 } 6408 } 6409 6410 ActOnDocumentableDecl(Namespc); 6411 6412 // Although we could have an invalid decl (i.e. the namespace name is a 6413 // redefinition), push it as current DeclContext and try to continue parsing. 6414 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6415 // for the namespace has the declarations that showed up in that particular 6416 // namespace definition. 6417 PushDeclContext(NamespcScope, Namespc); 6418 return Namespc; 6419} 6420 6421/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6422/// is a namespace alias, returns the namespace it points to. 6423static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6424 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6425 return AD->getNamespace(); 6426 return dyn_cast_or_null<NamespaceDecl>(D); 6427} 6428 6429/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6430/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6431void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6432 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6433 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6434 Namespc->setRBraceLoc(RBrace); 6435 PopDeclContext(); 6436 if (Namespc->hasAttr<VisibilityAttr>()) 6437 PopPragmaVisibility(true, RBrace); 6438} 6439 6440CXXRecordDecl *Sema::getStdBadAlloc() const { 6441 return cast_or_null<CXXRecordDecl>( 6442 StdBadAlloc.get(Context.getExternalSource())); 6443} 6444 6445NamespaceDecl *Sema::getStdNamespace() const { 6446 return cast_or_null<NamespaceDecl>( 6447 StdNamespace.get(Context.getExternalSource())); 6448} 6449 6450/// \brief Retrieve the special "std" namespace, which may require us to 6451/// implicitly define the namespace. 6452NamespaceDecl *Sema::getOrCreateStdNamespace() { 6453 if (!StdNamespace) { 6454 // The "std" namespace has not yet been defined, so build one implicitly. 6455 StdNamespace = NamespaceDecl::Create(Context, 6456 Context.getTranslationUnitDecl(), 6457 /*Inline=*/false, 6458 SourceLocation(), SourceLocation(), 6459 &PP.getIdentifierTable().get("std"), 6460 /*PrevDecl=*/0); 6461 getStdNamespace()->setImplicit(true); 6462 } 6463 6464 return getStdNamespace(); 6465} 6466 6467bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6468 assert(getLangOpts().CPlusPlus && 6469 "Looking for std::initializer_list outside of C++."); 6470 6471 // We're looking for implicit instantiations of 6472 // template <typename E> class std::initializer_list. 6473 6474 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6475 return false; 6476 6477 ClassTemplateDecl *Template = 0; 6478 const TemplateArgument *Arguments = 0; 6479 6480 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6481 6482 ClassTemplateSpecializationDecl *Specialization = 6483 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6484 if (!Specialization) 6485 return false; 6486 6487 Template = Specialization->getSpecializedTemplate(); 6488 Arguments = Specialization->getTemplateArgs().data(); 6489 } else if (const TemplateSpecializationType *TST = 6490 Ty->getAs<TemplateSpecializationType>()) { 6491 Template = dyn_cast_or_null<ClassTemplateDecl>( 6492 TST->getTemplateName().getAsTemplateDecl()); 6493 Arguments = TST->getArgs(); 6494 } 6495 if (!Template) 6496 return false; 6497 6498 if (!StdInitializerList) { 6499 // Haven't recognized std::initializer_list yet, maybe this is it. 6500 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6501 if (TemplateClass->getIdentifier() != 6502 &PP.getIdentifierTable().get("initializer_list") || 6503 !getStdNamespace()->InEnclosingNamespaceSetOf( 6504 TemplateClass->getDeclContext())) 6505 return false; 6506 // This is a template called std::initializer_list, but is it the right 6507 // template? 6508 TemplateParameterList *Params = Template->getTemplateParameters(); 6509 if (Params->getMinRequiredArguments() != 1) 6510 return false; 6511 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6512 return false; 6513 6514 // It's the right template. 6515 StdInitializerList = Template; 6516 } 6517 6518 if (Template != StdInitializerList) 6519 return false; 6520 6521 // This is an instance of std::initializer_list. Find the argument type. 6522 if (Element) 6523 *Element = Arguments[0].getAsType(); 6524 return true; 6525} 6526 6527static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6528 NamespaceDecl *Std = S.getStdNamespace(); 6529 if (!Std) { 6530 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6531 return 0; 6532 } 6533 6534 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6535 Loc, Sema::LookupOrdinaryName); 6536 if (!S.LookupQualifiedName(Result, Std)) { 6537 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6538 return 0; 6539 } 6540 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6541 if (!Template) { 6542 Result.suppressDiagnostics(); 6543 // We found something weird. Complain about the first thing we found. 6544 NamedDecl *Found = *Result.begin(); 6545 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6546 return 0; 6547 } 6548 6549 // We found some template called std::initializer_list. Now verify that it's 6550 // correct. 6551 TemplateParameterList *Params = Template->getTemplateParameters(); 6552 if (Params->getMinRequiredArguments() != 1 || 6553 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6554 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6555 return 0; 6556 } 6557 6558 return Template; 6559} 6560 6561QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6562 if (!StdInitializerList) { 6563 StdInitializerList = LookupStdInitializerList(*this, Loc); 6564 if (!StdInitializerList) 6565 return QualType(); 6566 } 6567 6568 TemplateArgumentListInfo Args(Loc, Loc); 6569 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6570 Context.getTrivialTypeSourceInfo(Element, 6571 Loc))); 6572 return Context.getCanonicalType( 6573 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6574} 6575 6576bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6577 // C++ [dcl.init.list]p2: 6578 // A constructor is an initializer-list constructor if its first parameter 6579 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6580 // std::initializer_list<E> for some type E, and either there are no other 6581 // parameters or else all other parameters have default arguments. 6582 if (Ctor->getNumParams() < 1 || 6583 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6584 return false; 6585 6586 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6587 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6588 ArgType = RT->getPointeeType().getUnqualifiedType(); 6589 6590 return isStdInitializerList(ArgType, 0); 6591} 6592 6593/// \brief Determine whether a using statement is in a context where it will be 6594/// apply in all contexts. 6595static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6596 switch (CurContext->getDeclKind()) { 6597 case Decl::TranslationUnit: 6598 return true; 6599 case Decl::LinkageSpec: 6600 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6601 default: 6602 return false; 6603 } 6604} 6605 6606namespace { 6607 6608// Callback to only accept typo corrections that are namespaces. 6609class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6610 public: 6611 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6612 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6613 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6614 } 6615 return false; 6616 } 6617}; 6618 6619} 6620 6621static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6622 CXXScopeSpec &SS, 6623 SourceLocation IdentLoc, 6624 IdentifierInfo *Ident) { 6625 NamespaceValidatorCCC Validator; 6626 R.clear(); 6627 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6628 R.getLookupKind(), Sc, &SS, 6629 Validator)) { 6630 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6631 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6632 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6633 bool droppedSpecifier = Corrected.WillReplaceSpecifier() && 6634 Ident->getName().equals(CorrectedStr); 6635 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6636 << Ident << DC << droppedSpecifier << CorrectedQuotedStr 6637 << SS.getRange() << FixItHint::CreateReplacement( 6638 Corrected.getCorrectionRange(), CorrectedStr); 6639 } else { 6640 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6641 << Ident << CorrectedQuotedStr 6642 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6643 } 6644 6645 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6646 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6647 6648 R.addDecl(Corrected.getCorrectionDecl()); 6649 return true; 6650 } 6651 return false; 6652} 6653 6654Decl *Sema::ActOnUsingDirective(Scope *S, 6655 SourceLocation UsingLoc, 6656 SourceLocation NamespcLoc, 6657 CXXScopeSpec &SS, 6658 SourceLocation IdentLoc, 6659 IdentifierInfo *NamespcName, 6660 AttributeList *AttrList) { 6661 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6662 assert(NamespcName && "Invalid NamespcName."); 6663 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6664 6665 // This can only happen along a recovery path. 6666 while (S->getFlags() & Scope::TemplateParamScope) 6667 S = S->getParent(); 6668 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6669 6670 UsingDirectiveDecl *UDir = 0; 6671 NestedNameSpecifier *Qualifier = 0; 6672 if (SS.isSet()) 6673 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6674 6675 // Lookup namespace name. 6676 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6677 LookupParsedName(R, S, &SS); 6678 if (R.isAmbiguous()) 6679 return 0; 6680 6681 if (R.empty()) { 6682 R.clear(); 6683 // Allow "using namespace std;" or "using namespace ::std;" even if 6684 // "std" hasn't been defined yet, for GCC compatibility. 6685 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6686 NamespcName->isStr("std")) { 6687 Diag(IdentLoc, diag::ext_using_undefined_std); 6688 R.addDecl(getOrCreateStdNamespace()); 6689 R.resolveKind(); 6690 } 6691 // Otherwise, attempt typo correction. 6692 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6693 } 6694 6695 if (!R.empty()) { 6696 NamedDecl *Named = R.getFoundDecl(); 6697 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6698 && "expected namespace decl"); 6699 // C++ [namespace.udir]p1: 6700 // A using-directive specifies that the names in the nominated 6701 // namespace can be used in the scope in which the 6702 // using-directive appears after the using-directive. During 6703 // unqualified name lookup (3.4.1), the names appear as if they 6704 // were declared in the nearest enclosing namespace which 6705 // contains both the using-directive and the nominated 6706 // namespace. [Note: in this context, "contains" means "contains 6707 // directly or indirectly". ] 6708 6709 // Find enclosing context containing both using-directive and 6710 // nominated namespace. 6711 NamespaceDecl *NS = getNamespaceDecl(Named); 6712 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6713 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6714 CommonAncestor = CommonAncestor->getParent(); 6715 6716 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6717 SS.getWithLocInContext(Context), 6718 IdentLoc, Named, CommonAncestor); 6719 6720 if (IsUsingDirectiveInToplevelContext(CurContext) && 6721 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6722 Diag(IdentLoc, diag::warn_using_directive_in_header); 6723 } 6724 6725 PushUsingDirective(S, UDir); 6726 } else { 6727 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6728 } 6729 6730 if (UDir) 6731 ProcessDeclAttributeList(S, UDir, AttrList); 6732 6733 return UDir; 6734} 6735 6736void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6737 // If the scope has an associated entity and the using directive is at 6738 // namespace or translation unit scope, add the UsingDirectiveDecl into 6739 // its lookup structure so qualified name lookup can find it. 6740 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6741 if (Ctx && !Ctx->isFunctionOrMethod()) 6742 Ctx->addDecl(UDir); 6743 else 6744 // Otherwise, it is at block sope. The using-directives will affect lookup 6745 // only to the end of the scope. 6746 S->PushUsingDirective(UDir); 6747} 6748 6749 6750Decl *Sema::ActOnUsingDeclaration(Scope *S, 6751 AccessSpecifier AS, 6752 bool HasUsingKeyword, 6753 SourceLocation UsingLoc, 6754 CXXScopeSpec &SS, 6755 UnqualifiedId &Name, 6756 AttributeList *AttrList, 6757 bool HasTypenameKeyword, 6758 SourceLocation TypenameLoc) { 6759 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6760 6761 switch (Name.getKind()) { 6762 case UnqualifiedId::IK_ImplicitSelfParam: 6763 case UnqualifiedId::IK_Identifier: 6764 case UnqualifiedId::IK_OperatorFunctionId: 6765 case UnqualifiedId::IK_LiteralOperatorId: 6766 case UnqualifiedId::IK_ConversionFunctionId: 6767 break; 6768 6769 case UnqualifiedId::IK_ConstructorName: 6770 case UnqualifiedId::IK_ConstructorTemplateId: 6771 // C++11 inheriting constructors. 6772 Diag(Name.getLocStart(), 6773 getLangOpts().CPlusPlus11 ? 6774 diag::warn_cxx98_compat_using_decl_constructor : 6775 diag::err_using_decl_constructor) 6776 << SS.getRange(); 6777 6778 if (getLangOpts().CPlusPlus11) break; 6779 6780 return 0; 6781 6782 case UnqualifiedId::IK_DestructorName: 6783 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6784 << SS.getRange(); 6785 return 0; 6786 6787 case UnqualifiedId::IK_TemplateId: 6788 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6789 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6790 return 0; 6791 } 6792 6793 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6794 DeclarationName TargetName = TargetNameInfo.getName(); 6795 if (!TargetName) 6796 return 0; 6797 6798 // Warn about access declarations. 6799 if (!HasUsingKeyword) { 6800 Diag(Name.getLocStart(), 6801 getLangOpts().CPlusPlus11 ? diag::err_access_decl 6802 : diag::warn_access_decl_deprecated) 6803 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6804 } 6805 6806 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6807 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6808 return 0; 6809 6810 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6811 TargetNameInfo, AttrList, 6812 /* IsInstantiation */ false, 6813 HasTypenameKeyword, TypenameLoc); 6814 if (UD) 6815 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6816 6817 return UD; 6818} 6819 6820/// \brief Determine whether a using declaration considers the given 6821/// declarations as "equivalent", e.g., if they are redeclarations of 6822/// the same entity or are both typedefs of the same type. 6823static bool 6824IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6825 bool &SuppressRedeclaration) { 6826 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6827 SuppressRedeclaration = false; 6828 return true; 6829 } 6830 6831 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6832 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6833 SuppressRedeclaration = true; 6834 return Context.hasSameType(TD1->getUnderlyingType(), 6835 TD2->getUnderlyingType()); 6836 } 6837 6838 return false; 6839} 6840 6841 6842/// Determines whether to create a using shadow decl for a particular 6843/// decl, given the set of decls existing prior to this using lookup. 6844bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6845 const LookupResult &Previous) { 6846 // Diagnose finding a decl which is not from a base class of the 6847 // current class. We do this now because there are cases where this 6848 // function will silently decide not to build a shadow decl, which 6849 // will pre-empt further diagnostics. 6850 // 6851 // We don't need to do this in C++0x because we do the check once on 6852 // the qualifier. 6853 // 6854 // FIXME: diagnose the following if we care enough: 6855 // struct A { int foo; }; 6856 // struct B : A { using A::foo; }; 6857 // template <class T> struct C : A {}; 6858 // template <class T> struct D : C<T> { using B::foo; } // <--- 6859 // This is invalid (during instantiation) in C++03 because B::foo 6860 // resolves to the using decl in B, which is not a base class of D<T>. 6861 // We can't diagnose it immediately because C<T> is an unknown 6862 // specialization. The UsingShadowDecl in D<T> then points directly 6863 // to A::foo, which will look well-formed when we instantiate. 6864 // The right solution is to not collapse the shadow-decl chain. 6865 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6866 DeclContext *OrigDC = Orig->getDeclContext(); 6867 6868 // Handle enums and anonymous structs. 6869 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6870 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6871 while (OrigRec->isAnonymousStructOrUnion()) 6872 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6873 6874 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6875 if (OrigDC == CurContext) { 6876 Diag(Using->getLocation(), 6877 diag::err_using_decl_nested_name_specifier_is_current_class) 6878 << Using->getQualifierLoc().getSourceRange(); 6879 Diag(Orig->getLocation(), diag::note_using_decl_target); 6880 return true; 6881 } 6882 6883 Diag(Using->getQualifierLoc().getBeginLoc(), 6884 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6885 << Using->getQualifier() 6886 << cast<CXXRecordDecl>(CurContext) 6887 << Using->getQualifierLoc().getSourceRange(); 6888 Diag(Orig->getLocation(), diag::note_using_decl_target); 6889 return true; 6890 } 6891 } 6892 6893 if (Previous.empty()) return false; 6894 6895 NamedDecl *Target = Orig; 6896 if (isa<UsingShadowDecl>(Target)) 6897 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6898 6899 // If the target happens to be one of the previous declarations, we 6900 // don't have a conflict. 6901 // 6902 // FIXME: but we might be increasing its access, in which case we 6903 // should redeclare it. 6904 NamedDecl *NonTag = 0, *Tag = 0; 6905 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6906 I != E; ++I) { 6907 NamedDecl *D = (*I)->getUnderlyingDecl(); 6908 bool Result; 6909 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6910 return Result; 6911 6912 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6913 } 6914 6915 if (Target->isFunctionOrFunctionTemplate()) { 6916 FunctionDecl *FD; 6917 if (isa<FunctionTemplateDecl>(Target)) 6918 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6919 else 6920 FD = cast<FunctionDecl>(Target); 6921 6922 NamedDecl *OldDecl = 0; 6923 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6924 case Ovl_Overload: 6925 return false; 6926 6927 case Ovl_NonFunction: 6928 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6929 break; 6930 6931 // We found a decl with the exact signature. 6932 case Ovl_Match: 6933 // If we're in a record, we want to hide the target, so we 6934 // return true (without a diagnostic) to tell the caller not to 6935 // build a shadow decl. 6936 if (CurContext->isRecord()) 6937 return true; 6938 6939 // If we're not in a record, this is an error. 6940 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6941 break; 6942 } 6943 6944 Diag(Target->getLocation(), diag::note_using_decl_target); 6945 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6946 return true; 6947 } 6948 6949 // Target is not a function. 6950 6951 if (isa<TagDecl>(Target)) { 6952 // No conflict between a tag and a non-tag. 6953 if (!Tag) return false; 6954 6955 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6956 Diag(Target->getLocation(), diag::note_using_decl_target); 6957 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6958 return true; 6959 } 6960 6961 // No conflict between a tag and a non-tag. 6962 if (!NonTag) return false; 6963 6964 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6965 Diag(Target->getLocation(), diag::note_using_decl_target); 6966 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6967 return true; 6968} 6969 6970/// Builds a shadow declaration corresponding to a 'using' declaration. 6971UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6972 UsingDecl *UD, 6973 NamedDecl *Orig) { 6974 6975 // If we resolved to another shadow declaration, just coalesce them. 6976 NamedDecl *Target = Orig; 6977 if (isa<UsingShadowDecl>(Target)) { 6978 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6979 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6980 } 6981 6982 UsingShadowDecl *Shadow 6983 = UsingShadowDecl::Create(Context, CurContext, 6984 UD->getLocation(), UD, Target); 6985 UD->addShadowDecl(Shadow); 6986 6987 Shadow->setAccess(UD->getAccess()); 6988 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6989 Shadow->setInvalidDecl(); 6990 6991 if (S) 6992 PushOnScopeChains(Shadow, S); 6993 else 6994 CurContext->addDecl(Shadow); 6995 6996 6997 return Shadow; 6998} 6999 7000/// Hides a using shadow declaration. This is required by the current 7001/// using-decl implementation when a resolvable using declaration in a 7002/// class is followed by a declaration which would hide or override 7003/// one or more of the using decl's targets; for example: 7004/// 7005/// struct Base { void foo(int); }; 7006/// struct Derived : Base { 7007/// using Base::foo; 7008/// void foo(int); 7009/// }; 7010/// 7011/// The governing language is C++03 [namespace.udecl]p12: 7012/// 7013/// When a using-declaration brings names from a base class into a 7014/// derived class scope, member functions in the derived class 7015/// override and/or hide member functions with the same name and 7016/// parameter types in a base class (rather than conflicting). 7017/// 7018/// There are two ways to implement this: 7019/// (1) optimistically create shadow decls when they're not hidden 7020/// by existing declarations, or 7021/// (2) don't create any shadow decls (or at least don't make them 7022/// visible) until we've fully parsed/instantiated the class. 7023/// The problem with (1) is that we might have to retroactively remove 7024/// a shadow decl, which requires several O(n) operations because the 7025/// decl structures are (very reasonably) not designed for removal. 7026/// (2) avoids this but is very fiddly and phase-dependent. 7027void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7028 if (Shadow->getDeclName().getNameKind() == 7029 DeclarationName::CXXConversionFunctionName) 7030 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7031 7032 // Remove it from the DeclContext... 7033 Shadow->getDeclContext()->removeDecl(Shadow); 7034 7035 // ...and the scope, if applicable... 7036 if (S) { 7037 S->RemoveDecl(Shadow); 7038 IdResolver.RemoveDecl(Shadow); 7039 } 7040 7041 // ...and the using decl. 7042 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7043 7044 // TODO: complain somehow if Shadow was used. It shouldn't 7045 // be possible for this to happen, because...? 7046} 7047 7048class UsingValidatorCCC : public CorrectionCandidateCallback { 7049public: 7050 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation) 7051 : HasTypenameKeyword(HasTypenameKeyword), 7052 IsInstantiation(IsInstantiation) {} 7053 7054 virtual bool ValidateCandidate(const TypoCorrection &Candidate) { 7055 if (NamedDecl *ND = Candidate.getCorrectionDecl()) { 7056 if (isa<NamespaceDecl>(ND)) 7057 return false; 7058 // Completely unqualified names are invalid for a 'using' declaration. 7059 bool droppedSpecifier = Candidate.WillReplaceSpecifier() && 7060 !Candidate.getCorrectionSpecifier(); 7061 if (droppedSpecifier) 7062 return false; 7063 else if (isa<TypeDecl>(ND)) 7064 return HasTypenameKeyword || !IsInstantiation; 7065 else 7066 return !HasTypenameKeyword; 7067 } else { 7068 // Keywords are not valid here. 7069 return false; 7070 } 7071 } 7072 7073private: 7074 bool HasTypenameKeyword; 7075 bool IsInstantiation; 7076}; 7077 7078/// Builds a using declaration. 7079/// 7080/// \param IsInstantiation - Whether this call arises from an 7081/// instantiation of an unresolved using declaration. We treat 7082/// the lookup differently for these declarations. 7083NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7084 SourceLocation UsingLoc, 7085 CXXScopeSpec &SS, 7086 const DeclarationNameInfo &NameInfo, 7087 AttributeList *AttrList, 7088 bool IsInstantiation, 7089 bool HasTypenameKeyword, 7090 SourceLocation TypenameLoc) { 7091 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7092 SourceLocation IdentLoc = NameInfo.getLoc(); 7093 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7094 7095 // FIXME: We ignore attributes for now. 7096 7097 if (SS.isEmpty()) { 7098 Diag(IdentLoc, diag::err_using_requires_qualname); 7099 return 0; 7100 } 7101 7102 // Do the redeclaration lookup in the current scope. 7103 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7104 ForRedeclaration); 7105 Previous.setHideTags(false); 7106 if (S) { 7107 LookupName(Previous, S); 7108 7109 // It is really dumb that we have to do this. 7110 LookupResult::Filter F = Previous.makeFilter(); 7111 while (F.hasNext()) { 7112 NamedDecl *D = F.next(); 7113 if (!isDeclInScope(D, CurContext, S)) 7114 F.erase(); 7115 } 7116 F.done(); 7117 } else { 7118 assert(IsInstantiation && "no scope in non-instantiation"); 7119 assert(CurContext->isRecord() && "scope not record in instantiation"); 7120 LookupQualifiedName(Previous, CurContext); 7121 } 7122 7123 // Check for invalid redeclarations. 7124 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7125 SS, IdentLoc, Previous)) 7126 return 0; 7127 7128 // Check for bad qualifiers. 7129 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7130 return 0; 7131 7132 DeclContext *LookupContext = computeDeclContext(SS); 7133 NamedDecl *D; 7134 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7135 if (!LookupContext) { 7136 if (HasTypenameKeyword) { 7137 // FIXME: not all declaration name kinds are legal here 7138 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7139 UsingLoc, TypenameLoc, 7140 QualifierLoc, 7141 IdentLoc, NameInfo.getName()); 7142 } else { 7143 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7144 QualifierLoc, NameInfo); 7145 } 7146 } else { 7147 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7148 NameInfo, HasTypenameKeyword); 7149 } 7150 D->setAccess(AS); 7151 CurContext->addDecl(D); 7152 7153 if (!LookupContext) return D; 7154 UsingDecl *UD = cast<UsingDecl>(D); 7155 7156 if (RequireCompleteDeclContext(SS, LookupContext)) { 7157 UD->setInvalidDecl(); 7158 return UD; 7159 } 7160 7161 // The normal rules do not apply to inheriting constructor declarations. 7162 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7163 if (CheckInheritingConstructorUsingDecl(UD)) 7164 UD->setInvalidDecl(); 7165 return UD; 7166 } 7167 7168 // Otherwise, look up the target name. 7169 7170 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7171 7172 // Unlike most lookups, we don't always want to hide tag 7173 // declarations: tag names are visible through the using declaration 7174 // even if hidden by ordinary names, *except* in a dependent context 7175 // where it's important for the sanity of two-phase lookup. 7176 if (!IsInstantiation) 7177 R.setHideTags(false); 7178 7179 // For the purposes of this lookup, we have a base object type 7180 // equal to that of the current context. 7181 if (CurContext->isRecord()) { 7182 R.setBaseObjectType( 7183 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7184 } 7185 7186 LookupQualifiedName(R, LookupContext); 7187 7188 // Try to correct typos if possible. 7189 if (R.empty()) { 7190 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation); 7191 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7192 R.getLookupKind(), S, &SS, CCC)){ 7193 // We reject any correction for which ND would be NULL. 7194 NamedDecl *ND = Corrected.getCorrectionDecl(); 7195 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 7196 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 7197 R.setLookupName(Corrected.getCorrection()); 7198 R.addDecl(ND); 7199 // We reject candidates where droppedSpecifier == true, hence the 7200 // literal '0' below. 7201 Diag(R.getNameLoc(), diag::err_no_member_suggest) 7202 << NameInfo.getName() << LookupContext << 0 7203 << CorrectedQuotedStr << SS.getRange() 7204 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 7205 CorrectedStr); 7206 Diag(ND->getLocation(), diag::note_previous_decl) 7207 << CorrectedQuotedStr; 7208 } else { 7209 Diag(IdentLoc, diag::err_no_member) 7210 << NameInfo.getName() << LookupContext << SS.getRange(); 7211 UD->setInvalidDecl(); 7212 return UD; 7213 } 7214 } 7215 7216 if (R.isAmbiguous()) { 7217 UD->setInvalidDecl(); 7218 return UD; 7219 } 7220 7221 if (HasTypenameKeyword) { 7222 // If we asked for a typename and got a non-type decl, error out. 7223 if (!R.getAsSingle<TypeDecl>()) { 7224 Diag(IdentLoc, diag::err_using_typename_non_type); 7225 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7226 Diag((*I)->getUnderlyingDecl()->getLocation(), 7227 diag::note_using_decl_target); 7228 UD->setInvalidDecl(); 7229 return UD; 7230 } 7231 } else { 7232 // If we asked for a non-typename and we got a type, error out, 7233 // but only if this is an instantiation of an unresolved using 7234 // decl. Otherwise just silently find the type name. 7235 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7236 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7237 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7238 UD->setInvalidDecl(); 7239 return UD; 7240 } 7241 } 7242 7243 // C++0x N2914 [namespace.udecl]p6: 7244 // A using-declaration shall not name a namespace. 7245 if (R.getAsSingle<NamespaceDecl>()) { 7246 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7247 << SS.getRange(); 7248 UD->setInvalidDecl(); 7249 return UD; 7250 } 7251 7252 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7253 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7254 BuildUsingShadowDecl(S, UD, *I); 7255 } 7256 7257 return UD; 7258} 7259 7260/// Additional checks for a using declaration referring to a constructor name. 7261bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7262 assert(!UD->hasTypename() && "expecting a constructor name"); 7263 7264 const Type *SourceType = UD->getQualifier()->getAsType(); 7265 assert(SourceType && 7266 "Using decl naming constructor doesn't have type in scope spec."); 7267 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7268 7269 // Check whether the named type is a direct base class. 7270 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7271 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7272 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7273 BaseIt != BaseE; ++BaseIt) { 7274 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7275 if (CanonicalSourceType == BaseType) 7276 break; 7277 if (BaseIt->getType()->isDependentType()) 7278 break; 7279 } 7280 7281 if (BaseIt == BaseE) { 7282 // Did not find SourceType in the bases. 7283 Diag(UD->getUsingLoc(), 7284 diag::err_using_decl_constructor_not_in_direct_base) 7285 << UD->getNameInfo().getSourceRange() 7286 << QualType(SourceType, 0) << TargetClass; 7287 return true; 7288 } 7289 7290 if (!CurContext->isDependentContext()) 7291 BaseIt->setInheritConstructors(); 7292 7293 return false; 7294} 7295 7296/// Checks that the given using declaration is not an invalid 7297/// redeclaration. Note that this is checking only for the using decl 7298/// itself, not for any ill-formedness among the UsingShadowDecls. 7299bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7300 bool HasTypenameKeyword, 7301 const CXXScopeSpec &SS, 7302 SourceLocation NameLoc, 7303 const LookupResult &Prev) { 7304 // C++03 [namespace.udecl]p8: 7305 // C++0x [namespace.udecl]p10: 7306 // A using-declaration is a declaration and can therefore be used 7307 // repeatedly where (and only where) multiple declarations are 7308 // allowed. 7309 // 7310 // That's in non-member contexts. 7311 if (!CurContext->getRedeclContext()->isRecord()) 7312 return false; 7313 7314 NestedNameSpecifier *Qual 7315 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7316 7317 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7318 NamedDecl *D = *I; 7319 7320 bool DTypename; 7321 NestedNameSpecifier *DQual; 7322 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7323 DTypename = UD->hasTypename(); 7324 DQual = UD->getQualifier(); 7325 } else if (UnresolvedUsingValueDecl *UD 7326 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7327 DTypename = false; 7328 DQual = UD->getQualifier(); 7329 } else if (UnresolvedUsingTypenameDecl *UD 7330 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7331 DTypename = true; 7332 DQual = UD->getQualifier(); 7333 } else continue; 7334 7335 // using decls differ if one says 'typename' and the other doesn't. 7336 // FIXME: non-dependent using decls? 7337 if (HasTypenameKeyword != DTypename) continue; 7338 7339 // using decls differ if they name different scopes (but note that 7340 // template instantiation can cause this check to trigger when it 7341 // didn't before instantiation). 7342 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7343 Context.getCanonicalNestedNameSpecifier(DQual)) 7344 continue; 7345 7346 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7347 Diag(D->getLocation(), diag::note_using_decl) << 1; 7348 return true; 7349 } 7350 7351 return false; 7352} 7353 7354 7355/// Checks that the given nested-name qualifier used in a using decl 7356/// in the current context is appropriately related to the current 7357/// scope. If an error is found, diagnoses it and returns true. 7358bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7359 const CXXScopeSpec &SS, 7360 SourceLocation NameLoc) { 7361 DeclContext *NamedContext = computeDeclContext(SS); 7362 7363 if (!CurContext->isRecord()) { 7364 // C++03 [namespace.udecl]p3: 7365 // C++0x [namespace.udecl]p8: 7366 // A using-declaration for a class member shall be a member-declaration. 7367 7368 // If we weren't able to compute a valid scope, it must be a 7369 // dependent class scope. 7370 if (!NamedContext || NamedContext->isRecord()) { 7371 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7372 << SS.getRange(); 7373 return true; 7374 } 7375 7376 // Otherwise, everything is known to be fine. 7377 return false; 7378 } 7379 7380 // The current scope is a record. 7381 7382 // If the named context is dependent, we can't decide much. 7383 if (!NamedContext) { 7384 // FIXME: in C++0x, we can diagnose if we can prove that the 7385 // nested-name-specifier does not refer to a base class, which is 7386 // still possible in some cases. 7387 7388 // Otherwise we have to conservatively report that things might be 7389 // okay. 7390 return false; 7391 } 7392 7393 if (!NamedContext->isRecord()) { 7394 // Ideally this would point at the last name in the specifier, 7395 // but we don't have that level of source info. 7396 Diag(SS.getRange().getBegin(), 7397 diag::err_using_decl_nested_name_specifier_is_not_class) 7398 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7399 return true; 7400 } 7401 7402 if (!NamedContext->isDependentContext() && 7403 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7404 return true; 7405 7406 if (getLangOpts().CPlusPlus11) { 7407 // C++0x [namespace.udecl]p3: 7408 // In a using-declaration used as a member-declaration, the 7409 // nested-name-specifier shall name a base class of the class 7410 // being defined. 7411 7412 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7413 cast<CXXRecordDecl>(NamedContext))) { 7414 if (CurContext == NamedContext) { 7415 Diag(NameLoc, 7416 diag::err_using_decl_nested_name_specifier_is_current_class) 7417 << SS.getRange(); 7418 return true; 7419 } 7420 7421 Diag(SS.getRange().getBegin(), 7422 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7423 << (NestedNameSpecifier*) SS.getScopeRep() 7424 << cast<CXXRecordDecl>(CurContext) 7425 << SS.getRange(); 7426 return true; 7427 } 7428 7429 return false; 7430 } 7431 7432 // C++03 [namespace.udecl]p4: 7433 // A using-declaration used as a member-declaration shall refer 7434 // to a member of a base class of the class being defined [etc.]. 7435 7436 // Salient point: SS doesn't have to name a base class as long as 7437 // lookup only finds members from base classes. Therefore we can 7438 // diagnose here only if we can prove that that can't happen, 7439 // i.e. if the class hierarchies provably don't intersect. 7440 7441 // TODO: it would be nice if "definitely valid" results were cached 7442 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7443 // need to be repeated. 7444 7445 struct UserData { 7446 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7447 7448 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7449 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7450 Data->Bases.insert(Base); 7451 return true; 7452 } 7453 7454 bool hasDependentBases(const CXXRecordDecl *Class) { 7455 return !Class->forallBases(collect, this); 7456 } 7457 7458 /// Returns true if the base is dependent or is one of the 7459 /// accumulated base classes. 7460 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7461 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7462 return !Data->Bases.count(Base); 7463 } 7464 7465 bool mightShareBases(const CXXRecordDecl *Class) { 7466 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7467 } 7468 }; 7469 7470 UserData Data; 7471 7472 // Returns false if we find a dependent base. 7473 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7474 return false; 7475 7476 // Returns false if the class has a dependent base or if it or one 7477 // of its bases is present in the base set of the current context. 7478 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7479 return false; 7480 7481 Diag(SS.getRange().getBegin(), 7482 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7483 << (NestedNameSpecifier*) SS.getScopeRep() 7484 << cast<CXXRecordDecl>(CurContext) 7485 << SS.getRange(); 7486 7487 return true; 7488} 7489 7490Decl *Sema::ActOnAliasDeclaration(Scope *S, 7491 AccessSpecifier AS, 7492 MultiTemplateParamsArg TemplateParamLists, 7493 SourceLocation UsingLoc, 7494 UnqualifiedId &Name, 7495 AttributeList *AttrList, 7496 TypeResult Type) { 7497 // Skip up to the relevant declaration scope. 7498 while (S->getFlags() & Scope::TemplateParamScope) 7499 S = S->getParent(); 7500 assert((S->getFlags() & Scope::DeclScope) && 7501 "got alias-declaration outside of declaration scope"); 7502 7503 if (Type.isInvalid()) 7504 return 0; 7505 7506 bool Invalid = false; 7507 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7508 TypeSourceInfo *TInfo = 0; 7509 GetTypeFromParser(Type.get(), &TInfo); 7510 7511 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7512 return 0; 7513 7514 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7515 UPPC_DeclarationType)) { 7516 Invalid = true; 7517 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7518 TInfo->getTypeLoc().getBeginLoc()); 7519 } 7520 7521 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7522 LookupName(Previous, S); 7523 7524 // Warn about shadowing the name of a template parameter. 7525 if (Previous.isSingleResult() && 7526 Previous.getFoundDecl()->isTemplateParameter()) { 7527 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7528 Previous.clear(); 7529 } 7530 7531 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7532 "name in alias declaration must be an identifier"); 7533 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7534 Name.StartLocation, 7535 Name.Identifier, TInfo); 7536 7537 NewTD->setAccess(AS); 7538 7539 if (Invalid) 7540 NewTD->setInvalidDecl(); 7541 7542 ProcessDeclAttributeList(S, NewTD, AttrList); 7543 7544 CheckTypedefForVariablyModifiedType(S, NewTD); 7545 Invalid |= NewTD->isInvalidDecl(); 7546 7547 bool Redeclaration = false; 7548 7549 NamedDecl *NewND; 7550 if (TemplateParamLists.size()) { 7551 TypeAliasTemplateDecl *OldDecl = 0; 7552 TemplateParameterList *OldTemplateParams = 0; 7553 7554 if (TemplateParamLists.size() != 1) { 7555 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7556 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7557 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7558 } 7559 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7560 7561 // Only consider previous declarations in the same scope. 7562 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7563 /*ExplicitInstantiationOrSpecialization*/false); 7564 if (!Previous.empty()) { 7565 Redeclaration = true; 7566 7567 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7568 if (!OldDecl && !Invalid) { 7569 Diag(UsingLoc, diag::err_redefinition_different_kind) 7570 << Name.Identifier; 7571 7572 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7573 if (OldD->getLocation().isValid()) 7574 Diag(OldD->getLocation(), diag::note_previous_definition); 7575 7576 Invalid = true; 7577 } 7578 7579 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7580 if (TemplateParameterListsAreEqual(TemplateParams, 7581 OldDecl->getTemplateParameters(), 7582 /*Complain=*/true, 7583 TPL_TemplateMatch)) 7584 OldTemplateParams = OldDecl->getTemplateParameters(); 7585 else 7586 Invalid = true; 7587 7588 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7589 if (!Invalid && 7590 !Context.hasSameType(OldTD->getUnderlyingType(), 7591 NewTD->getUnderlyingType())) { 7592 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7593 // but we can't reasonably accept it. 7594 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7595 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7596 if (OldTD->getLocation().isValid()) 7597 Diag(OldTD->getLocation(), diag::note_previous_definition); 7598 Invalid = true; 7599 } 7600 } 7601 } 7602 7603 // Merge any previous default template arguments into our parameters, 7604 // and check the parameter list. 7605 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7606 TPC_TypeAliasTemplate)) 7607 return 0; 7608 7609 TypeAliasTemplateDecl *NewDecl = 7610 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7611 Name.Identifier, TemplateParams, 7612 NewTD); 7613 7614 NewDecl->setAccess(AS); 7615 7616 if (Invalid) 7617 NewDecl->setInvalidDecl(); 7618 else if (OldDecl) 7619 NewDecl->setPreviousDeclaration(OldDecl); 7620 7621 NewND = NewDecl; 7622 } else { 7623 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7624 NewND = NewTD; 7625 } 7626 7627 if (!Redeclaration) 7628 PushOnScopeChains(NewND, S); 7629 7630 ActOnDocumentableDecl(NewND); 7631 return NewND; 7632} 7633 7634Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7635 SourceLocation NamespaceLoc, 7636 SourceLocation AliasLoc, 7637 IdentifierInfo *Alias, 7638 CXXScopeSpec &SS, 7639 SourceLocation IdentLoc, 7640 IdentifierInfo *Ident) { 7641 7642 // Lookup the namespace name. 7643 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7644 LookupParsedName(R, S, &SS); 7645 7646 // Check if we have a previous declaration with the same name. 7647 NamedDecl *PrevDecl 7648 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7649 ForRedeclaration); 7650 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7651 PrevDecl = 0; 7652 7653 if (PrevDecl) { 7654 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7655 // We already have an alias with the same name that points to the same 7656 // namespace, so don't create a new one. 7657 // FIXME: At some point, we'll want to create the (redundant) 7658 // declaration to maintain better source information. 7659 if (!R.isAmbiguous() && !R.empty() && 7660 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7661 return 0; 7662 } 7663 7664 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7665 diag::err_redefinition_different_kind; 7666 Diag(AliasLoc, DiagID) << Alias; 7667 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7668 return 0; 7669 } 7670 7671 if (R.isAmbiguous()) 7672 return 0; 7673 7674 if (R.empty()) { 7675 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7676 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7677 return 0; 7678 } 7679 } 7680 7681 NamespaceAliasDecl *AliasDecl = 7682 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7683 Alias, SS.getWithLocInContext(Context), 7684 IdentLoc, R.getFoundDecl()); 7685 7686 PushOnScopeChains(AliasDecl, S); 7687 return AliasDecl; 7688} 7689 7690Sema::ImplicitExceptionSpecification 7691Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7692 CXXMethodDecl *MD) { 7693 CXXRecordDecl *ClassDecl = MD->getParent(); 7694 7695 // C++ [except.spec]p14: 7696 // An implicitly declared special member function (Clause 12) shall have an 7697 // exception-specification. [...] 7698 ImplicitExceptionSpecification ExceptSpec(*this); 7699 if (ClassDecl->isInvalidDecl()) 7700 return ExceptSpec; 7701 7702 // Direct base-class constructors. 7703 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7704 BEnd = ClassDecl->bases_end(); 7705 B != BEnd; ++B) { 7706 if (B->isVirtual()) // Handled below. 7707 continue; 7708 7709 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7710 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7711 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7712 // If this is a deleted function, add it anyway. This might be conformant 7713 // with the standard. This might not. I'm not sure. It might not matter. 7714 if (Constructor) 7715 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7716 } 7717 } 7718 7719 // Virtual base-class constructors. 7720 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7721 BEnd = ClassDecl->vbases_end(); 7722 B != BEnd; ++B) { 7723 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7724 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7725 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7726 // If this is a deleted function, add it anyway. This might be conformant 7727 // with the standard. This might not. I'm not sure. It might not matter. 7728 if (Constructor) 7729 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7730 } 7731 } 7732 7733 // Field constructors. 7734 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7735 FEnd = ClassDecl->field_end(); 7736 F != FEnd; ++F) { 7737 if (F->hasInClassInitializer()) { 7738 if (Expr *E = F->getInClassInitializer()) 7739 ExceptSpec.CalledExpr(E); 7740 else if (!F->isInvalidDecl()) 7741 // DR1351: 7742 // If the brace-or-equal-initializer of a non-static data member 7743 // invokes a defaulted default constructor of its class or of an 7744 // enclosing class in a potentially evaluated subexpression, the 7745 // program is ill-formed. 7746 // 7747 // This resolution is unworkable: the exception specification of the 7748 // default constructor can be needed in an unevaluated context, in 7749 // particular, in the operand of a noexcept-expression, and we can be 7750 // unable to compute an exception specification for an enclosed class. 7751 // 7752 // We do not allow an in-class initializer to require the evaluation 7753 // of the exception specification for any in-class initializer whose 7754 // definition is not lexically complete. 7755 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7756 } else if (const RecordType *RecordTy 7757 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7758 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7759 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7760 // If this is a deleted function, add it anyway. This might be conformant 7761 // with the standard. This might not. I'm not sure. It might not matter. 7762 // In particular, the problem is that this function never gets called. It 7763 // might just be ill-formed because this function attempts to refer to 7764 // a deleted function here. 7765 if (Constructor) 7766 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7767 } 7768 } 7769 7770 return ExceptSpec; 7771} 7772 7773Sema::ImplicitExceptionSpecification 7774Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7775 CXXRecordDecl *ClassDecl = CD->getParent(); 7776 7777 // C++ [except.spec]p14: 7778 // An inheriting constructor [...] shall have an exception-specification. [...] 7779 ImplicitExceptionSpecification ExceptSpec(*this); 7780 if (ClassDecl->isInvalidDecl()) 7781 return ExceptSpec; 7782 7783 // Inherited constructor. 7784 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7785 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7786 // FIXME: Copying or moving the parameters could add extra exceptions to the 7787 // set, as could the default arguments for the inherited constructor. This 7788 // will be addressed when we implement the resolution of core issue 1351. 7789 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7790 7791 // Direct base-class constructors. 7792 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7793 BEnd = ClassDecl->bases_end(); 7794 B != BEnd; ++B) { 7795 if (B->isVirtual()) // Handled below. 7796 continue; 7797 7798 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7800 if (BaseClassDecl == InheritedDecl) 7801 continue; 7802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7803 if (Constructor) 7804 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7805 } 7806 } 7807 7808 // Virtual base-class constructors. 7809 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7810 BEnd = ClassDecl->vbases_end(); 7811 B != BEnd; ++B) { 7812 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7813 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7814 if (BaseClassDecl == InheritedDecl) 7815 continue; 7816 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7817 if (Constructor) 7818 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7819 } 7820 } 7821 7822 // Field constructors. 7823 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7824 FEnd = ClassDecl->field_end(); 7825 F != FEnd; ++F) { 7826 if (F->hasInClassInitializer()) { 7827 if (Expr *E = F->getInClassInitializer()) 7828 ExceptSpec.CalledExpr(E); 7829 else if (!F->isInvalidDecl()) 7830 Diag(CD->getLocation(), 7831 diag::err_in_class_initializer_references_def_ctor) << CD; 7832 } else if (const RecordType *RecordTy 7833 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7834 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7835 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7836 if (Constructor) 7837 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7838 } 7839 } 7840 7841 return ExceptSpec; 7842} 7843 7844namespace { 7845/// RAII object to register a special member as being currently declared. 7846struct DeclaringSpecialMember { 7847 Sema &S; 7848 Sema::SpecialMemberDecl D; 7849 bool WasAlreadyBeingDeclared; 7850 7851 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7852 : S(S), D(RD, CSM) { 7853 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7854 if (WasAlreadyBeingDeclared) 7855 // This almost never happens, but if it does, ensure that our cache 7856 // doesn't contain a stale result. 7857 S.SpecialMemberCache.clear(); 7858 7859 // FIXME: Register a note to be produced if we encounter an error while 7860 // declaring the special member. 7861 } 7862 ~DeclaringSpecialMember() { 7863 if (!WasAlreadyBeingDeclared) 7864 S.SpecialMembersBeingDeclared.erase(D); 7865 } 7866 7867 /// \brief Are we already trying to declare this special member? 7868 bool isAlreadyBeingDeclared() const { 7869 return WasAlreadyBeingDeclared; 7870 } 7871}; 7872} 7873 7874CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7875 CXXRecordDecl *ClassDecl) { 7876 // C++ [class.ctor]p5: 7877 // A default constructor for a class X is a constructor of class X 7878 // that can be called without an argument. If there is no 7879 // user-declared constructor for class X, a default constructor is 7880 // implicitly declared. An implicitly-declared default constructor 7881 // is an inline public member of its class. 7882 assert(ClassDecl->needsImplicitDefaultConstructor() && 7883 "Should not build implicit default constructor!"); 7884 7885 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7886 if (DSM.isAlreadyBeingDeclared()) 7887 return 0; 7888 7889 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7890 CXXDefaultConstructor, 7891 false); 7892 7893 // Create the actual constructor declaration. 7894 CanQualType ClassType 7895 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7896 SourceLocation ClassLoc = ClassDecl->getLocation(); 7897 DeclarationName Name 7898 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7899 DeclarationNameInfo NameInfo(Name, ClassLoc); 7900 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7901 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7902 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7903 Constexpr); 7904 DefaultCon->setAccess(AS_public); 7905 DefaultCon->setDefaulted(); 7906 DefaultCon->setImplicit(); 7907 7908 // Build an exception specification pointing back at this constructor. 7909 FunctionProtoType::ExtProtoInfo EPI; 7910 EPI.ExceptionSpecType = EST_Unevaluated; 7911 EPI.ExceptionSpecDecl = DefaultCon; 7912 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 7913 7914 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7915 // constructors is easy to compute. 7916 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7917 7918 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7919 SetDeclDeleted(DefaultCon, ClassLoc); 7920 7921 // Note that we have declared this constructor. 7922 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7923 7924 if (Scope *S = getScopeForContext(ClassDecl)) 7925 PushOnScopeChains(DefaultCon, S, false); 7926 ClassDecl->addDecl(DefaultCon); 7927 7928 return DefaultCon; 7929} 7930 7931void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7932 CXXConstructorDecl *Constructor) { 7933 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7934 !Constructor->doesThisDeclarationHaveABody() && 7935 !Constructor->isDeleted()) && 7936 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7937 7938 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7939 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7940 7941 SynthesizedFunctionScope Scope(*this, Constructor); 7942 DiagnosticErrorTrap Trap(Diags); 7943 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7944 Trap.hasErrorOccurred()) { 7945 Diag(CurrentLocation, diag::note_member_synthesized_at) 7946 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7947 Constructor->setInvalidDecl(); 7948 return; 7949 } 7950 7951 SourceLocation Loc = Constructor->getLocation(); 7952 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7953 7954 Constructor->setUsed(); 7955 MarkVTableUsed(CurrentLocation, ClassDecl); 7956 7957 if (ASTMutationListener *L = getASTMutationListener()) { 7958 L->CompletedImplicitDefinition(Constructor); 7959 } 7960} 7961 7962void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7963 // Check that any explicitly-defaulted methods have exception specifications 7964 // compatible with their implicit exception specifications. 7965 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7966} 7967 7968namespace { 7969/// Information on inheriting constructors to declare. 7970class InheritingConstructorInfo { 7971public: 7972 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 7973 : SemaRef(SemaRef), Derived(Derived) { 7974 // Mark the constructors that we already have in the derived class. 7975 // 7976 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7977 // unless there is a user-declared constructor with the same signature in 7978 // the class where the using-declaration appears. 7979 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 7980 } 7981 7982 void inheritAll(CXXRecordDecl *RD) { 7983 visitAll(RD, &InheritingConstructorInfo::inherit); 7984 } 7985 7986private: 7987 /// Information about an inheriting constructor. 7988 struct InheritingConstructor { 7989 InheritingConstructor() 7990 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 7991 7992 /// If \c true, a constructor with this signature is already declared 7993 /// in the derived class. 7994 bool DeclaredInDerived; 7995 7996 /// The constructor which is inherited. 7997 const CXXConstructorDecl *BaseCtor; 7998 7999 /// The derived constructor we declared. 8000 CXXConstructorDecl *DerivedCtor; 8001 }; 8002 8003 /// Inheriting constructors with a given canonical type. There can be at 8004 /// most one such non-template constructor, and any number of templated 8005 /// constructors. 8006 struct InheritingConstructorsForType { 8007 InheritingConstructor NonTemplate; 8008 llvm::SmallVector< 8009 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates; 8010 8011 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8012 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8013 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8014 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8015 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8016 false, S.TPL_TemplateMatch)) 8017 return Templates[I].second; 8018 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8019 return Templates.back().second; 8020 } 8021 8022 return NonTemplate; 8023 } 8024 }; 8025 8026 /// Get or create the inheriting constructor record for a constructor. 8027 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8028 QualType CtorType) { 8029 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8030 .getEntry(SemaRef, Ctor); 8031 } 8032 8033 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8034 8035 /// Process all constructors for a class. 8036 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8037 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 8038 CtorE = RD->ctor_end(); 8039 CtorIt != CtorE; ++CtorIt) 8040 (this->*Callback)(*CtorIt); 8041 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8042 I(RD->decls_begin()), E(RD->decls_end()); 8043 I != E; ++I) { 8044 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8045 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8046 (this->*Callback)(CD); 8047 } 8048 } 8049 8050 /// Note that a constructor (or constructor template) was declared in Derived. 8051 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8052 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8053 } 8054 8055 /// Inherit a single constructor. 8056 void inherit(const CXXConstructorDecl *Ctor) { 8057 const FunctionProtoType *CtorType = 8058 Ctor->getType()->castAs<FunctionProtoType>(); 8059 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 8060 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8061 8062 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8063 8064 // Core issue (no number yet): the ellipsis is always discarded. 8065 if (EPI.Variadic) { 8066 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8067 SemaRef.Diag(Ctor->getLocation(), 8068 diag::note_using_decl_constructor_ellipsis); 8069 EPI.Variadic = false; 8070 } 8071 8072 // Declare a constructor for each number of parameters. 8073 // 8074 // C++11 [class.inhctor]p1: 8075 // The candidate set of inherited constructors from the class X named in 8076 // the using-declaration consists of [... modulo defects ...] for each 8077 // constructor or constructor template of X, the set of constructors or 8078 // constructor templates that results from omitting any ellipsis parameter 8079 // specification and successively omitting parameters with a default 8080 // argument from the end of the parameter-type-list 8081 unsigned MinParams = minParamsToInherit(Ctor); 8082 unsigned Params = Ctor->getNumParams(); 8083 if (Params >= MinParams) { 8084 do 8085 declareCtor(UsingLoc, Ctor, 8086 SemaRef.Context.getFunctionType( 8087 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 8088 while (Params > MinParams && 8089 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8090 } 8091 } 8092 8093 /// Find the using-declaration which specified that we should inherit the 8094 /// constructors of \p Base. 8095 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8096 // No fancy lookup required; just look for the base constructor name 8097 // directly within the derived class. 8098 ASTContext &Context = SemaRef.Context; 8099 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8100 Context.getCanonicalType(Context.getRecordType(Base))); 8101 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8102 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8103 } 8104 8105 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8106 // C++11 [class.inhctor]p3: 8107 // [F]or each constructor template in the candidate set of inherited 8108 // constructors, a constructor template is implicitly declared 8109 if (Ctor->getDescribedFunctionTemplate()) 8110 return 0; 8111 8112 // For each non-template constructor in the candidate set of inherited 8113 // constructors other than a constructor having no parameters or a 8114 // copy/move constructor having a single parameter, a constructor is 8115 // implicitly declared [...] 8116 if (Ctor->getNumParams() == 0) 8117 return 1; 8118 if (Ctor->isCopyOrMoveConstructor()) 8119 return 2; 8120 8121 // Per discussion on core reflector, never inherit a constructor which 8122 // would become a default, copy, or move constructor of Derived either. 8123 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8124 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8125 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8126 } 8127 8128 /// Declare a single inheriting constructor, inheriting the specified 8129 /// constructor, with the given type. 8130 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8131 QualType DerivedType) { 8132 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8133 8134 // C++11 [class.inhctor]p3: 8135 // ... a constructor is implicitly declared with the same constructor 8136 // characteristics unless there is a user-declared constructor with 8137 // the same signature in the class where the using-declaration appears 8138 if (Entry.DeclaredInDerived) 8139 return; 8140 8141 // C++11 [class.inhctor]p7: 8142 // If two using-declarations declare inheriting constructors with the 8143 // same signature, the program is ill-formed 8144 if (Entry.DerivedCtor) { 8145 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8146 // Only diagnose this once per constructor. 8147 if (Entry.DerivedCtor->isInvalidDecl()) 8148 return; 8149 Entry.DerivedCtor->setInvalidDecl(); 8150 8151 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8152 SemaRef.Diag(BaseCtor->getLocation(), 8153 diag::note_using_decl_constructor_conflict_current_ctor); 8154 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8155 diag::note_using_decl_constructor_conflict_previous_ctor); 8156 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8157 diag::note_using_decl_constructor_conflict_previous_using); 8158 } else { 8159 // Core issue (no number): if the same inheriting constructor is 8160 // produced by multiple base class constructors from the same base 8161 // class, the inheriting constructor is defined as deleted. 8162 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8163 } 8164 8165 return; 8166 } 8167 8168 ASTContext &Context = SemaRef.Context; 8169 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8170 Context.getCanonicalType(Context.getRecordType(Derived))); 8171 DeclarationNameInfo NameInfo(Name, UsingLoc); 8172 8173 TemplateParameterList *TemplateParams = 0; 8174 if (const FunctionTemplateDecl *FTD = 8175 BaseCtor->getDescribedFunctionTemplate()) { 8176 TemplateParams = FTD->getTemplateParameters(); 8177 // We're reusing template parameters from a different DeclContext. This 8178 // is questionable at best, but works out because the template depth in 8179 // both places is guaranteed to be 0. 8180 // FIXME: Rebuild the template parameters in the new context, and 8181 // transform the function type to refer to them. 8182 } 8183 8184 // Build type source info pointing at the using-declaration. This is 8185 // required by template instantiation. 8186 TypeSourceInfo *TInfo = 8187 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8188 FunctionProtoTypeLoc ProtoLoc = 8189 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8190 8191 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8192 Context, Derived, UsingLoc, NameInfo, DerivedType, 8193 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8194 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8195 8196 // Build an unevaluated exception specification for this constructor. 8197 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8198 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8199 EPI.ExceptionSpecType = EST_Unevaluated; 8200 EPI.ExceptionSpecDecl = DerivedCtor; 8201 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8202 FPT->getArgTypes(), EPI)); 8203 8204 // Build the parameter declarations. 8205 SmallVector<ParmVarDecl *, 16> ParamDecls; 8206 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8207 TypeSourceInfo *TInfo = 8208 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8209 ParmVarDecl *PD = ParmVarDecl::Create( 8210 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8211 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8212 PD->setScopeInfo(0, I); 8213 PD->setImplicit(); 8214 ParamDecls.push_back(PD); 8215 ProtoLoc.setArg(I, PD); 8216 } 8217 8218 // Set up the new constructor. 8219 DerivedCtor->setAccess(BaseCtor->getAccess()); 8220 DerivedCtor->setParams(ParamDecls); 8221 DerivedCtor->setInheritedConstructor(BaseCtor); 8222 if (BaseCtor->isDeleted()) 8223 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8224 8225 // If this is a constructor template, build the template declaration. 8226 if (TemplateParams) { 8227 FunctionTemplateDecl *DerivedTemplate = 8228 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8229 TemplateParams, DerivedCtor); 8230 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8231 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8232 Derived->addDecl(DerivedTemplate); 8233 } else { 8234 Derived->addDecl(DerivedCtor); 8235 } 8236 8237 Entry.BaseCtor = BaseCtor; 8238 Entry.DerivedCtor = DerivedCtor; 8239 } 8240 8241 Sema &SemaRef; 8242 CXXRecordDecl *Derived; 8243 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8244 MapType Map; 8245}; 8246} 8247 8248void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8249 // Defer declaring the inheriting constructors until the class is 8250 // instantiated. 8251 if (ClassDecl->isDependentContext()) 8252 return; 8253 8254 // Find base classes from which we might inherit constructors. 8255 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8256 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8257 BaseE = ClassDecl->bases_end(); 8258 BaseIt != BaseE; ++BaseIt) 8259 if (BaseIt->getInheritConstructors()) 8260 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8261 8262 // Go no further if we're not inheriting any constructors. 8263 if (InheritedBases.empty()) 8264 return; 8265 8266 // Declare the inherited constructors. 8267 InheritingConstructorInfo ICI(*this, ClassDecl); 8268 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8269 ICI.inheritAll(InheritedBases[I]); 8270} 8271 8272void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8273 CXXConstructorDecl *Constructor) { 8274 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8275 assert(Constructor->getInheritedConstructor() && 8276 !Constructor->doesThisDeclarationHaveABody() && 8277 !Constructor->isDeleted()); 8278 8279 SynthesizedFunctionScope Scope(*this, Constructor); 8280 DiagnosticErrorTrap Trap(Diags); 8281 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8282 Trap.hasErrorOccurred()) { 8283 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8284 << Context.getTagDeclType(ClassDecl); 8285 Constructor->setInvalidDecl(); 8286 return; 8287 } 8288 8289 SourceLocation Loc = Constructor->getLocation(); 8290 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8291 8292 Constructor->setUsed(); 8293 MarkVTableUsed(CurrentLocation, ClassDecl); 8294 8295 if (ASTMutationListener *L = getASTMutationListener()) { 8296 L->CompletedImplicitDefinition(Constructor); 8297 } 8298} 8299 8300 8301Sema::ImplicitExceptionSpecification 8302Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8303 CXXRecordDecl *ClassDecl = MD->getParent(); 8304 8305 // C++ [except.spec]p14: 8306 // An implicitly declared special member function (Clause 12) shall have 8307 // an exception-specification. 8308 ImplicitExceptionSpecification ExceptSpec(*this); 8309 if (ClassDecl->isInvalidDecl()) 8310 return ExceptSpec; 8311 8312 // Direct base-class destructors. 8313 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8314 BEnd = ClassDecl->bases_end(); 8315 B != BEnd; ++B) { 8316 if (B->isVirtual()) // Handled below. 8317 continue; 8318 8319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8320 ExceptSpec.CalledDecl(B->getLocStart(), 8321 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8322 } 8323 8324 // Virtual base-class destructors. 8325 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8326 BEnd = ClassDecl->vbases_end(); 8327 B != BEnd; ++B) { 8328 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8329 ExceptSpec.CalledDecl(B->getLocStart(), 8330 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8331 } 8332 8333 // Field destructors. 8334 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8335 FEnd = ClassDecl->field_end(); 8336 F != FEnd; ++F) { 8337 if (const RecordType *RecordTy 8338 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8339 ExceptSpec.CalledDecl(F->getLocation(), 8340 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8341 } 8342 8343 return ExceptSpec; 8344} 8345 8346CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8347 // C++ [class.dtor]p2: 8348 // If a class has no user-declared destructor, a destructor is 8349 // declared implicitly. An implicitly-declared destructor is an 8350 // inline public member of its class. 8351 assert(ClassDecl->needsImplicitDestructor()); 8352 8353 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8354 if (DSM.isAlreadyBeingDeclared()) 8355 return 0; 8356 8357 // Create the actual destructor declaration. 8358 CanQualType ClassType 8359 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8360 SourceLocation ClassLoc = ClassDecl->getLocation(); 8361 DeclarationName Name 8362 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8363 DeclarationNameInfo NameInfo(Name, ClassLoc); 8364 CXXDestructorDecl *Destructor 8365 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8366 QualType(), 0, /*isInline=*/true, 8367 /*isImplicitlyDeclared=*/true); 8368 Destructor->setAccess(AS_public); 8369 Destructor->setDefaulted(); 8370 Destructor->setImplicit(); 8371 8372 // Build an exception specification pointing back at this destructor. 8373 FunctionProtoType::ExtProtoInfo EPI; 8374 EPI.ExceptionSpecType = EST_Unevaluated; 8375 EPI.ExceptionSpecDecl = Destructor; 8376 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8377 8378 AddOverriddenMethods(ClassDecl, Destructor); 8379 8380 // We don't need to use SpecialMemberIsTrivial here; triviality for 8381 // destructors is easy to compute. 8382 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8383 8384 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8385 SetDeclDeleted(Destructor, ClassLoc); 8386 8387 // Note that we have declared this destructor. 8388 ++ASTContext::NumImplicitDestructorsDeclared; 8389 8390 // Introduce this destructor into its scope. 8391 if (Scope *S = getScopeForContext(ClassDecl)) 8392 PushOnScopeChains(Destructor, S, false); 8393 ClassDecl->addDecl(Destructor); 8394 8395 return Destructor; 8396} 8397 8398void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8399 CXXDestructorDecl *Destructor) { 8400 assert((Destructor->isDefaulted() && 8401 !Destructor->doesThisDeclarationHaveABody() && 8402 !Destructor->isDeleted()) && 8403 "DefineImplicitDestructor - call it for implicit default dtor"); 8404 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8405 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8406 8407 if (Destructor->isInvalidDecl()) 8408 return; 8409 8410 SynthesizedFunctionScope Scope(*this, Destructor); 8411 8412 DiagnosticErrorTrap Trap(Diags); 8413 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8414 Destructor->getParent()); 8415 8416 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8417 Diag(CurrentLocation, diag::note_member_synthesized_at) 8418 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8419 8420 Destructor->setInvalidDecl(); 8421 return; 8422 } 8423 8424 SourceLocation Loc = Destructor->getLocation(); 8425 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8426 Destructor->setImplicitlyDefined(true); 8427 Destructor->setUsed(); 8428 MarkVTableUsed(CurrentLocation, ClassDecl); 8429 8430 if (ASTMutationListener *L = getASTMutationListener()) { 8431 L->CompletedImplicitDefinition(Destructor); 8432 } 8433} 8434 8435/// \brief Perform any semantic analysis which needs to be delayed until all 8436/// pending class member declarations have been parsed. 8437void Sema::ActOnFinishCXXMemberDecls() { 8438 // If the context is an invalid C++ class, just suppress these checks. 8439 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8440 if (Record->isInvalidDecl()) { 8441 DelayedDestructorExceptionSpecChecks.clear(); 8442 return; 8443 } 8444 } 8445 8446 // Perform any deferred checking of exception specifications for virtual 8447 // destructors. 8448 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8449 i != e; ++i) { 8450 const CXXDestructorDecl *Dtor = 8451 DelayedDestructorExceptionSpecChecks[i].first; 8452 assert(!Dtor->getParent()->isDependentType() && 8453 "Should not ever add destructors of templates into the list."); 8454 CheckOverridingFunctionExceptionSpec(Dtor, 8455 DelayedDestructorExceptionSpecChecks[i].second); 8456 } 8457 DelayedDestructorExceptionSpecChecks.clear(); 8458} 8459 8460void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8461 CXXDestructorDecl *Destructor) { 8462 assert(getLangOpts().CPlusPlus11 && 8463 "adjusting dtor exception specs was introduced in c++11"); 8464 8465 // C++11 [class.dtor]p3: 8466 // A declaration of a destructor that does not have an exception- 8467 // specification is implicitly considered to have the same exception- 8468 // specification as an implicit declaration. 8469 const FunctionProtoType *DtorType = Destructor->getType()-> 8470 getAs<FunctionProtoType>(); 8471 if (DtorType->hasExceptionSpec()) 8472 return; 8473 8474 // Replace the destructor's type, building off the existing one. Fortunately, 8475 // the only thing of interest in the destructor type is its extended info. 8476 // The return and arguments are fixed. 8477 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8478 EPI.ExceptionSpecType = EST_Unevaluated; 8479 EPI.ExceptionSpecDecl = Destructor; 8480 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8481 8482 // FIXME: If the destructor has a body that could throw, and the newly created 8483 // spec doesn't allow exceptions, we should emit a warning, because this 8484 // change in behavior can break conforming C++03 programs at runtime. 8485 // However, we don't have a body or an exception specification yet, so it 8486 // needs to be done somewhere else. 8487} 8488 8489/// When generating a defaulted copy or move assignment operator, if a field 8490/// should be copied with __builtin_memcpy rather than via explicit assignments, 8491/// do so. This optimization only applies for arrays of scalars, and for arrays 8492/// of class type where the selected copy/move-assignment operator is trivial. 8493static StmtResult 8494buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8495 Expr *To, Expr *From) { 8496 // Compute the size of the memory buffer to be copied. 8497 QualType SizeType = S.Context.getSizeType(); 8498 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8499 S.Context.getTypeSizeInChars(T).getQuantity()); 8500 8501 // Take the address of the field references for "from" and "to". We 8502 // directly construct UnaryOperators here because semantic analysis 8503 // does not permit us to take the address of an xvalue. 8504 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8505 S.Context.getPointerType(From->getType()), 8506 VK_RValue, OK_Ordinary, Loc); 8507 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8508 S.Context.getPointerType(To->getType()), 8509 VK_RValue, OK_Ordinary, Loc); 8510 8511 const Type *E = T->getBaseElementTypeUnsafe(); 8512 bool NeedsCollectableMemCpy = 8513 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8514 8515 // Create a reference to the __builtin_objc_memmove_collectable function 8516 StringRef MemCpyName = NeedsCollectableMemCpy ? 8517 "__builtin_objc_memmove_collectable" : 8518 "__builtin_memcpy"; 8519 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8520 Sema::LookupOrdinaryName); 8521 S.LookupName(R, S.TUScope, true); 8522 8523 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8524 if (!MemCpy) 8525 // Something went horribly wrong earlier, and we will have complained 8526 // about it. 8527 return StmtError(); 8528 8529 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8530 VK_RValue, Loc, 0); 8531 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8532 8533 Expr *CallArgs[] = { 8534 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8535 }; 8536 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8537 Loc, CallArgs, Loc); 8538 8539 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8540 return S.Owned(Call.takeAs<Stmt>()); 8541} 8542 8543/// \brief Builds a statement that copies/moves the given entity from \p From to 8544/// \c To. 8545/// 8546/// This routine is used to copy/move the members of a class with an 8547/// implicitly-declared copy/move assignment operator. When the entities being 8548/// copied are arrays, this routine builds for loops to copy them. 8549/// 8550/// \param S The Sema object used for type-checking. 8551/// 8552/// \param Loc The location where the implicit copy/move is being generated. 8553/// 8554/// \param T The type of the expressions being copied/moved. Both expressions 8555/// must have this type. 8556/// 8557/// \param To The expression we are copying/moving to. 8558/// 8559/// \param From The expression we are copying/moving from. 8560/// 8561/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8562/// Otherwise, it's a non-static member subobject. 8563/// 8564/// \param Copying Whether we're copying or moving. 8565/// 8566/// \param Depth Internal parameter recording the depth of the recursion. 8567/// 8568/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8569/// if a memcpy should be used instead. 8570static StmtResult 8571buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8572 Expr *To, Expr *From, 8573 bool CopyingBaseSubobject, bool Copying, 8574 unsigned Depth = 0) { 8575 // C++11 [class.copy]p28: 8576 // Each subobject is assigned in the manner appropriate to its type: 8577 // 8578 // - if the subobject is of class type, as if by a call to operator= with 8579 // the subobject as the object expression and the corresponding 8580 // subobject of x as a single function argument (as if by explicit 8581 // qualification; that is, ignoring any possible virtual overriding 8582 // functions in more derived classes); 8583 // 8584 // C++03 [class.copy]p13: 8585 // - if the subobject is of class type, the copy assignment operator for 8586 // the class is used (as if by explicit qualification; that is, 8587 // ignoring any possible virtual overriding functions in more derived 8588 // classes); 8589 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8590 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8591 8592 // Look for operator=. 8593 DeclarationName Name 8594 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8595 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8596 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8597 8598 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8599 // operator. 8600 if (!S.getLangOpts().CPlusPlus11) { 8601 LookupResult::Filter F = OpLookup.makeFilter(); 8602 while (F.hasNext()) { 8603 NamedDecl *D = F.next(); 8604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8605 if (Method->isCopyAssignmentOperator() || 8606 (!Copying && Method->isMoveAssignmentOperator())) 8607 continue; 8608 8609 F.erase(); 8610 } 8611 F.done(); 8612 } 8613 8614 // Suppress the protected check (C++ [class.protected]) for each of the 8615 // assignment operators we found. This strange dance is required when 8616 // we're assigning via a base classes's copy-assignment operator. To 8617 // ensure that we're getting the right base class subobject (without 8618 // ambiguities), we need to cast "this" to that subobject type; to 8619 // ensure that we don't go through the virtual call mechanism, we need 8620 // to qualify the operator= name with the base class (see below). However, 8621 // this means that if the base class has a protected copy assignment 8622 // operator, the protected member access check will fail. So, we 8623 // rewrite "protected" access to "public" access in this case, since we 8624 // know by construction that we're calling from a derived class. 8625 if (CopyingBaseSubobject) { 8626 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8627 L != LEnd; ++L) { 8628 if (L.getAccess() == AS_protected) 8629 L.setAccess(AS_public); 8630 } 8631 } 8632 8633 // Create the nested-name-specifier that will be used to qualify the 8634 // reference to operator=; this is required to suppress the virtual 8635 // call mechanism. 8636 CXXScopeSpec SS; 8637 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8638 SS.MakeTrivial(S.Context, 8639 NestedNameSpecifier::Create(S.Context, 0, false, 8640 CanonicalT), 8641 Loc); 8642 8643 // Create the reference to operator=. 8644 ExprResult OpEqualRef 8645 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8646 /*TemplateKWLoc=*/SourceLocation(), 8647 /*FirstQualifierInScope=*/0, 8648 OpLookup, 8649 /*TemplateArgs=*/0, 8650 /*SuppressQualifierCheck=*/true); 8651 if (OpEqualRef.isInvalid()) 8652 return StmtError(); 8653 8654 // Build the call to the assignment operator. 8655 8656 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8657 OpEqualRef.takeAs<Expr>(), 8658 Loc, From, Loc); 8659 if (Call.isInvalid()) 8660 return StmtError(); 8661 8662 // If we built a call to a trivial 'operator=' while copying an array, 8663 // bail out. We'll replace the whole shebang with a memcpy. 8664 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8665 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8666 return StmtResult((Stmt*)0); 8667 8668 // Convert to an expression-statement, and clean up any produced 8669 // temporaries. 8670 return S.ActOnExprStmt(Call); 8671 } 8672 8673 // - if the subobject is of scalar type, the built-in assignment 8674 // operator is used. 8675 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8676 if (!ArrayTy) { 8677 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8678 if (Assignment.isInvalid()) 8679 return StmtError(); 8680 return S.ActOnExprStmt(Assignment); 8681 } 8682 8683 // - if the subobject is an array, each element is assigned, in the 8684 // manner appropriate to the element type; 8685 8686 // Construct a loop over the array bounds, e.g., 8687 // 8688 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8689 // 8690 // that will copy each of the array elements. 8691 QualType SizeType = S.Context.getSizeType(); 8692 8693 // Create the iteration variable. 8694 IdentifierInfo *IterationVarName = 0; 8695 { 8696 SmallString<8> Str; 8697 llvm::raw_svector_ostream OS(Str); 8698 OS << "__i" << Depth; 8699 IterationVarName = &S.Context.Idents.get(OS.str()); 8700 } 8701 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8702 IterationVarName, SizeType, 8703 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8704 SC_None); 8705 8706 // Initialize the iteration variable to zero. 8707 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8708 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8709 8710 // Create a reference to the iteration variable; we'll use this several 8711 // times throughout. 8712 Expr *IterationVarRef 8713 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8714 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8715 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8716 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8717 8718 // Create the DeclStmt that holds the iteration variable. 8719 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8720 8721 // Subscript the "from" and "to" expressions with the iteration variable. 8722 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8723 IterationVarRefRVal, 8724 Loc)); 8725 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8726 IterationVarRefRVal, 8727 Loc)); 8728 if (!Copying) // Cast to rvalue 8729 From = CastForMoving(S, From); 8730 8731 // Build the copy/move for an individual element of the array. 8732 StmtResult Copy = 8733 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8734 To, From, CopyingBaseSubobject, 8735 Copying, Depth + 1); 8736 // Bail out if copying fails or if we determined that we should use memcpy. 8737 if (Copy.isInvalid() || !Copy.get()) 8738 return Copy; 8739 8740 // Create the comparison against the array bound. 8741 llvm::APInt Upper 8742 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8743 Expr *Comparison 8744 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8745 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8746 BO_NE, S.Context.BoolTy, 8747 VK_RValue, OK_Ordinary, Loc, false); 8748 8749 // Create the pre-increment of the iteration variable. 8750 Expr *Increment 8751 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8752 VK_LValue, OK_Ordinary, Loc); 8753 8754 // Construct the loop that copies all elements of this array. 8755 return S.ActOnForStmt(Loc, Loc, InitStmt, 8756 S.MakeFullExpr(Comparison), 8757 0, S.MakeFullDiscardedValueExpr(Increment), 8758 Loc, Copy.take()); 8759} 8760 8761static StmtResult 8762buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8763 Expr *To, Expr *From, 8764 bool CopyingBaseSubobject, bool Copying) { 8765 // Maybe we should use a memcpy? 8766 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8767 T.isTriviallyCopyableType(S.Context)) 8768 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8769 8770 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8771 CopyingBaseSubobject, 8772 Copying, 0)); 8773 8774 // If we ended up picking a trivial assignment operator for an array of a 8775 // non-trivially-copyable class type, just emit a memcpy. 8776 if (!Result.isInvalid() && !Result.get()) 8777 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8778 8779 return Result; 8780} 8781 8782Sema::ImplicitExceptionSpecification 8783Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8784 CXXRecordDecl *ClassDecl = MD->getParent(); 8785 8786 ImplicitExceptionSpecification ExceptSpec(*this); 8787 if (ClassDecl->isInvalidDecl()) 8788 return ExceptSpec; 8789 8790 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8791 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8792 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8793 8794 // C++ [except.spec]p14: 8795 // An implicitly declared special member function (Clause 12) shall have an 8796 // exception-specification. [...] 8797 8798 // It is unspecified whether or not an implicit copy assignment operator 8799 // attempts to deduplicate calls to assignment operators of virtual bases are 8800 // made. As such, this exception specification is effectively unspecified. 8801 // Based on a similar decision made for constness in C++0x, we're erring on 8802 // the side of assuming such calls to be made regardless of whether they 8803 // actually happen. 8804 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8805 BaseEnd = ClassDecl->bases_end(); 8806 Base != BaseEnd; ++Base) { 8807 if (Base->isVirtual()) 8808 continue; 8809 8810 CXXRecordDecl *BaseClassDecl 8811 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8812 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8813 ArgQuals, false, 0)) 8814 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8815 } 8816 8817 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8818 BaseEnd = ClassDecl->vbases_end(); 8819 Base != BaseEnd; ++Base) { 8820 CXXRecordDecl *BaseClassDecl 8821 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8822 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8823 ArgQuals, false, 0)) 8824 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8825 } 8826 8827 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8828 FieldEnd = ClassDecl->field_end(); 8829 Field != FieldEnd; 8830 ++Field) { 8831 QualType FieldType = Context.getBaseElementType(Field->getType()); 8832 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8833 if (CXXMethodDecl *CopyAssign = 8834 LookupCopyingAssignment(FieldClassDecl, 8835 ArgQuals | FieldType.getCVRQualifiers(), 8836 false, 0)) 8837 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8838 } 8839 } 8840 8841 return ExceptSpec; 8842} 8843 8844CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8845 // Note: The following rules are largely analoguous to the copy 8846 // constructor rules. Note that virtual bases are not taken into account 8847 // for determining the argument type of the operator. Note also that 8848 // operators taking an object instead of a reference are allowed. 8849 assert(ClassDecl->needsImplicitCopyAssignment()); 8850 8851 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8852 if (DSM.isAlreadyBeingDeclared()) 8853 return 0; 8854 8855 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8856 QualType RetType = Context.getLValueReferenceType(ArgType); 8857 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 8858 if (Const) 8859 ArgType = ArgType.withConst(); 8860 ArgType = Context.getLValueReferenceType(ArgType); 8861 8862 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8863 CXXCopyAssignment, 8864 Const); 8865 8866 // An implicitly-declared copy assignment operator is an inline public 8867 // member of its class. 8868 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8869 SourceLocation ClassLoc = ClassDecl->getLocation(); 8870 DeclarationNameInfo NameInfo(Name, ClassLoc); 8871 CXXMethodDecl *CopyAssignment = 8872 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8873 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 8874 /*isInline=*/ true, Constexpr, SourceLocation()); 8875 CopyAssignment->setAccess(AS_public); 8876 CopyAssignment->setDefaulted(); 8877 CopyAssignment->setImplicit(); 8878 8879 // Build an exception specification pointing back at this member. 8880 FunctionProtoType::ExtProtoInfo EPI; 8881 EPI.ExceptionSpecType = EST_Unevaluated; 8882 EPI.ExceptionSpecDecl = CopyAssignment; 8883 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8884 8885 // Add the parameter to the operator. 8886 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8887 ClassLoc, ClassLoc, /*Id=*/0, 8888 ArgType, /*TInfo=*/0, 8889 SC_None, 0); 8890 CopyAssignment->setParams(FromParam); 8891 8892 AddOverriddenMethods(ClassDecl, CopyAssignment); 8893 8894 CopyAssignment->setTrivial( 8895 ClassDecl->needsOverloadResolutionForCopyAssignment() 8896 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8897 : ClassDecl->hasTrivialCopyAssignment()); 8898 8899 // C++11 [class.copy]p19: 8900 // .... If the class definition does not explicitly declare a copy 8901 // assignment operator, there is no user-declared move constructor, and 8902 // there is no user-declared move assignment operator, a copy assignment 8903 // operator is implicitly declared as defaulted. 8904 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8905 SetDeclDeleted(CopyAssignment, ClassLoc); 8906 8907 // Note that we have added this copy-assignment operator. 8908 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8909 8910 if (Scope *S = getScopeForContext(ClassDecl)) 8911 PushOnScopeChains(CopyAssignment, S, false); 8912 ClassDecl->addDecl(CopyAssignment); 8913 8914 return CopyAssignment; 8915} 8916 8917/// Diagnose an implicit copy operation for a class which is odr-used, but 8918/// which is deprecated because the class has a user-declared copy constructor, 8919/// copy assignment operator, or destructor. 8920static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 8921 SourceLocation UseLoc) { 8922 assert(CopyOp->isImplicit()); 8923 8924 CXXRecordDecl *RD = CopyOp->getParent(); 8925 CXXMethodDecl *UserDeclaredOperation = 0; 8926 8927 // In Microsoft mode, assignment operations don't affect constructors and 8928 // vice versa. 8929 if (RD->hasUserDeclaredDestructor()) { 8930 UserDeclaredOperation = RD->getDestructor(); 8931 } else if (!isa<CXXConstructorDecl>(CopyOp) && 8932 RD->hasUserDeclaredCopyConstructor() && 8933 !S.getLangOpts().MicrosoftMode) { 8934 // Find any user-declared copy constructor. 8935 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 8936 E = RD->ctor_end(); I != E; ++I) { 8937 if (I->isCopyConstructor()) { 8938 UserDeclaredOperation = *I; 8939 break; 8940 } 8941 } 8942 assert(UserDeclaredOperation); 8943 } else if (isa<CXXConstructorDecl>(CopyOp) && 8944 RD->hasUserDeclaredCopyAssignment() && 8945 !S.getLangOpts().MicrosoftMode) { 8946 // Find any user-declared move assignment operator. 8947 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 8948 E = RD->method_end(); I != E; ++I) { 8949 if (I->isCopyAssignmentOperator()) { 8950 UserDeclaredOperation = *I; 8951 break; 8952 } 8953 } 8954 assert(UserDeclaredOperation); 8955 } 8956 8957 if (UserDeclaredOperation) { 8958 S.Diag(UserDeclaredOperation->getLocation(), 8959 diag::warn_deprecated_copy_operation) 8960 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 8961 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 8962 S.Diag(UseLoc, diag::note_member_synthesized_at) 8963 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 8964 : Sema::CXXCopyAssignment) 8965 << RD; 8966 } 8967} 8968 8969void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8970 CXXMethodDecl *CopyAssignOperator) { 8971 assert((CopyAssignOperator->isDefaulted() && 8972 CopyAssignOperator->isOverloadedOperator() && 8973 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8974 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8975 !CopyAssignOperator->isDeleted()) && 8976 "DefineImplicitCopyAssignment called for wrong function"); 8977 8978 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8979 8980 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8981 CopyAssignOperator->setInvalidDecl(); 8982 return; 8983 } 8984 8985 // C++11 [class.copy]p18: 8986 // The [definition of an implicitly declared copy assignment operator] is 8987 // deprecated if the class has a user-declared copy constructor or a 8988 // user-declared destructor. 8989 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 8990 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 8991 8992 CopyAssignOperator->setUsed(); 8993 8994 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8995 DiagnosticErrorTrap Trap(Diags); 8996 8997 // C++0x [class.copy]p30: 8998 // The implicitly-defined or explicitly-defaulted copy assignment operator 8999 // for a non-union class X performs memberwise copy assignment of its 9000 // subobjects. The direct base classes of X are assigned first, in the 9001 // order of their declaration in the base-specifier-list, and then the 9002 // immediate non-static data members of X are assigned, in the order in 9003 // which they were declared in the class definition. 9004 9005 // The statements that form the synthesized function body. 9006 SmallVector<Stmt*, 8> Statements; 9007 9008 // The parameter for the "other" object, which we are copying from. 9009 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9010 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9011 QualType OtherRefType = Other->getType(); 9012 if (const LValueReferenceType *OtherRef 9013 = OtherRefType->getAs<LValueReferenceType>()) { 9014 OtherRefType = OtherRef->getPointeeType(); 9015 OtherQuals = OtherRefType.getQualifiers(); 9016 } 9017 9018 // Our location for everything implicitly-generated. 9019 SourceLocation Loc = CopyAssignOperator->getLocation(); 9020 9021 // Construct a reference to the "other" object. We'll be using this 9022 // throughout the generated ASTs. 9023 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9024 assert(OtherRef && "Reference to parameter cannot fail!"); 9025 9026 // Construct the "this" pointer. We'll be using this throughout the generated 9027 // ASTs. 9028 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9029 assert(This && "Reference to this cannot fail!"); 9030 9031 // Assign base classes. 9032 bool Invalid = false; 9033 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9034 E = ClassDecl->bases_end(); Base != E; ++Base) { 9035 // Form the assignment: 9036 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9037 QualType BaseType = Base->getType().getUnqualifiedType(); 9038 if (!BaseType->isRecordType()) { 9039 Invalid = true; 9040 continue; 9041 } 9042 9043 CXXCastPath BasePath; 9044 BasePath.push_back(Base); 9045 9046 // Construct the "from" expression, which is an implicit cast to the 9047 // appropriately-qualified base type. 9048 Expr *From = OtherRef; 9049 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 9050 CK_UncheckedDerivedToBase, 9051 VK_LValue, &BasePath).take(); 9052 9053 // Dereference "this". 9054 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9055 9056 // Implicitly cast "this" to the appropriately-qualified base type. 9057 To = ImpCastExprToType(To.take(), 9058 Context.getCVRQualifiedType(BaseType, 9059 CopyAssignOperator->getTypeQualifiers()), 9060 CK_UncheckedDerivedToBase, 9061 VK_LValue, &BasePath); 9062 9063 // Build the copy. 9064 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9065 To.get(), From, 9066 /*CopyingBaseSubobject=*/true, 9067 /*Copying=*/true); 9068 if (Copy.isInvalid()) { 9069 Diag(CurrentLocation, diag::note_member_synthesized_at) 9070 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9071 CopyAssignOperator->setInvalidDecl(); 9072 return; 9073 } 9074 9075 // Success! Record the copy. 9076 Statements.push_back(Copy.takeAs<Expr>()); 9077 } 9078 9079 // Assign non-static members. 9080 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9081 FieldEnd = ClassDecl->field_end(); 9082 Field != FieldEnd; ++Field) { 9083 if (Field->isUnnamedBitfield()) 9084 continue; 9085 9086 if (Field->isInvalidDecl()) { 9087 Invalid = true; 9088 continue; 9089 } 9090 9091 // Check for members of reference type; we can't copy those. 9092 if (Field->getType()->isReferenceType()) { 9093 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9094 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9095 Diag(Field->getLocation(), diag::note_declared_at); 9096 Diag(CurrentLocation, diag::note_member_synthesized_at) 9097 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9098 Invalid = true; 9099 continue; 9100 } 9101 9102 // Check for members of const-qualified, non-class type. 9103 QualType BaseType = Context.getBaseElementType(Field->getType()); 9104 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9105 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9106 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9107 Diag(Field->getLocation(), diag::note_declared_at); 9108 Diag(CurrentLocation, diag::note_member_synthesized_at) 9109 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9110 Invalid = true; 9111 continue; 9112 } 9113 9114 // Suppress assigning zero-width bitfields. 9115 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9116 continue; 9117 9118 QualType FieldType = Field->getType().getNonReferenceType(); 9119 if (FieldType->isIncompleteArrayType()) { 9120 assert(ClassDecl->hasFlexibleArrayMember() && 9121 "Incomplete array type is not valid"); 9122 continue; 9123 } 9124 9125 // Build references to the field in the object we're copying from and to. 9126 CXXScopeSpec SS; // Intentionally empty 9127 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9128 LookupMemberName); 9129 MemberLookup.addDecl(*Field); 9130 MemberLookup.resolveKind(); 9131 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9132 Loc, /*IsArrow=*/false, 9133 SS, SourceLocation(), 0, 9134 MemberLookup, 0); 9135 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9136 Loc, /*IsArrow=*/true, 9137 SS, SourceLocation(), 0, 9138 MemberLookup, 0); 9139 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9140 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9141 9142 // Build the copy of this field. 9143 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9144 To.get(), From.get(), 9145 /*CopyingBaseSubobject=*/false, 9146 /*Copying=*/true); 9147 if (Copy.isInvalid()) { 9148 Diag(CurrentLocation, diag::note_member_synthesized_at) 9149 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9150 CopyAssignOperator->setInvalidDecl(); 9151 return; 9152 } 9153 9154 // Success! Record the copy. 9155 Statements.push_back(Copy.takeAs<Stmt>()); 9156 } 9157 9158 if (!Invalid) { 9159 // Add a "return *this;" 9160 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9161 9162 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9163 if (Return.isInvalid()) 9164 Invalid = true; 9165 else { 9166 Statements.push_back(Return.takeAs<Stmt>()); 9167 9168 if (Trap.hasErrorOccurred()) { 9169 Diag(CurrentLocation, diag::note_member_synthesized_at) 9170 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9171 Invalid = true; 9172 } 9173 } 9174 } 9175 9176 if (Invalid) { 9177 CopyAssignOperator->setInvalidDecl(); 9178 return; 9179 } 9180 9181 StmtResult Body; 9182 { 9183 CompoundScopeRAII CompoundScope(*this); 9184 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9185 /*isStmtExpr=*/false); 9186 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9187 } 9188 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9189 9190 if (ASTMutationListener *L = getASTMutationListener()) { 9191 L->CompletedImplicitDefinition(CopyAssignOperator); 9192 } 9193} 9194 9195Sema::ImplicitExceptionSpecification 9196Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9197 CXXRecordDecl *ClassDecl = MD->getParent(); 9198 9199 ImplicitExceptionSpecification ExceptSpec(*this); 9200 if (ClassDecl->isInvalidDecl()) 9201 return ExceptSpec; 9202 9203 // C++0x [except.spec]p14: 9204 // An implicitly declared special member function (Clause 12) shall have an 9205 // exception-specification. [...] 9206 9207 // It is unspecified whether or not an implicit move assignment operator 9208 // attempts to deduplicate calls to assignment operators of virtual bases are 9209 // made. As such, this exception specification is effectively unspecified. 9210 // Based on a similar decision made for constness in C++0x, we're erring on 9211 // the side of assuming such calls to be made regardless of whether they 9212 // actually happen. 9213 // Note that a move constructor is not implicitly declared when there are 9214 // virtual bases, but it can still be user-declared and explicitly defaulted. 9215 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9216 BaseEnd = ClassDecl->bases_end(); 9217 Base != BaseEnd; ++Base) { 9218 if (Base->isVirtual()) 9219 continue; 9220 9221 CXXRecordDecl *BaseClassDecl 9222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9223 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9224 0, false, 0)) 9225 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9226 } 9227 9228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9229 BaseEnd = ClassDecl->vbases_end(); 9230 Base != BaseEnd; ++Base) { 9231 CXXRecordDecl *BaseClassDecl 9232 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9233 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9234 0, false, 0)) 9235 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9236 } 9237 9238 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9239 FieldEnd = ClassDecl->field_end(); 9240 Field != FieldEnd; 9241 ++Field) { 9242 QualType FieldType = Context.getBaseElementType(Field->getType()); 9243 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9244 if (CXXMethodDecl *MoveAssign = 9245 LookupMovingAssignment(FieldClassDecl, 9246 FieldType.getCVRQualifiers(), 9247 false, 0)) 9248 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9249 } 9250 } 9251 9252 return ExceptSpec; 9253} 9254 9255/// Determine whether the class type has any direct or indirect virtual base 9256/// classes which have a non-trivial move assignment operator. 9257static bool 9258hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9259 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9260 BaseEnd = ClassDecl->vbases_end(); 9261 Base != BaseEnd; ++Base) { 9262 CXXRecordDecl *BaseClass = 9263 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9264 9265 // Try to declare the move assignment. If it would be deleted, then the 9266 // class does not have a non-trivial move assignment. 9267 if (BaseClass->needsImplicitMoveAssignment()) 9268 S.DeclareImplicitMoveAssignment(BaseClass); 9269 9270 if (BaseClass->hasNonTrivialMoveAssignment()) 9271 return true; 9272 } 9273 9274 return false; 9275} 9276 9277/// Determine whether the given type either has a move constructor or is 9278/// trivially copyable. 9279static bool 9280hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9281 Type = S.Context.getBaseElementType(Type); 9282 9283 // FIXME: Technically, non-trivially-copyable non-class types, such as 9284 // reference types, are supposed to return false here, but that appears 9285 // to be a standard defect. 9286 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9287 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9288 return true; 9289 9290 if (Type.isTriviallyCopyableType(S.Context)) 9291 return true; 9292 9293 if (IsConstructor) { 9294 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9295 // give the right answer. 9296 if (ClassDecl->needsImplicitMoveConstructor()) 9297 S.DeclareImplicitMoveConstructor(ClassDecl); 9298 return ClassDecl->hasMoveConstructor(); 9299 } 9300 9301 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9302 // give the right answer. 9303 if (ClassDecl->needsImplicitMoveAssignment()) 9304 S.DeclareImplicitMoveAssignment(ClassDecl); 9305 return ClassDecl->hasMoveAssignment(); 9306} 9307 9308/// Determine whether all non-static data members and direct or virtual bases 9309/// of class \p ClassDecl have either a move operation, or are trivially 9310/// copyable. 9311static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9312 bool IsConstructor) { 9313 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9314 BaseEnd = ClassDecl->bases_end(); 9315 Base != BaseEnd; ++Base) { 9316 if (Base->isVirtual()) 9317 continue; 9318 9319 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9320 return false; 9321 } 9322 9323 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9324 BaseEnd = ClassDecl->vbases_end(); 9325 Base != BaseEnd; ++Base) { 9326 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9327 return false; 9328 } 9329 9330 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9331 FieldEnd = ClassDecl->field_end(); 9332 Field != FieldEnd; ++Field) { 9333 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9334 return false; 9335 } 9336 9337 return true; 9338} 9339 9340CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9341 // C++11 [class.copy]p20: 9342 // If the definition of a class X does not explicitly declare a move 9343 // assignment operator, one will be implicitly declared as defaulted 9344 // if and only if: 9345 // 9346 // - [first 4 bullets] 9347 assert(ClassDecl->needsImplicitMoveAssignment()); 9348 9349 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9350 if (DSM.isAlreadyBeingDeclared()) 9351 return 0; 9352 9353 // [Checked after we build the declaration] 9354 // - the move assignment operator would not be implicitly defined as 9355 // deleted, 9356 9357 // [DR1402]: 9358 // - X has no direct or indirect virtual base class with a non-trivial 9359 // move assignment operator, and 9360 // - each of X's non-static data members and direct or virtual base classes 9361 // has a type that either has a move assignment operator or is trivially 9362 // copyable. 9363 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9364 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9365 ClassDecl->setFailedImplicitMoveAssignment(); 9366 return 0; 9367 } 9368 9369 // Note: The following rules are largely analoguous to the move 9370 // constructor rules. 9371 9372 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9373 QualType RetType = Context.getLValueReferenceType(ArgType); 9374 ArgType = Context.getRValueReferenceType(ArgType); 9375 9376 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9377 CXXMoveAssignment, 9378 false); 9379 9380 // An implicitly-declared move assignment operator is an inline public 9381 // member of its class. 9382 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9383 SourceLocation ClassLoc = ClassDecl->getLocation(); 9384 DeclarationNameInfo NameInfo(Name, ClassLoc); 9385 CXXMethodDecl *MoveAssignment = 9386 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9387 /*TInfo=*/0, /*StorageClass=*/SC_None, 9388 /*isInline=*/true, Constexpr, SourceLocation()); 9389 MoveAssignment->setAccess(AS_public); 9390 MoveAssignment->setDefaulted(); 9391 MoveAssignment->setImplicit(); 9392 9393 // Build an exception specification pointing back at this member. 9394 FunctionProtoType::ExtProtoInfo EPI; 9395 EPI.ExceptionSpecType = EST_Unevaluated; 9396 EPI.ExceptionSpecDecl = MoveAssignment; 9397 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9398 9399 // Add the parameter to the operator. 9400 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9401 ClassLoc, ClassLoc, /*Id=*/0, 9402 ArgType, /*TInfo=*/0, 9403 SC_None, 0); 9404 MoveAssignment->setParams(FromParam); 9405 9406 AddOverriddenMethods(ClassDecl, MoveAssignment); 9407 9408 MoveAssignment->setTrivial( 9409 ClassDecl->needsOverloadResolutionForMoveAssignment() 9410 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9411 : ClassDecl->hasTrivialMoveAssignment()); 9412 9413 // C++0x [class.copy]p9: 9414 // If the definition of a class X does not explicitly declare a move 9415 // assignment operator, one will be implicitly declared as defaulted if and 9416 // only if: 9417 // [...] 9418 // - the move assignment operator would not be implicitly defined as 9419 // deleted. 9420 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9421 // Cache this result so that we don't try to generate this over and over 9422 // on every lookup, leaking memory and wasting time. 9423 ClassDecl->setFailedImplicitMoveAssignment(); 9424 return 0; 9425 } 9426 9427 // Note that we have added this copy-assignment operator. 9428 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9429 9430 if (Scope *S = getScopeForContext(ClassDecl)) 9431 PushOnScopeChains(MoveAssignment, S, false); 9432 ClassDecl->addDecl(MoveAssignment); 9433 9434 return MoveAssignment; 9435} 9436 9437void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9438 CXXMethodDecl *MoveAssignOperator) { 9439 assert((MoveAssignOperator->isDefaulted() && 9440 MoveAssignOperator->isOverloadedOperator() && 9441 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9442 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9443 !MoveAssignOperator->isDeleted()) && 9444 "DefineImplicitMoveAssignment called for wrong function"); 9445 9446 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9447 9448 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9449 MoveAssignOperator->setInvalidDecl(); 9450 return; 9451 } 9452 9453 MoveAssignOperator->setUsed(); 9454 9455 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9456 DiagnosticErrorTrap Trap(Diags); 9457 9458 // C++0x [class.copy]p28: 9459 // The implicitly-defined or move assignment operator for a non-union class 9460 // X performs memberwise move assignment of its subobjects. The direct base 9461 // classes of X are assigned first, in the order of their declaration in the 9462 // base-specifier-list, and then the immediate non-static data members of X 9463 // are assigned, in the order in which they were declared in the class 9464 // definition. 9465 9466 // The statements that form the synthesized function body. 9467 SmallVector<Stmt*, 8> Statements; 9468 9469 // The parameter for the "other" object, which we are move from. 9470 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9471 QualType OtherRefType = Other->getType()-> 9472 getAs<RValueReferenceType>()->getPointeeType(); 9473 assert(!OtherRefType.getQualifiers() && 9474 "Bad argument type of defaulted move assignment"); 9475 9476 // Our location for everything implicitly-generated. 9477 SourceLocation Loc = MoveAssignOperator->getLocation(); 9478 9479 // Construct a reference to the "other" object. We'll be using this 9480 // throughout the generated ASTs. 9481 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9482 assert(OtherRef && "Reference to parameter cannot fail!"); 9483 // Cast to rvalue. 9484 OtherRef = CastForMoving(*this, OtherRef); 9485 9486 // Construct the "this" pointer. We'll be using this throughout the generated 9487 // ASTs. 9488 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9489 assert(This && "Reference to this cannot fail!"); 9490 9491 // Assign base classes. 9492 bool Invalid = false; 9493 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9494 E = ClassDecl->bases_end(); Base != E; ++Base) { 9495 // Form the assignment: 9496 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9497 QualType BaseType = Base->getType().getUnqualifiedType(); 9498 if (!BaseType->isRecordType()) { 9499 Invalid = true; 9500 continue; 9501 } 9502 9503 CXXCastPath BasePath; 9504 BasePath.push_back(Base); 9505 9506 // Construct the "from" expression, which is an implicit cast to the 9507 // appropriately-qualified base type. 9508 Expr *From = OtherRef; 9509 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9510 VK_XValue, &BasePath).take(); 9511 9512 // Dereference "this". 9513 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9514 9515 // Implicitly cast "this" to the appropriately-qualified base type. 9516 To = ImpCastExprToType(To.take(), 9517 Context.getCVRQualifiedType(BaseType, 9518 MoveAssignOperator->getTypeQualifiers()), 9519 CK_UncheckedDerivedToBase, 9520 VK_LValue, &BasePath); 9521 9522 // Build the move. 9523 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9524 To.get(), From, 9525 /*CopyingBaseSubobject=*/true, 9526 /*Copying=*/false); 9527 if (Move.isInvalid()) { 9528 Diag(CurrentLocation, diag::note_member_synthesized_at) 9529 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9530 MoveAssignOperator->setInvalidDecl(); 9531 return; 9532 } 9533 9534 // Success! Record the move. 9535 Statements.push_back(Move.takeAs<Expr>()); 9536 } 9537 9538 // Assign non-static members. 9539 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9540 FieldEnd = ClassDecl->field_end(); 9541 Field != FieldEnd; ++Field) { 9542 if (Field->isUnnamedBitfield()) 9543 continue; 9544 9545 if (Field->isInvalidDecl()) { 9546 Invalid = true; 9547 continue; 9548 } 9549 9550 // Check for members of reference type; we can't move those. 9551 if (Field->getType()->isReferenceType()) { 9552 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9553 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9554 Diag(Field->getLocation(), diag::note_declared_at); 9555 Diag(CurrentLocation, diag::note_member_synthesized_at) 9556 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9557 Invalid = true; 9558 continue; 9559 } 9560 9561 // Check for members of const-qualified, non-class type. 9562 QualType BaseType = Context.getBaseElementType(Field->getType()); 9563 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9564 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9565 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9566 Diag(Field->getLocation(), diag::note_declared_at); 9567 Diag(CurrentLocation, diag::note_member_synthesized_at) 9568 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9569 Invalid = true; 9570 continue; 9571 } 9572 9573 // Suppress assigning zero-width bitfields. 9574 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9575 continue; 9576 9577 QualType FieldType = Field->getType().getNonReferenceType(); 9578 if (FieldType->isIncompleteArrayType()) { 9579 assert(ClassDecl->hasFlexibleArrayMember() && 9580 "Incomplete array type is not valid"); 9581 continue; 9582 } 9583 9584 // Build references to the field in the object we're copying from and to. 9585 CXXScopeSpec SS; // Intentionally empty 9586 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9587 LookupMemberName); 9588 MemberLookup.addDecl(*Field); 9589 MemberLookup.resolveKind(); 9590 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9591 Loc, /*IsArrow=*/false, 9592 SS, SourceLocation(), 0, 9593 MemberLookup, 0); 9594 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9595 Loc, /*IsArrow=*/true, 9596 SS, SourceLocation(), 0, 9597 MemberLookup, 0); 9598 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9599 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9600 9601 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9602 "Member reference with rvalue base must be rvalue except for reference " 9603 "members, which aren't allowed for move assignment."); 9604 9605 // Build the move of this field. 9606 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9607 To.get(), From.get(), 9608 /*CopyingBaseSubobject=*/false, 9609 /*Copying=*/false); 9610 if (Move.isInvalid()) { 9611 Diag(CurrentLocation, diag::note_member_synthesized_at) 9612 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9613 MoveAssignOperator->setInvalidDecl(); 9614 return; 9615 } 9616 9617 // Success! Record the copy. 9618 Statements.push_back(Move.takeAs<Stmt>()); 9619 } 9620 9621 if (!Invalid) { 9622 // Add a "return *this;" 9623 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9624 9625 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9626 if (Return.isInvalid()) 9627 Invalid = true; 9628 else { 9629 Statements.push_back(Return.takeAs<Stmt>()); 9630 9631 if (Trap.hasErrorOccurred()) { 9632 Diag(CurrentLocation, diag::note_member_synthesized_at) 9633 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9634 Invalid = true; 9635 } 9636 } 9637 } 9638 9639 if (Invalid) { 9640 MoveAssignOperator->setInvalidDecl(); 9641 return; 9642 } 9643 9644 StmtResult Body; 9645 { 9646 CompoundScopeRAII CompoundScope(*this); 9647 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9648 /*isStmtExpr=*/false); 9649 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9650 } 9651 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9652 9653 if (ASTMutationListener *L = getASTMutationListener()) { 9654 L->CompletedImplicitDefinition(MoveAssignOperator); 9655 } 9656} 9657 9658Sema::ImplicitExceptionSpecification 9659Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9660 CXXRecordDecl *ClassDecl = MD->getParent(); 9661 9662 ImplicitExceptionSpecification ExceptSpec(*this); 9663 if (ClassDecl->isInvalidDecl()) 9664 return ExceptSpec; 9665 9666 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9667 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9668 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9669 9670 // C++ [except.spec]p14: 9671 // An implicitly declared special member function (Clause 12) shall have an 9672 // exception-specification. [...] 9673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9674 BaseEnd = ClassDecl->bases_end(); 9675 Base != BaseEnd; 9676 ++Base) { 9677 // Virtual bases are handled below. 9678 if (Base->isVirtual()) 9679 continue; 9680 9681 CXXRecordDecl *BaseClassDecl 9682 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9683 if (CXXConstructorDecl *CopyConstructor = 9684 LookupCopyingConstructor(BaseClassDecl, Quals)) 9685 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9686 } 9687 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9688 BaseEnd = ClassDecl->vbases_end(); 9689 Base != BaseEnd; 9690 ++Base) { 9691 CXXRecordDecl *BaseClassDecl 9692 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9693 if (CXXConstructorDecl *CopyConstructor = 9694 LookupCopyingConstructor(BaseClassDecl, Quals)) 9695 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9696 } 9697 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9698 FieldEnd = ClassDecl->field_end(); 9699 Field != FieldEnd; 9700 ++Field) { 9701 QualType FieldType = Context.getBaseElementType(Field->getType()); 9702 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9703 if (CXXConstructorDecl *CopyConstructor = 9704 LookupCopyingConstructor(FieldClassDecl, 9705 Quals | FieldType.getCVRQualifiers())) 9706 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9707 } 9708 } 9709 9710 return ExceptSpec; 9711} 9712 9713CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9714 CXXRecordDecl *ClassDecl) { 9715 // C++ [class.copy]p4: 9716 // If the class definition does not explicitly declare a copy 9717 // constructor, one is declared implicitly. 9718 assert(ClassDecl->needsImplicitCopyConstructor()); 9719 9720 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9721 if (DSM.isAlreadyBeingDeclared()) 9722 return 0; 9723 9724 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9725 QualType ArgType = ClassType; 9726 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9727 if (Const) 9728 ArgType = ArgType.withConst(); 9729 ArgType = Context.getLValueReferenceType(ArgType); 9730 9731 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9732 CXXCopyConstructor, 9733 Const); 9734 9735 DeclarationName Name 9736 = Context.DeclarationNames.getCXXConstructorName( 9737 Context.getCanonicalType(ClassType)); 9738 SourceLocation ClassLoc = ClassDecl->getLocation(); 9739 DeclarationNameInfo NameInfo(Name, ClassLoc); 9740 9741 // An implicitly-declared copy constructor is an inline public 9742 // member of its class. 9743 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9744 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9745 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9746 Constexpr); 9747 CopyConstructor->setAccess(AS_public); 9748 CopyConstructor->setDefaulted(); 9749 9750 // Build an exception specification pointing back at this member. 9751 FunctionProtoType::ExtProtoInfo EPI; 9752 EPI.ExceptionSpecType = EST_Unevaluated; 9753 EPI.ExceptionSpecDecl = CopyConstructor; 9754 CopyConstructor->setType( 9755 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9756 9757 // Add the parameter to the constructor. 9758 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9759 ClassLoc, ClassLoc, 9760 /*IdentifierInfo=*/0, 9761 ArgType, /*TInfo=*/0, 9762 SC_None, 0); 9763 CopyConstructor->setParams(FromParam); 9764 9765 CopyConstructor->setTrivial( 9766 ClassDecl->needsOverloadResolutionForCopyConstructor() 9767 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9768 : ClassDecl->hasTrivialCopyConstructor()); 9769 9770 // C++11 [class.copy]p8: 9771 // ... If the class definition does not explicitly declare a copy 9772 // constructor, there is no user-declared move constructor, and there is no 9773 // user-declared move assignment operator, a copy constructor is implicitly 9774 // declared as defaulted. 9775 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9776 SetDeclDeleted(CopyConstructor, ClassLoc); 9777 9778 // Note that we have declared this constructor. 9779 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9780 9781 if (Scope *S = getScopeForContext(ClassDecl)) 9782 PushOnScopeChains(CopyConstructor, S, false); 9783 ClassDecl->addDecl(CopyConstructor); 9784 9785 return CopyConstructor; 9786} 9787 9788void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9789 CXXConstructorDecl *CopyConstructor) { 9790 assert((CopyConstructor->isDefaulted() && 9791 CopyConstructor->isCopyConstructor() && 9792 !CopyConstructor->doesThisDeclarationHaveABody() && 9793 !CopyConstructor->isDeleted()) && 9794 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9795 9796 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9797 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9798 9799 // C++11 [class.copy]p7: 9800 // The [definition of an implicitly declared copy constructro] is 9801 // deprecated if the class has a user-declared copy assignment operator 9802 // or a user-declared destructor. 9803 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 9804 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 9805 9806 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9807 DiagnosticErrorTrap Trap(Diags); 9808 9809 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9810 Trap.hasErrorOccurred()) { 9811 Diag(CurrentLocation, diag::note_member_synthesized_at) 9812 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9813 CopyConstructor->setInvalidDecl(); 9814 } else { 9815 Sema::CompoundScopeRAII CompoundScope(*this); 9816 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9817 CopyConstructor->getLocation(), 9818 MultiStmtArg(), 9819 /*isStmtExpr=*/false) 9820 .takeAs<Stmt>()); 9821 CopyConstructor->setImplicitlyDefined(true); 9822 } 9823 9824 CopyConstructor->setUsed(); 9825 if (ASTMutationListener *L = getASTMutationListener()) { 9826 L->CompletedImplicitDefinition(CopyConstructor); 9827 } 9828} 9829 9830Sema::ImplicitExceptionSpecification 9831Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9832 CXXRecordDecl *ClassDecl = MD->getParent(); 9833 9834 // C++ [except.spec]p14: 9835 // An implicitly declared special member function (Clause 12) shall have an 9836 // exception-specification. [...] 9837 ImplicitExceptionSpecification ExceptSpec(*this); 9838 if (ClassDecl->isInvalidDecl()) 9839 return ExceptSpec; 9840 9841 // Direct base-class constructors. 9842 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9843 BEnd = ClassDecl->bases_end(); 9844 B != BEnd; ++B) { 9845 if (B->isVirtual()) // Handled below. 9846 continue; 9847 9848 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9849 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9850 CXXConstructorDecl *Constructor = 9851 LookupMovingConstructor(BaseClassDecl, 0); 9852 // If this is a deleted function, add it anyway. This might be conformant 9853 // with the standard. This might not. I'm not sure. It might not matter. 9854 if (Constructor) 9855 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9856 } 9857 } 9858 9859 // Virtual base-class constructors. 9860 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9861 BEnd = ClassDecl->vbases_end(); 9862 B != BEnd; ++B) { 9863 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9864 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9865 CXXConstructorDecl *Constructor = 9866 LookupMovingConstructor(BaseClassDecl, 0); 9867 // If this is a deleted function, add it anyway. This might be conformant 9868 // with the standard. This might not. I'm not sure. It might not matter. 9869 if (Constructor) 9870 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9871 } 9872 } 9873 9874 // Field constructors. 9875 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9876 FEnd = ClassDecl->field_end(); 9877 F != FEnd; ++F) { 9878 QualType FieldType = Context.getBaseElementType(F->getType()); 9879 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9880 CXXConstructorDecl *Constructor = 9881 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9882 // If this is a deleted function, add it anyway. This might be conformant 9883 // with the standard. This might not. I'm not sure. It might not matter. 9884 // In particular, the problem is that this function never gets called. It 9885 // might just be ill-formed because this function attempts to refer to 9886 // a deleted function here. 9887 if (Constructor) 9888 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9889 } 9890 } 9891 9892 return ExceptSpec; 9893} 9894 9895CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9896 CXXRecordDecl *ClassDecl) { 9897 // C++11 [class.copy]p9: 9898 // If the definition of a class X does not explicitly declare a move 9899 // constructor, one will be implicitly declared as defaulted if and only if: 9900 // 9901 // - [first 4 bullets] 9902 assert(ClassDecl->needsImplicitMoveConstructor()); 9903 9904 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9905 if (DSM.isAlreadyBeingDeclared()) 9906 return 0; 9907 9908 // [Checked after we build the declaration] 9909 // - the move assignment operator would not be implicitly defined as 9910 // deleted, 9911 9912 // [DR1402]: 9913 // - each of X's non-static data members and direct or virtual base classes 9914 // has a type that either has a move constructor or is trivially copyable. 9915 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9916 ClassDecl->setFailedImplicitMoveConstructor(); 9917 return 0; 9918 } 9919 9920 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9921 QualType ArgType = Context.getRValueReferenceType(ClassType); 9922 9923 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9924 CXXMoveConstructor, 9925 false); 9926 9927 DeclarationName Name 9928 = Context.DeclarationNames.getCXXConstructorName( 9929 Context.getCanonicalType(ClassType)); 9930 SourceLocation ClassLoc = ClassDecl->getLocation(); 9931 DeclarationNameInfo NameInfo(Name, ClassLoc); 9932 9933 // C++11 [class.copy]p11: 9934 // An implicitly-declared copy/move constructor is an inline public 9935 // member of its class. 9936 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9937 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9938 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9939 Constexpr); 9940 MoveConstructor->setAccess(AS_public); 9941 MoveConstructor->setDefaulted(); 9942 9943 // Build an exception specification pointing back at this member. 9944 FunctionProtoType::ExtProtoInfo EPI; 9945 EPI.ExceptionSpecType = EST_Unevaluated; 9946 EPI.ExceptionSpecDecl = MoveConstructor; 9947 MoveConstructor->setType( 9948 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9949 9950 // Add the parameter to the constructor. 9951 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9952 ClassLoc, ClassLoc, 9953 /*IdentifierInfo=*/0, 9954 ArgType, /*TInfo=*/0, 9955 SC_None, 0); 9956 MoveConstructor->setParams(FromParam); 9957 9958 MoveConstructor->setTrivial( 9959 ClassDecl->needsOverloadResolutionForMoveConstructor() 9960 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9961 : ClassDecl->hasTrivialMoveConstructor()); 9962 9963 // C++0x [class.copy]p9: 9964 // If the definition of a class X does not explicitly declare a move 9965 // constructor, one will be implicitly declared as defaulted if and only if: 9966 // [...] 9967 // - the move constructor would not be implicitly defined as deleted. 9968 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9969 // Cache this result so that we don't try to generate this over and over 9970 // on every lookup, leaking memory and wasting time. 9971 ClassDecl->setFailedImplicitMoveConstructor(); 9972 return 0; 9973 } 9974 9975 // Note that we have declared this constructor. 9976 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9977 9978 if (Scope *S = getScopeForContext(ClassDecl)) 9979 PushOnScopeChains(MoveConstructor, S, false); 9980 ClassDecl->addDecl(MoveConstructor); 9981 9982 return MoveConstructor; 9983} 9984 9985void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9986 CXXConstructorDecl *MoveConstructor) { 9987 assert((MoveConstructor->isDefaulted() && 9988 MoveConstructor->isMoveConstructor() && 9989 !MoveConstructor->doesThisDeclarationHaveABody() && 9990 !MoveConstructor->isDeleted()) && 9991 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9992 9993 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9994 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9995 9996 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9997 DiagnosticErrorTrap Trap(Diags); 9998 9999 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10000 Trap.hasErrorOccurred()) { 10001 Diag(CurrentLocation, diag::note_member_synthesized_at) 10002 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10003 MoveConstructor->setInvalidDecl(); 10004 } else { 10005 Sema::CompoundScopeRAII CompoundScope(*this); 10006 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 10007 MoveConstructor->getLocation(), 10008 MultiStmtArg(), 10009 /*isStmtExpr=*/false) 10010 .takeAs<Stmt>()); 10011 MoveConstructor->setImplicitlyDefined(true); 10012 } 10013 10014 MoveConstructor->setUsed(); 10015 10016 if (ASTMutationListener *L = getASTMutationListener()) { 10017 L->CompletedImplicitDefinition(MoveConstructor); 10018 } 10019} 10020 10021bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10022 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10023} 10024 10025/// \brief Mark the call operator of the given lambda closure type as "used". 10026static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 10027 CXXMethodDecl *CallOperator 10028 = cast<CXXMethodDecl>( 10029 Lambda->lookup( 10030 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 10031 CallOperator->setReferenced(); 10032 CallOperator->setUsed(); 10033} 10034 10035void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10036 SourceLocation CurrentLocation, 10037 CXXConversionDecl *Conv) 10038{ 10039 CXXRecordDecl *Lambda = Conv->getParent(); 10040 10041 // Make sure that the lambda call operator is marked used. 10042 markLambdaCallOperatorUsed(*this, Lambda); 10043 10044 Conv->setUsed(); 10045 10046 SynthesizedFunctionScope Scope(*this, Conv); 10047 DiagnosticErrorTrap Trap(Diags); 10048 10049 // Return the address of the __invoke function. 10050 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 10051 CXXMethodDecl *Invoke 10052 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 10053 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 10054 VK_LValue, Conv->getLocation()).take(); 10055 assert(FunctionRef && "Can't refer to __invoke function?"); 10056 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10057 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10058 Conv->getLocation(), 10059 Conv->getLocation())); 10060 10061 // Fill in the __invoke function with a dummy implementation. IR generation 10062 // will fill in the actual details. 10063 Invoke->setUsed(); 10064 Invoke->setReferenced(); 10065 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10066 10067 if (ASTMutationListener *L = getASTMutationListener()) { 10068 L->CompletedImplicitDefinition(Conv); 10069 L->CompletedImplicitDefinition(Invoke); 10070 } 10071} 10072 10073void Sema::DefineImplicitLambdaToBlockPointerConversion( 10074 SourceLocation CurrentLocation, 10075 CXXConversionDecl *Conv) 10076{ 10077 Conv->setUsed(); 10078 10079 SynthesizedFunctionScope Scope(*this, Conv); 10080 DiagnosticErrorTrap Trap(Diags); 10081 10082 // Copy-initialize the lambda object as needed to capture it. 10083 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10084 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10085 10086 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10087 Conv->getLocation(), 10088 Conv, DerefThis); 10089 10090 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10091 // behavior. Note that only the general conversion function does this 10092 // (since it's unusable otherwise); in the case where we inline the 10093 // block literal, it has block literal lifetime semantics. 10094 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10095 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10096 CK_CopyAndAutoreleaseBlockObject, 10097 BuildBlock.get(), 0, VK_RValue); 10098 10099 if (BuildBlock.isInvalid()) { 10100 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10101 Conv->setInvalidDecl(); 10102 return; 10103 } 10104 10105 // Create the return statement that returns the block from the conversion 10106 // function. 10107 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10108 if (Return.isInvalid()) { 10109 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10110 Conv->setInvalidDecl(); 10111 return; 10112 } 10113 10114 // Set the body of the conversion function. 10115 Stmt *ReturnS = Return.take(); 10116 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10117 Conv->getLocation(), 10118 Conv->getLocation())); 10119 10120 // We're done; notify the mutation listener, if any. 10121 if (ASTMutationListener *L = getASTMutationListener()) { 10122 L->CompletedImplicitDefinition(Conv); 10123 } 10124} 10125 10126/// \brief Determine whether the given list arguments contains exactly one 10127/// "real" (non-default) argument. 10128static bool hasOneRealArgument(MultiExprArg Args) { 10129 switch (Args.size()) { 10130 case 0: 10131 return false; 10132 10133 default: 10134 if (!Args[1]->isDefaultArgument()) 10135 return false; 10136 10137 // fall through 10138 case 1: 10139 return !Args[0]->isDefaultArgument(); 10140 } 10141 10142 return false; 10143} 10144 10145ExprResult 10146Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10147 CXXConstructorDecl *Constructor, 10148 MultiExprArg ExprArgs, 10149 bool HadMultipleCandidates, 10150 bool IsListInitialization, 10151 bool RequiresZeroInit, 10152 unsigned ConstructKind, 10153 SourceRange ParenRange) { 10154 bool Elidable = false; 10155 10156 // C++0x [class.copy]p34: 10157 // When certain criteria are met, an implementation is allowed to 10158 // omit the copy/move construction of a class object, even if the 10159 // copy/move constructor and/or destructor for the object have 10160 // side effects. [...] 10161 // - when a temporary class object that has not been bound to a 10162 // reference (12.2) would be copied/moved to a class object 10163 // with the same cv-unqualified type, the copy/move operation 10164 // can be omitted by constructing the temporary object 10165 // directly into the target of the omitted copy/move 10166 if (ConstructKind == CXXConstructExpr::CK_Complete && 10167 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10168 Expr *SubExpr = ExprArgs[0]; 10169 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10170 } 10171 10172 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10173 Elidable, ExprArgs, HadMultipleCandidates, 10174 IsListInitialization, RequiresZeroInit, 10175 ConstructKind, ParenRange); 10176} 10177 10178/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10179/// including handling of its default argument expressions. 10180ExprResult 10181Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10182 CXXConstructorDecl *Constructor, bool Elidable, 10183 MultiExprArg ExprArgs, 10184 bool HadMultipleCandidates, 10185 bool IsListInitialization, 10186 bool RequiresZeroInit, 10187 unsigned ConstructKind, 10188 SourceRange ParenRange) { 10189 MarkFunctionReferenced(ConstructLoc, Constructor); 10190 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10191 Constructor, Elidable, ExprArgs, 10192 HadMultipleCandidates, 10193 IsListInitialization, RequiresZeroInit, 10194 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10195 ParenRange)); 10196} 10197 10198void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10199 if (VD->isInvalidDecl()) return; 10200 10201 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10202 if (ClassDecl->isInvalidDecl()) return; 10203 if (ClassDecl->hasIrrelevantDestructor()) return; 10204 if (ClassDecl->isDependentContext()) return; 10205 10206 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10207 MarkFunctionReferenced(VD->getLocation(), Destructor); 10208 CheckDestructorAccess(VD->getLocation(), Destructor, 10209 PDiag(diag::err_access_dtor_var) 10210 << VD->getDeclName() 10211 << VD->getType()); 10212 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10213 10214 if (!VD->hasGlobalStorage()) return; 10215 10216 // Emit warning for non-trivial dtor in global scope (a real global, 10217 // class-static, function-static). 10218 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10219 10220 // TODO: this should be re-enabled for static locals by !CXAAtExit 10221 if (!VD->isStaticLocal()) 10222 Diag(VD->getLocation(), diag::warn_global_destructor); 10223} 10224 10225/// \brief Given a constructor and the set of arguments provided for the 10226/// constructor, convert the arguments and add any required default arguments 10227/// to form a proper call to this constructor. 10228/// 10229/// \returns true if an error occurred, false otherwise. 10230bool 10231Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10232 MultiExprArg ArgsPtr, 10233 SourceLocation Loc, 10234 SmallVectorImpl<Expr*> &ConvertedArgs, 10235 bool AllowExplicit, 10236 bool IsListInitialization) { 10237 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10238 unsigned NumArgs = ArgsPtr.size(); 10239 Expr **Args = ArgsPtr.data(); 10240 10241 const FunctionProtoType *Proto 10242 = Constructor->getType()->getAs<FunctionProtoType>(); 10243 assert(Proto && "Constructor without a prototype?"); 10244 unsigned NumArgsInProto = Proto->getNumArgs(); 10245 10246 // If too few arguments are available, we'll fill in the rest with defaults. 10247 if (NumArgs < NumArgsInProto) 10248 ConvertedArgs.reserve(NumArgsInProto); 10249 else 10250 ConvertedArgs.reserve(NumArgs); 10251 10252 VariadicCallType CallType = 10253 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10254 SmallVector<Expr *, 8> AllArgs; 10255 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10256 Proto, 0, 10257 llvm::makeArrayRef(Args, NumArgs), 10258 AllArgs, 10259 CallType, AllowExplicit, 10260 IsListInitialization); 10261 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10262 10263 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10264 10265 CheckConstructorCall(Constructor, 10266 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10267 AllArgs.size()), 10268 Proto, Loc); 10269 10270 return Invalid; 10271} 10272 10273static inline bool 10274CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10275 const FunctionDecl *FnDecl) { 10276 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10277 if (isa<NamespaceDecl>(DC)) { 10278 return SemaRef.Diag(FnDecl->getLocation(), 10279 diag::err_operator_new_delete_declared_in_namespace) 10280 << FnDecl->getDeclName(); 10281 } 10282 10283 if (isa<TranslationUnitDecl>(DC) && 10284 FnDecl->getStorageClass() == SC_Static) { 10285 return SemaRef.Diag(FnDecl->getLocation(), 10286 diag::err_operator_new_delete_declared_static) 10287 << FnDecl->getDeclName(); 10288 } 10289 10290 return false; 10291} 10292 10293static inline bool 10294CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10295 CanQualType ExpectedResultType, 10296 CanQualType ExpectedFirstParamType, 10297 unsigned DependentParamTypeDiag, 10298 unsigned InvalidParamTypeDiag) { 10299 QualType ResultType = 10300 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10301 10302 // Check that the result type is not dependent. 10303 if (ResultType->isDependentType()) 10304 return SemaRef.Diag(FnDecl->getLocation(), 10305 diag::err_operator_new_delete_dependent_result_type) 10306 << FnDecl->getDeclName() << ExpectedResultType; 10307 10308 // Check that the result type is what we expect. 10309 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10310 return SemaRef.Diag(FnDecl->getLocation(), 10311 diag::err_operator_new_delete_invalid_result_type) 10312 << FnDecl->getDeclName() << ExpectedResultType; 10313 10314 // A function template must have at least 2 parameters. 10315 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10316 return SemaRef.Diag(FnDecl->getLocation(), 10317 diag::err_operator_new_delete_template_too_few_parameters) 10318 << FnDecl->getDeclName(); 10319 10320 // The function decl must have at least 1 parameter. 10321 if (FnDecl->getNumParams() == 0) 10322 return SemaRef.Diag(FnDecl->getLocation(), 10323 diag::err_operator_new_delete_too_few_parameters) 10324 << FnDecl->getDeclName(); 10325 10326 // Check the first parameter type is not dependent. 10327 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10328 if (FirstParamType->isDependentType()) 10329 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10330 << FnDecl->getDeclName() << ExpectedFirstParamType; 10331 10332 // Check that the first parameter type is what we expect. 10333 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10334 ExpectedFirstParamType) 10335 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10336 << FnDecl->getDeclName() << ExpectedFirstParamType; 10337 10338 return false; 10339} 10340 10341static bool 10342CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10343 // C++ [basic.stc.dynamic.allocation]p1: 10344 // A program is ill-formed if an allocation function is declared in a 10345 // namespace scope other than global scope or declared static in global 10346 // scope. 10347 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10348 return true; 10349 10350 CanQualType SizeTy = 10351 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10352 10353 // C++ [basic.stc.dynamic.allocation]p1: 10354 // The return type shall be void*. The first parameter shall have type 10355 // std::size_t. 10356 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10357 SizeTy, 10358 diag::err_operator_new_dependent_param_type, 10359 diag::err_operator_new_param_type)) 10360 return true; 10361 10362 // C++ [basic.stc.dynamic.allocation]p1: 10363 // The first parameter shall not have an associated default argument. 10364 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10365 return SemaRef.Diag(FnDecl->getLocation(), 10366 diag::err_operator_new_default_arg) 10367 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10368 10369 return false; 10370} 10371 10372static bool 10373CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10374 // C++ [basic.stc.dynamic.deallocation]p1: 10375 // A program is ill-formed if deallocation functions are declared in a 10376 // namespace scope other than global scope or declared static in global 10377 // scope. 10378 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10379 return true; 10380 10381 // C++ [basic.stc.dynamic.deallocation]p2: 10382 // Each deallocation function shall return void and its first parameter 10383 // shall be void*. 10384 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10385 SemaRef.Context.VoidPtrTy, 10386 diag::err_operator_delete_dependent_param_type, 10387 diag::err_operator_delete_param_type)) 10388 return true; 10389 10390 return false; 10391} 10392 10393/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10394/// of this overloaded operator is well-formed. If so, returns false; 10395/// otherwise, emits appropriate diagnostics and returns true. 10396bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10397 assert(FnDecl && FnDecl->isOverloadedOperator() && 10398 "Expected an overloaded operator declaration"); 10399 10400 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10401 10402 // C++ [over.oper]p5: 10403 // The allocation and deallocation functions, operator new, 10404 // operator new[], operator delete and operator delete[], are 10405 // described completely in 3.7.3. The attributes and restrictions 10406 // found in the rest of this subclause do not apply to them unless 10407 // explicitly stated in 3.7.3. 10408 if (Op == OO_Delete || Op == OO_Array_Delete) 10409 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10410 10411 if (Op == OO_New || Op == OO_Array_New) 10412 return CheckOperatorNewDeclaration(*this, FnDecl); 10413 10414 // C++ [over.oper]p6: 10415 // An operator function shall either be a non-static member 10416 // function or be a non-member function and have at least one 10417 // parameter whose type is a class, a reference to a class, an 10418 // enumeration, or a reference to an enumeration. 10419 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10420 if (MethodDecl->isStatic()) 10421 return Diag(FnDecl->getLocation(), 10422 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10423 } else { 10424 bool ClassOrEnumParam = false; 10425 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10426 ParamEnd = FnDecl->param_end(); 10427 Param != ParamEnd; ++Param) { 10428 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10429 if (ParamType->isDependentType() || ParamType->isRecordType() || 10430 ParamType->isEnumeralType()) { 10431 ClassOrEnumParam = true; 10432 break; 10433 } 10434 } 10435 10436 if (!ClassOrEnumParam) 10437 return Diag(FnDecl->getLocation(), 10438 diag::err_operator_overload_needs_class_or_enum) 10439 << FnDecl->getDeclName(); 10440 } 10441 10442 // C++ [over.oper]p8: 10443 // An operator function cannot have default arguments (8.3.6), 10444 // except where explicitly stated below. 10445 // 10446 // Only the function-call operator allows default arguments 10447 // (C++ [over.call]p1). 10448 if (Op != OO_Call) { 10449 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10450 Param != FnDecl->param_end(); ++Param) { 10451 if ((*Param)->hasDefaultArg()) 10452 return Diag((*Param)->getLocation(), 10453 diag::err_operator_overload_default_arg) 10454 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10455 } 10456 } 10457 10458 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10459 { false, false, false } 10460#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10461 , { Unary, Binary, MemberOnly } 10462#include "clang/Basic/OperatorKinds.def" 10463 }; 10464 10465 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10466 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10467 bool MustBeMemberOperator = OperatorUses[Op][2]; 10468 10469 // C++ [over.oper]p8: 10470 // [...] Operator functions cannot have more or fewer parameters 10471 // than the number required for the corresponding operator, as 10472 // described in the rest of this subclause. 10473 unsigned NumParams = FnDecl->getNumParams() 10474 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10475 if (Op != OO_Call && 10476 ((NumParams == 1 && !CanBeUnaryOperator) || 10477 (NumParams == 2 && !CanBeBinaryOperator) || 10478 (NumParams < 1) || (NumParams > 2))) { 10479 // We have the wrong number of parameters. 10480 unsigned ErrorKind; 10481 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10482 ErrorKind = 2; // 2 -> unary or binary. 10483 } else if (CanBeUnaryOperator) { 10484 ErrorKind = 0; // 0 -> unary 10485 } else { 10486 assert(CanBeBinaryOperator && 10487 "All non-call overloaded operators are unary or binary!"); 10488 ErrorKind = 1; // 1 -> binary 10489 } 10490 10491 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10492 << FnDecl->getDeclName() << NumParams << ErrorKind; 10493 } 10494 10495 // Overloaded operators other than operator() cannot be variadic. 10496 if (Op != OO_Call && 10497 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10498 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10499 << FnDecl->getDeclName(); 10500 } 10501 10502 // Some operators must be non-static member functions. 10503 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10504 return Diag(FnDecl->getLocation(), 10505 diag::err_operator_overload_must_be_member) 10506 << FnDecl->getDeclName(); 10507 } 10508 10509 // C++ [over.inc]p1: 10510 // The user-defined function called operator++ implements the 10511 // prefix and postfix ++ operator. If this function is a member 10512 // function with no parameters, or a non-member function with one 10513 // parameter of class or enumeration type, it defines the prefix 10514 // increment operator ++ for objects of that type. If the function 10515 // is a member function with one parameter (which shall be of type 10516 // int) or a non-member function with two parameters (the second 10517 // of which shall be of type int), it defines the postfix 10518 // increment operator ++ for objects of that type. 10519 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10520 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10521 bool ParamIsInt = false; 10522 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10523 ParamIsInt = BT->getKind() == BuiltinType::Int; 10524 10525 if (!ParamIsInt) 10526 return Diag(LastParam->getLocation(), 10527 diag::err_operator_overload_post_incdec_must_be_int) 10528 << LastParam->getType() << (Op == OO_MinusMinus); 10529 } 10530 10531 return false; 10532} 10533 10534/// CheckLiteralOperatorDeclaration - Check whether the declaration 10535/// of this literal operator function is well-formed. If so, returns 10536/// false; otherwise, emits appropriate diagnostics and returns true. 10537bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10538 if (isa<CXXMethodDecl>(FnDecl)) { 10539 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10540 << FnDecl->getDeclName(); 10541 return true; 10542 } 10543 10544 if (FnDecl->isExternC()) { 10545 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10546 return true; 10547 } 10548 10549 bool Valid = false; 10550 10551 // This might be the definition of a literal operator template. 10552 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10553 // This might be a specialization of a literal operator template. 10554 if (!TpDecl) 10555 TpDecl = FnDecl->getPrimaryTemplate(); 10556 10557 // template <char...> type operator "" name() is the only valid template 10558 // signature, and the only valid signature with no parameters. 10559 if (TpDecl) { 10560 if (FnDecl->param_size() == 0) { 10561 // Must have only one template parameter 10562 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10563 if (Params->size() == 1) { 10564 NonTypeTemplateParmDecl *PmDecl = 10565 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10566 10567 // The template parameter must be a char parameter pack. 10568 if (PmDecl && PmDecl->isTemplateParameterPack() && 10569 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10570 Valid = true; 10571 } 10572 } 10573 } else if (FnDecl->param_size()) { 10574 // Check the first parameter 10575 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10576 10577 QualType T = (*Param)->getType().getUnqualifiedType(); 10578 10579 // unsigned long long int, long double, and any character type are allowed 10580 // as the only parameters. 10581 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10582 Context.hasSameType(T, Context.LongDoubleTy) || 10583 Context.hasSameType(T, Context.CharTy) || 10584 Context.hasSameType(T, Context.WideCharTy) || 10585 Context.hasSameType(T, Context.Char16Ty) || 10586 Context.hasSameType(T, Context.Char32Ty)) { 10587 if (++Param == FnDecl->param_end()) 10588 Valid = true; 10589 goto FinishedParams; 10590 } 10591 10592 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10593 const PointerType *PT = T->getAs<PointerType>(); 10594 if (!PT) 10595 goto FinishedParams; 10596 T = PT->getPointeeType(); 10597 if (!T.isConstQualified() || T.isVolatileQualified()) 10598 goto FinishedParams; 10599 T = T.getUnqualifiedType(); 10600 10601 // Move on to the second parameter; 10602 ++Param; 10603 10604 // If there is no second parameter, the first must be a const char * 10605 if (Param == FnDecl->param_end()) { 10606 if (Context.hasSameType(T, Context.CharTy)) 10607 Valid = true; 10608 goto FinishedParams; 10609 } 10610 10611 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10612 // are allowed as the first parameter to a two-parameter function 10613 if (!(Context.hasSameType(T, Context.CharTy) || 10614 Context.hasSameType(T, Context.WideCharTy) || 10615 Context.hasSameType(T, Context.Char16Ty) || 10616 Context.hasSameType(T, Context.Char32Ty))) 10617 goto FinishedParams; 10618 10619 // The second and final parameter must be an std::size_t 10620 T = (*Param)->getType().getUnqualifiedType(); 10621 if (Context.hasSameType(T, Context.getSizeType()) && 10622 ++Param == FnDecl->param_end()) 10623 Valid = true; 10624 } 10625 10626 // FIXME: This diagnostic is absolutely terrible. 10627FinishedParams: 10628 if (!Valid) { 10629 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10630 << FnDecl->getDeclName(); 10631 return true; 10632 } 10633 10634 // A parameter-declaration-clause containing a default argument is not 10635 // equivalent to any of the permitted forms. 10636 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10637 ParamEnd = FnDecl->param_end(); 10638 Param != ParamEnd; ++Param) { 10639 if ((*Param)->hasDefaultArg()) { 10640 Diag((*Param)->getDefaultArgRange().getBegin(), 10641 diag::err_literal_operator_default_argument) 10642 << (*Param)->getDefaultArgRange(); 10643 break; 10644 } 10645 } 10646 10647 StringRef LiteralName 10648 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10649 if (LiteralName[0] != '_') { 10650 // C++11 [usrlit.suffix]p1: 10651 // Literal suffix identifiers that do not start with an underscore 10652 // are reserved for future standardization. 10653 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10654 } 10655 10656 return false; 10657} 10658 10659/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10660/// linkage specification, including the language and (if present) 10661/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10662/// the location of the language string literal, which is provided 10663/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10664/// the '{' brace. Otherwise, this linkage specification does not 10665/// have any braces. 10666Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10667 SourceLocation LangLoc, 10668 StringRef Lang, 10669 SourceLocation LBraceLoc) { 10670 LinkageSpecDecl::LanguageIDs Language; 10671 if (Lang == "\"C\"") 10672 Language = LinkageSpecDecl::lang_c; 10673 else if (Lang == "\"C++\"") 10674 Language = LinkageSpecDecl::lang_cxx; 10675 else { 10676 Diag(LangLoc, diag::err_bad_language); 10677 return 0; 10678 } 10679 10680 // FIXME: Add all the various semantics of linkage specifications 10681 10682 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10683 ExternLoc, LangLoc, Language, 10684 LBraceLoc.isValid()); 10685 CurContext->addDecl(D); 10686 PushDeclContext(S, D); 10687 return D; 10688} 10689 10690/// ActOnFinishLinkageSpecification - Complete the definition of 10691/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10692/// valid, it's the position of the closing '}' brace in a linkage 10693/// specification that uses braces. 10694Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10695 Decl *LinkageSpec, 10696 SourceLocation RBraceLoc) { 10697 if (LinkageSpec) { 10698 if (RBraceLoc.isValid()) { 10699 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10700 LSDecl->setRBraceLoc(RBraceLoc); 10701 } 10702 PopDeclContext(); 10703 } 10704 return LinkageSpec; 10705} 10706 10707Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10708 AttributeList *AttrList, 10709 SourceLocation SemiLoc) { 10710 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10711 // Attribute declarations appertain to empty declaration so we handle 10712 // them here. 10713 if (AttrList) 10714 ProcessDeclAttributeList(S, ED, AttrList); 10715 10716 CurContext->addDecl(ED); 10717 return ED; 10718} 10719 10720/// \brief Perform semantic analysis for the variable declaration that 10721/// occurs within a C++ catch clause, returning the newly-created 10722/// variable. 10723VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10724 TypeSourceInfo *TInfo, 10725 SourceLocation StartLoc, 10726 SourceLocation Loc, 10727 IdentifierInfo *Name) { 10728 bool Invalid = false; 10729 QualType ExDeclType = TInfo->getType(); 10730 10731 // Arrays and functions decay. 10732 if (ExDeclType->isArrayType()) 10733 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10734 else if (ExDeclType->isFunctionType()) 10735 ExDeclType = Context.getPointerType(ExDeclType); 10736 10737 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10738 // The exception-declaration shall not denote a pointer or reference to an 10739 // incomplete type, other than [cv] void*. 10740 // N2844 forbids rvalue references. 10741 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10742 Diag(Loc, diag::err_catch_rvalue_ref); 10743 Invalid = true; 10744 } 10745 10746 QualType BaseType = ExDeclType; 10747 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10748 unsigned DK = diag::err_catch_incomplete; 10749 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10750 BaseType = Ptr->getPointeeType(); 10751 Mode = 1; 10752 DK = diag::err_catch_incomplete_ptr; 10753 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10754 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10755 BaseType = Ref->getPointeeType(); 10756 Mode = 2; 10757 DK = diag::err_catch_incomplete_ref; 10758 } 10759 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10760 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10761 Invalid = true; 10762 10763 if (!Invalid && !ExDeclType->isDependentType() && 10764 RequireNonAbstractType(Loc, ExDeclType, 10765 diag::err_abstract_type_in_decl, 10766 AbstractVariableType)) 10767 Invalid = true; 10768 10769 // Only the non-fragile NeXT runtime currently supports C++ catches 10770 // of ObjC types, and no runtime supports catching ObjC types by value. 10771 if (!Invalid && getLangOpts().ObjC1) { 10772 QualType T = ExDeclType; 10773 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10774 T = RT->getPointeeType(); 10775 10776 if (T->isObjCObjectType()) { 10777 Diag(Loc, diag::err_objc_object_catch); 10778 Invalid = true; 10779 } else if (T->isObjCObjectPointerType()) { 10780 // FIXME: should this be a test for macosx-fragile specifically? 10781 if (getLangOpts().ObjCRuntime.isFragile()) 10782 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10783 } 10784 } 10785 10786 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10787 ExDeclType, TInfo, SC_None); 10788 ExDecl->setExceptionVariable(true); 10789 10790 // In ARC, infer 'retaining' for variables of retainable type. 10791 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10792 Invalid = true; 10793 10794 if (!Invalid && !ExDeclType->isDependentType()) { 10795 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10796 // Insulate this from anything else we might currently be parsing. 10797 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10798 10799 // C++ [except.handle]p16: 10800 // The object declared in an exception-declaration or, if the 10801 // exception-declaration does not specify a name, a temporary (12.2) is 10802 // copy-initialized (8.5) from the exception object. [...] 10803 // The object is destroyed when the handler exits, after the destruction 10804 // of any automatic objects initialized within the handler. 10805 // 10806 // We just pretend to initialize the object with itself, then make sure 10807 // it can be destroyed later. 10808 QualType initType = ExDeclType; 10809 10810 InitializedEntity entity = 10811 InitializedEntity::InitializeVariable(ExDecl); 10812 InitializationKind initKind = 10813 InitializationKind::CreateCopy(Loc, SourceLocation()); 10814 10815 Expr *opaqueValue = 10816 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10817 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 10818 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 10819 if (result.isInvalid()) 10820 Invalid = true; 10821 else { 10822 // If the constructor used was non-trivial, set this as the 10823 // "initializer". 10824 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10825 if (!construct->getConstructor()->isTrivial()) { 10826 Expr *init = MaybeCreateExprWithCleanups(construct); 10827 ExDecl->setInit(init); 10828 } 10829 10830 // And make sure it's destructable. 10831 FinalizeVarWithDestructor(ExDecl, recordType); 10832 } 10833 } 10834 } 10835 10836 if (Invalid) 10837 ExDecl->setInvalidDecl(); 10838 10839 return ExDecl; 10840} 10841 10842/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10843/// handler. 10844Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10845 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10846 bool Invalid = D.isInvalidType(); 10847 10848 // Check for unexpanded parameter packs. 10849 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10850 UPPC_ExceptionType)) { 10851 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10852 D.getIdentifierLoc()); 10853 Invalid = true; 10854 } 10855 10856 IdentifierInfo *II = D.getIdentifier(); 10857 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10858 LookupOrdinaryName, 10859 ForRedeclaration)) { 10860 // The scope should be freshly made just for us. There is just no way 10861 // it contains any previous declaration. 10862 assert(!S->isDeclScope(PrevDecl)); 10863 if (PrevDecl->isTemplateParameter()) { 10864 // Maybe we will complain about the shadowed template parameter. 10865 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10866 PrevDecl = 0; 10867 } 10868 } 10869 10870 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10871 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10872 << D.getCXXScopeSpec().getRange(); 10873 Invalid = true; 10874 } 10875 10876 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10877 D.getLocStart(), 10878 D.getIdentifierLoc(), 10879 D.getIdentifier()); 10880 if (Invalid) 10881 ExDecl->setInvalidDecl(); 10882 10883 // Add the exception declaration into this scope. 10884 if (II) 10885 PushOnScopeChains(ExDecl, S); 10886 else 10887 CurContext->addDecl(ExDecl); 10888 10889 ProcessDeclAttributes(S, ExDecl, D); 10890 return ExDecl; 10891} 10892 10893Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10894 Expr *AssertExpr, 10895 Expr *AssertMessageExpr, 10896 SourceLocation RParenLoc) { 10897 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10898 10899 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10900 return 0; 10901 10902 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10903 AssertMessage, RParenLoc, false); 10904} 10905 10906Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10907 Expr *AssertExpr, 10908 StringLiteral *AssertMessage, 10909 SourceLocation RParenLoc, 10910 bool Failed) { 10911 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10912 !Failed) { 10913 // In a static_assert-declaration, the constant-expression shall be a 10914 // constant expression that can be contextually converted to bool. 10915 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10916 if (Converted.isInvalid()) 10917 Failed = true; 10918 10919 llvm::APSInt Cond; 10920 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10921 diag::err_static_assert_expression_is_not_constant, 10922 /*AllowFold=*/false).isInvalid()) 10923 Failed = true; 10924 10925 if (!Failed && !Cond) { 10926 SmallString<256> MsgBuffer; 10927 llvm::raw_svector_ostream Msg(MsgBuffer); 10928 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10929 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10930 << Msg.str() << AssertExpr->getSourceRange(); 10931 Failed = true; 10932 } 10933 } 10934 10935 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10936 AssertExpr, AssertMessage, RParenLoc, 10937 Failed); 10938 10939 CurContext->addDecl(Decl); 10940 return Decl; 10941} 10942 10943/// \brief Perform semantic analysis of the given friend type declaration. 10944/// 10945/// \returns A friend declaration that. 10946FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10947 SourceLocation FriendLoc, 10948 TypeSourceInfo *TSInfo) { 10949 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10950 10951 QualType T = TSInfo->getType(); 10952 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10953 10954 // C++03 [class.friend]p2: 10955 // An elaborated-type-specifier shall be used in a friend declaration 10956 // for a class.* 10957 // 10958 // * The class-key of the elaborated-type-specifier is required. 10959 if (!ActiveTemplateInstantiations.empty()) { 10960 // Do not complain about the form of friend template types during 10961 // template instantiation; we will already have complained when the 10962 // template was declared. 10963 } else { 10964 if (!T->isElaboratedTypeSpecifier()) { 10965 // If we evaluated the type to a record type, suggest putting 10966 // a tag in front. 10967 if (const RecordType *RT = T->getAs<RecordType>()) { 10968 RecordDecl *RD = RT->getDecl(); 10969 10970 std::string InsertionText = std::string(" ") + RD->getKindName(); 10971 10972 Diag(TypeRange.getBegin(), 10973 getLangOpts().CPlusPlus11 ? 10974 diag::warn_cxx98_compat_unelaborated_friend_type : 10975 diag::ext_unelaborated_friend_type) 10976 << (unsigned) RD->getTagKind() 10977 << T 10978 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10979 InsertionText); 10980 } else { 10981 Diag(FriendLoc, 10982 getLangOpts().CPlusPlus11 ? 10983 diag::warn_cxx98_compat_nonclass_type_friend : 10984 diag::ext_nonclass_type_friend) 10985 << T 10986 << TypeRange; 10987 } 10988 } else if (T->getAs<EnumType>()) { 10989 Diag(FriendLoc, 10990 getLangOpts().CPlusPlus11 ? 10991 diag::warn_cxx98_compat_enum_friend : 10992 diag::ext_enum_friend) 10993 << T 10994 << TypeRange; 10995 } 10996 10997 // C++11 [class.friend]p3: 10998 // A friend declaration that does not declare a function shall have one 10999 // of the following forms: 11000 // friend elaborated-type-specifier ; 11001 // friend simple-type-specifier ; 11002 // friend typename-specifier ; 11003 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11004 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11005 } 11006 11007 // If the type specifier in a friend declaration designates a (possibly 11008 // cv-qualified) class type, that class is declared as a friend; otherwise, 11009 // the friend declaration is ignored. 11010 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11011} 11012 11013/// Handle a friend tag declaration where the scope specifier was 11014/// templated. 11015Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11016 unsigned TagSpec, SourceLocation TagLoc, 11017 CXXScopeSpec &SS, 11018 IdentifierInfo *Name, 11019 SourceLocation NameLoc, 11020 AttributeList *Attr, 11021 MultiTemplateParamsArg TempParamLists) { 11022 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11023 11024 bool isExplicitSpecialization = false; 11025 bool Invalid = false; 11026 11027 if (TemplateParameterList *TemplateParams = 11028 MatchTemplateParametersToScopeSpecifier( 11029 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11030 isExplicitSpecialization, Invalid)) { 11031 if (TemplateParams->size() > 0) { 11032 // This is a declaration of a class template. 11033 if (Invalid) 11034 return 0; 11035 11036 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11037 SS, Name, NameLoc, Attr, 11038 TemplateParams, AS_public, 11039 /*ModulePrivateLoc=*/SourceLocation(), 11040 TempParamLists.size() - 1, 11041 TempParamLists.data()).take(); 11042 } else { 11043 // The "template<>" header is extraneous. 11044 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11045 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11046 isExplicitSpecialization = true; 11047 } 11048 } 11049 11050 if (Invalid) return 0; 11051 11052 bool isAllExplicitSpecializations = true; 11053 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11054 if (TempParamLists[I]->size()) { 11055 isAllExplicitSpecializations = false; 11056 break; 11057 } 11058 } 11059 11060 // FIXME: don't ignore attributes. 11061 11062 // If it's explicit specializations all the way down, just forget 11063 // about the template header and build an appropriate non-templated 11064 // friend. TODO: for source fidelity, remember the headers. 11065 if (isAllExplicitSpecializations) { 11066 if (SS.isEmpty()) { 11067 bool Owned = false; 11068 bool IsDependent = false; 11069 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11070 Attr, AS_public, 11071 /*ModulePrivateLoc=*/SourceLocation(), 11072 MultiTemplateParamsArg(), Owned, IsDependent, 11073 /*ScopedEnumKWLoc=*/SourceLocation(), 11074 /*ScopedEnumUsesClassTag=*/false, 11075 /*UnderlyingType=*/TypeResult()); 11076 } 11077 11078 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11079 ElaboratedTypeKeyword Keyword 11080 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11081 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11082 *Name, NameLoc); 11083 if (T.isNull()) 11084 return 0; 11085 11086 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11087 if (isa<DependentNameType>(T)) { 11088 DependentNameTypeLoc TL = 11089 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11090 TL.setElaboratedKeywordLoc(TagLoc); 11091 TL.setQualifierLoc(QualifierLoc); 11092 TL.setNameLoc(NameLoc); 11093 } else { 11094 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11095 TL.setElaboratedKeywordLoc(TagLoc); 11096 TL.setQualifierLoc(QualifierLoc); 11097 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11098 } 11099 11100 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11101 TSI, FriendLoc, TempParamLists); 11102 Friend->setAccess(AS_public); 11103 CurContext->addDecl(Friend); 11104 return Friend; 11105 } 11106 11107 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11108 11109 11110 11111 // Handle the case of a templated-scope friend class. e.g. 11112 // template <class T> class A<T>::B; 11113 // FIXME: we don't support these right now. 11114 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11115 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11116 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11117 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11118 TL.setElaboratedKeywordLoc(TagLoc); 11119 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11120 TL.setNameLoc(NameLoc); 11121 11122 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11123 TSI, FriendLoc, TempParamLists); 11124 Friend->setAccess(AS_public); 11125 Friend->setUnsupportedFriend(true); 11126 CurContext->addDecl(Friend); 11127 return Friend; 11128} 11129 11130 11131/// Handle a friend type declaration. This works in tandem with 11132/// ActOnTag. 11133/// 11134/// Notes on friend class templates: 11135/// 11136/// We generally treat friend class declarations as if they were 11137/// declaring a class. So, for example, the elaborated type specifier 11138/// in a friend declaration is required to obey the restrictions of a 11139/// class-head (i.e. no typedefs in the scope chain), template 11140/// parameters are required to match up with simple template-ids, &c. 11141/// However, unlike when declaring a template specialization, it's 11142/// okay to refer to a template specialization without an empty 11143/// template parameter declaration, e.g. 11144/// friend class A<T>::B<unsigned>; 11145/// We permit this as a special case; if there are any template 11146/// parameters present at all, require proper matching, i.e. 11147/// template <> template \<class T> friend class A<int>::B; 11148Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11149 MultiTemplateParamsArg TempParams) { 11150 SourceLocation Loc = DS.getLocStart(); 11151 11152 assert(DS.isFriendSpecified()); 11153 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11154 11155 // Try to convert the decl specifier to a type. This works for 11156 // friend templates because ActOnTag never produces a ClassTemplateDecl 11157 // for a TUK_Friend. 11158 Declarator TheDeclarator(DS, Declarator::MemberContext); 11159 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11160 QualType T = TSI->getType(); 11161 if (TheDeclarator.isInvalidType()) 11162 return 0; 11163 11164 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11165 return 0; 11166 11167 // This is definitely an error in C++98. It's probably meant to 11168 // be forbidden in C++0x, too, but the specification is just 11169 // poorly written. 11170 // 11171 // The problem is with declarations like the following: 11172 // template <T> friend A<T>::foo; 11173 // where deciding whether a class C is a friend or not now hinges 11174 // on whether there exists an instantiation of A that causes 11175 // 'foo' to equal C. There are restrictions on class-heads 11176 // (which we declare (by fiat) elaborated friend declarations to 11177 // be) that makes this tractable. 11178 // 11179 // FIXME: handle "template <> friend class A<T>;", which 11180 // is possibly well-formed? Who even knows? 11181 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11182 Diag(Loc, diag::err_tagless_friend_type_template) 11183 << DS.getSourceRange(); 11184 return 0; 11185 } 11186 11187 // C++98 [class.friend]p1: A friend of a class is a function 11188 // or class that is not a member of the class . . . 11189 // This is fixed in DR77, which just barely didn't make the C++03 11190 // deadline. It's also a very silly restriction that seriously 11191 // affects inner classes and which nobody else seems to implement; 11192 // thus we never diagnose it, not even in -pedantic. 11193 // 11194 // But note that we could warn about it: it's always useless to 11195 // friend one of your own members (it's not, however, worthless to 11196 // friend a member of an arbitrary specialization of your template). 11197 11198 Decl *D; 11199 if (unsigned NumTempParamLists = TempParams.size()) 11200 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11201 NumTempParamLists, 11202 TempParams.data(), 11203 TSI, 11204 DS.getFriendSpecLoc()); 11205 else 11206 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11207 11208 if (!D) 11209 return 0; 11210 11211 D->setAccess(AS_public); 11212 CurContext->addDecl(D); 11213 11214 return D; 11215} 11216 11217NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11218 MultiTemplateParamsArg TemplateParams) { 11219 const DeclSpec &DS = D.getDeclSpec(); 11220 11221 assert(DS.isFriendSpecified()); 11222 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11223 11224 SourceLocation Loc = D.getIdentifierLoc(); 11225 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11226 11227 // C++ [class.friend]p1 11228 // A friend of a class is a function or class.... 11229 // Note that this sees through typedefs, which is intended. 11230 // It *doesn't* see through dependent types, which is correct 11231 // according to [temp.arg.type]p3: 11232 // If a declaration acquires a function type through a 11233 // type dependent on a template-parameter and this causes 11234 // a declaration that does not use the syntactic form of a 11235 // function declarator to have a function type, the program 11236 // is ill-formed. 11237 if (!TInfo->getType()->isFunctionType()) { 11238 Diag(Loc, diag::err_unexpected_friend); 11239 11240 // It might be worthwhile to try to recover by creating an 11241 // appropriate declaration. 11242 return 0; 11243 } 11244 11245 // C++ [namespace.memdef]p3 11246 // - If a friend declaration in a non-local class first declares a 11247 // class or function, the friend class or function is a member 11248 // of the innermost enclosing namespace. 11249 // - The name of the friend is not found by simple name lookup 11250 // until a matching declaration is provided in that namespace 11251 // scope (either before or after the class declaration granting 11252 // friendship). 11253 // - If a friend function is called, its name may be found by the 11254 // name lookup that considers functions from namespaces and 11255 // classes associated with the types of the function arguments. 11256 // - When looking for a prior declaration of a class or a function 11257 // declared as a friend, scopes outside the innermost enclosing 11258 // namespace scope are not considered. 11259 11260 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11261 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11262 DeclarationName Name = NameInfo.getName(); 11263 assert(Name); 11264 11265 // Check for unexpanded parameter packs. 11266 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11267 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11268 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11269 return 0; 11270 11271 // The context we found the declaration in, or in which we should 11272 // create the declaration. 11273 DeclContext *DC; 11274 Scope *DCScope = S; 11275 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11276 ForRedeclaration); 11277 11278 // FIXME: there are different rules in local classes 11279 11280 // There are four cases here. 11281 // - There's no scope specifier, in which case we just go to the 11282 // appropriate scope and look for a function or function template 11283 // there as appropriate. 11284 // Recover from invalid scope qualifiers as if they just weren't there. 11285 if (SS.isInvalid() || !SS.isSet()) { 11286 // C++0x [namespace.memdef]p3: 11287 // If the name in a friend declaration is neither qualified nor 11288 // a template-id and the declaration is a function or an 11289 // elaborated-type-specifier, the lookup to determine whether 11290 // the entity has been previously declared shall not consider 11291 // any scopes outside the innermost enclosing namespace. 11292 // C++0x [class.friend]p11: 11293 // If a friend declaration appears in a local class and the name 11294 // specified is an unqualified name, a prior declaration is 11295 // looked up without considering scopes that are outside the 11296 // innermost enclosing non-class scope. For a friend function 11297 // declaration, if there is no prior declaration, the program is 11298 // ill-formed. 11299 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 11300 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11301 11302 // Find the appropriate context according to the above. 11303 DC = CurContext; 11304 11305 // Skip class contexts. If someone can cite chapter and verse 11306 // for this behavior, that would be nice --- it's what GCC and 11307 // EDG do, and it seems like a reasonable intent, but the spec 11308 // really only says that checks for unqualified existing 11309 // declarations should stop at the nearest enclosing namespace, 11310 // not that they should only consider the nearest enclosing 11311 // namespace. 11312 while (DC->isRecord()) 11313 DC = DC->getParent(); 11314 11315 DeclContext *LookupDC = DC; 11316 while (LookupDC->isTransparentContext()) 11317 LookupDC = LookupDC->getParent(); 11318 11319 while (true) { 11320 LookupQualifiedName(Previous, LookupDC); 11321 11322 // TODO: decide what we think about using declarations. 11323 if (isLocal) 11324 break; 11325 11326 if (!Previous.empty()) { 11327 DC = LookupDC; 11328 break; 11329 } 11330 11331 if (isTemplateId) { 11332 if (isa<TranslationUnitDecl>(LookupDC)) break; 11333 } else { 11334 if (LookupDC->isFileContext()) break; 11335 } 11336 LookupDC = LookupDC->getParent(); 11337 } 11338 11339 DCScope = getScopeForDeclContext(S, DC); 11340 11341 // C++ [class.friend]p6: 11342 // A function can be defined in a friend declaration of a class if and 11343 // only if the class is a non-local class (9.8), the function name is 11344 // unqualified, and the function has namespace scope. 11345 if (isLocal && D.isFunctionDefinition()) { 11346 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11347 } 11348 11349 // - There's a non-dependent scope specifier, in which case we 11350 // compute it and do a previous lookup there for a function 11351 // or function template. 11352 } else if (!SS.getScopeRep()->isDependent()) { 11353 DC = computeDeclContext(SS); 11354 if (!DC) return 0; 11355 11356 if (RequireCompleteDeclContext(SS, DC)) return 0; 11357 11358 LookupQualifiedName(Previous, DC); 11359 11360 // Ignore things found implicitly in the wrong scope. 11361 // TODO: better diagnostics for this case. Suggesting the right 11362 // qualified scope would be nice... 11363 LookupResult::Filter F = Previous.makeFilter(); 11364 while (F.hasNext()) { 11365 NamedDecl *D = F.next(); 11366 if (!DC->InEnclosingNamespaceSetOf( 11367 D->getDeclContext()->getRedeclContext())) 11368 F.erase(); 11369 } 11370 F.done(); 11371 11372 if (Previous.empty()) { 11373 D.setInvalidType(); 11374 Diag(Loc, diag::err_qualified_friend_not_found) 11375 << Name << TInfo->getType(); 11376 return 0; 11377 } 11378 11379 // C++ [class.friend]p1: A friend of a class is a function or 11380 // class that is not a member of the class . . . 11381 if (DC->Equals(CurContext)) 11382 Diag(DS.getFriendSpecLoc(), 11383 getLangOpts().CPlusPlus11 ? 11384 diag::warn_cxx98_compat_friend_is_member : 11385 diag::err_friend_is_member); 11386 11387 if (D.isFunctionDefinition()) { 11388 // C++ [class.friend]p6: 11389 // A function can be defined in a friend declaration of a class if and 11390 // only if the class is a non-local class (9.8), the function name is 11391 // unqualified, and the function has namespace scope. 11392 SemaDiagnosticBuilder DB 11393 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11394 11395 DB << SS.getScopeRep(); 11396 if (DC->isFileContext()) 11397 DB << FixItHint::CreateRemoval(SS.getRange()); 11398 SS.clear(); 11399 } 11400 11401 // - There's a scope specifier that does not match any template 11402 // parameter lists, in which case we use some arbitrary context, 11403 // create a method or method template, and wait for instantiation. 11404 // - There's a scope specifier that does match some template 11405 // parameter lists, which we don't handle right now. 11406 } else { 11407 if (D.isFunctionDefinition()) { 11408 // C++ [class.friend]p6: 11409 // A function can be defined in a friend declaration of a class if and 11410 // only if the class is a non-local class (9.8), the function name is 11411 // unqualified, and the function has namespace scope. 11412 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11413 << SS.getScopeRep(); 11414 } 11415 11416 DC = CurContext; 11417 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11418 } 11419 11420 if (!DC->isRecord()) { 11421 // This implies that it has to be an operator or function. 11422 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11423 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11424 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11425 Diag(Loc, diag::err_introducing_special_friend) << 11426 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11427 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11428 return 0; 11429 } 11430 } 11431 11432 // FIXME: This is an egregious hack to cope with cases where the scope stack 11433 // does not contain the declaration context, i.e., in an out-of-line 11434 // definition of a class. 11435 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11436 if (!DCScope) { 11437 FakeDCScope.setEntity(DC); 11438 DCScope = &FakeDCScope; 11439 } 11440 11441 bool AddToScope = true; 11442 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11443 TemplateParams, AddToScope); 11444 if (!ND) return 0; 11445 11446 assert(ND->getDeclContext() == DC); 11447 assert(ND->getLexicalDeclContext() == CurContext); 11448 11449 // Add the function declaration to the appropriate lookup tables, 11450 // adjusting the redeclarations list as necessary. We don't 11451 // want to do this yet if the friending class is dependent. 11452 // 11453 // Also update the scope-based lookup if the target context's 11454 // lookup context is in lexical scope. 11455 if (!CurContext->isDependentContext()) { 11456 DC = DC->getRedeclContext(); 11457 DC->makeDeclVisibleInContext(ND); 11458 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11459 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11460 } 11461 11462 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11463 D.getIdentifierLoc(), ND, 11464 DS.getFriendSpecLoc()); 11465 FrD->setAccess(AS_public); 11466 CurContext->addDecl(FrD); 11467 11468 if (ND->isInvalidDecl()) { 11469 FrD->setInvalidDecl(); 11470 } else { 11471 if (DC->isRecord()) CheckFriendAccess(ND); 11472 11473 FunctionDecl *FD; 11474 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11475 FD = FTD->getTemplatedDecl(); 11476 else 11477 FD = cast<FunctionDecl>(ND); 11478 11479 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11480 // default argument expression, that declaration shall be a definition 11481 // and shall be the only declaration of the function or function 11482 // template in the translation unit. 11483 if (functionDeclHasDefaultArgument(FD)) { 11484 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11485 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11486 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11487 } else if (!D.isFunctionDefinition()) 11488 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11489 } 11490 11491 // Mark templated-scope function declarations as unsupported. 11492 if (FD->getNumTemplateParameterLists()) 11493 FrD->setUnsupportedFriend(true); 11494 } 11495 11496 return ND; 11497} 11498 11499void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11500 AdjustDeclIfTemplate(Dcl); 11501 11502 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11503 if (!Fn) { 11504 Diag(DelLoc, diag::err_deleted_non_function); 11505 return; 11506 } 11507 11508 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11509 // Don't consider the implicit declaration we generate for explicit 11510 // specializations. FIXME: Do not generate these implicit declarations. 11511 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11512 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11513 Diag(DelLoc, diag::err_deleted_decl_not_first); 11514 Diag(Prev->getLocation(), diag::note_previous_declaration); 11515 } 11516 // If the declaration wasn't the first, we delete the function anyway for 11517 // recovery. 11518 Fn = Fn->getCanonicalDecl(); 11519 } 11520 11521 if (Fn->isDeleted()) 11522 return; 11523 11524 // See if we're deleting a function which is already known to override a 11525 // non-deleted virtual function. 11526 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11527 bool IssuedDiagnostic = false; 11528 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11529 E = MD->end_overridden_methods(); 11530 I != E; ++I) { 11531 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11532 if (!IssuedDiagnostic) { 11533 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11534 IssuedDiagnostic = true; 11535 } 11536 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11537 } 11538 } 11539 } 11540 11541 Fn->setDeletedAsWritten(); 11542} 11543 11544void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11545 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11546 11547 if (MD) { 11548 if (MD->getParent()->isDependentType()) { 11549 MD->setDefaulted(); 11550 MD->setExplicitlyDefaulted(); 11551 return; 11552 } 11553 11554 CXXSpecialMember Member = getSpecialMember(MD); 11555 if (Member == CXXInvalid) { 11556 if (!MD->isInvalidDecl()) 11557 Diag(DefaultLoc, diag::err_default_special_members); 11558 return; 11559 } 11560 11561 MD->setDefaulted(); 11562 MD->setExplicitlyDefaulted(); 11563 11564 // If this definition appears within the record, do the checking when 11565 // the record is complete. 11566 const FunctionDecl *Primary = MD; 11567 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11568 // Find the uninstantiated declaration that actually had the '= default' 11569 // on it. 11570 Pattern->isDefined(Primary); 11571 11572 // If the method was defaulted on its first declaration, we will have 11573 // already performed the checking in CheckCompletedCXXClass. Such a 11574 // declaration doesn't trigger an implicit definition. 11575 if (Primary == Primary->getCanonicalDecl()) 11576 return; 11577 11578 CheckExplicitlyDefaultedSpecialMember(MD); 11579 11580 // The exception specification is needed because we are defining the 11581 // function. 11582 ResolveExceptionSpec(DefaultLoc, 11583 MD->getType()->castAs<FunctionProtoType>()); 11584 11585 switch (Member) { 11586 case CXXDefaultConstructor: { 11587 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11588 if (!CD->isInvalidDecl()) 11589 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11590 break; 11591 } 11592 11593 case CXXCopyConstructor: { 11594 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11595 if (!CD->isInvalidDecl()) 11596 DefineImplicitCopyConstructor(DefaultLoc, CD); 11597 break; 11598 } 11599 11600 case CXXCopyAssignment: { 11601 if (!MD->isInvalidDecl()) 11602 DefineImplicitCopyAssignment(DefaultLoc, MD); 11603 break; 11604 } 11605 11606 case CXXDestructor: { 11607 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11608 if (!DD->isInvalidDecl()) 11609 DefineImplicitDestructor(DefaultLoc, DD); 11610 break; 11611 } 11612 11613 case CXXMoveConstructor: { 11614 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11615 if (!CD->isInvalidDecl()) 11616 DefineImplicitMoveConstructor(DefaultLoc, CD); 11617 break; 11618 } 11619 11620 case CXXMoveAssignment: { 11621 if (!MD->isInvalidDecl()) 11622 DefineImplicitMoveAssignment(DefaultLoc, MD); 11623 break; 11624 } 11625 11626 case CXXInvalid: 11627 llvm_unreachable("Invalid special member."); 11628 } 11629 } else { 11630 Diag(DefaultLoc, diag::err_default_special_members); 11631 } 11632} 11633 11634static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11635 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11636 Stmt *SubStmt = *CI; 11637 if (!SubStmt) 11638 continue; 11639 if (isa<ReturnStmt>(SubStmt)) 11640 Self.Diag(SubStmt->getLocStart(), 11641 diag::err_return_in_constructor_handler); 11642 if (!isa<Expr>(SubStmt)) 11643 SearchForReturnInStmt(Self, SubStmt); 11644 } 11645} 11646 11647void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11648 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11649 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11650 SearchForReturnInStmt(*this, Handler); 11651 } 11652} 11653 11654bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11655 const CXXMethodDecl *Old) { 11656 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11657 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11658 11659 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11660 11661 // If the calling conventions match, everything is fine 11662 if (NewCC == OldCC) 11663 return false; 11664 11665 // If either of the calling conventions are set to "default", we need to pick 11666 // something more sensible based on the target. This supports code where the 11667 // one method explicitly sets thiscall, and another has no explicit calling 11668 // convention. 11669 CallingConv Default = 11670 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11671 if (NewCC == CC_Default) 11672 NewCC = Default; 11673 if (OldCC == CC_Default) 11674 OldCC = Default; 11675 11676 // If the calling conventions still don't match, then report the error 11677 if (NewCC != OldCC) { 11678 Diag(New->getLocation(), 11679 diag::err_conflicting_overriding_cc_attributes) 11680 << New->getDeclName() << New->getType() << Old->getType(); 11681 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11682 return true; 11683 } 11684 11685 return false; 11686} 11687 11688bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11689 const CXXMethodDecl *Old) { 11690 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11691 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11692 11693 if (Context.hasSameType(NewTy, OldTy) || 11694 NewTy->isDependentType() || OldTy->isDependentType()) 11695 return false; 11696 11697 // Check if the return types are covariant 11698 QualType NewClassTy, OldClassTy; 11699 11700 /// Both types must be pointers or references to classes. 11701 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11702 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11703 NewClassTy = NewPT->getPointeeType(); 11704 OldClassTy = OldPT->getPointeeType(); 11705 } 11706 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11707 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11708 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11709 NewClassTy = NewRT->getPointeeType(); 11710 OldClassTy = OldRT->getPointeeType(); 11711 } 11712 } 11713 } 11714 11715 // The return types aren't either both pointers or references to a class type. 11716 if (NewClassTy.isNull()) { 11717 Diag(New->getLocation(), 11718 diag::err_different_return_type_for_overriding_virtual_function) 11719 << New->getDeclName() << NewTy << OldTy; 11720 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11721 11722 return true; 11723 } 11724 11725 // C++ [class.virtual]p6: 11726 // If the return type of D::f differs from the return type of B::f, the 11727 // class type in the return type of D::f shall be complete at the point of 11728 // declaration of D::f or shall be the class type D. 11729 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11730 if (!RT->isBeingDefined() && 11731 RequireCompleteType(New->getLocation(), NewClassTy, 11732 diag::err_covariant_return_incomplete, 11733 New->getDeclName())) 11734 return true; 11735 } 11736 11737 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11738 // Check if the new class derives from the old class. 11739 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11740 Diag(New->getLocation(), 11741 diag::err_covariant_return_not_derived) 11742 << New->getDeclName() << NewTy << OldTy; 11743 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11744 return true; 11745 } 11746 11747 // Check if we the conversion from derived to base is valid. 11748 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11749 diag::err_covariant_return_inaccessible_base, 11750 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11751 // FIXME: Should this point to the return type? 11752 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11753 // FIXME: this note won't trigger for delayed access control 11754 // diagnostics, and it's impossible to get an undelayed error 11755 // here from access control during the original parse because 11756 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11757 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11758 return true; 11759 } 11760 } 11761 11762 // The qualifiers of the return types must be the same. 11763 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11764 Diag(New->getLocation(), 11765 diag::err_covariant_return_type_different_qualifications) 11766 << New->getDeclName() << NewTy << OldTy; 11767 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11768 return true; 11769 }; 11770 11771 11772 // The new class type must have the same or less qualifiers as the old type. 11773 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11774 Diag(New->getLocation(), 11775 diag::err_covariant_return_type_class_type_more_qualified) 11776 << New->getDeclName() << NewTy << OldTy; 11777 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11778 return true; 11779 }; 11780 11781 return false; 11782} 11783 11784/// \brief Mark the given method pure. 11785/// 11786/// \param Method the method to be marked pure. 11787/// 11788/// \param InitRange the source range that covers the "0" initializer. 11789bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11790 SourceLocation EndLoc = InitRange.getEnd(); 11791 if (EndLoc.isValid()) 11792 Method->setRangeEnd(EndLoc); 11793 11794 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11795 Method->setPure(); 11796 return false; 11797 } 11798 11799 if (!Method->isInvalidDecl()) 11800 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11801 << Method->getDeclName() << InitRange; 11802 return true; 11803} 11804 11805/// \brief Determine whether the given declaration is a static data member. 11806static bool isStaticDataMember(Decl *D) { 11807 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11808 if (!Var) 11809 return false; 11810 11811 return Var->isStaticDataMember(); 11812} 11813/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11814/// an initializer for the out-of-line declaration 'Dcl'. The scope 11815/// is a fresh scope pushed for just this purpose. 11816/// 11817/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11818/// static data member of class X, names should be looked up in the scope of 11819/// class X. 11820void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11821 // If there is no declaration, there was an error parsing it. 11822 if (D == 0 || D->isInvalidDecl()) return; 11823 11824 // We should only get called for declarations with scope specifiers, like: 11825 // int foo::bar; 11826 assert(D->isOutOfLine()); 11827 EnterDeclaratorContext(S, D->getDeclContext()); 11828 11829 // If we are parsing the initializer for a static data member, push a 11830 // new expression evaluation context that is associated with this static 11831 // data member. 11832 if (isStaticDataMember(D)) 11833 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11834} 11835 11836/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11837/// initializer for the out-of-line declaration 'D'. 11838void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11839 // If there is no declaration, there was an error parsing it. 11840 if (D == 0 || D->isInvalidDecl()) return; 11841 11842 if (isStaticDataMember(D)) 11843 PopExpressionEvaluationContext(); 11844 11845 assert(D->isOutOfLine()); 11846 ExitDeclaratorContext(S); 11847} 11848 11849/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11850/// C++ if/switch/while/for statement. 11851/// e.g: "if (int x = f()) {...}" 11852DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11853 // C++ 6.4p2: 11854 // The declarator shall not specify a function or an array. 11855 // The type-specifier-seq shall not contain typedef and shall not declare a 11856 // new class or enumeration. 11857 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11858 "Parser allowed 'typedef' as storage class of condition decl."); 11859 11860 Decl *Dcl = ActOnDeclarator(S, D); 11861 if (!Dcl) 11862 return true; 11863 11864 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11865 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11866 << D.getSourceRange(); 11867 return true; 11868 } 11869 11870 return Dcl; 11871} 11872 11873void Sema::LoadExternalVTableUses() { 11874 if (!ExternalSource) 11875 return; 11876 11877 SmallVector<ExternalVTableUse, 4> VTables; 11878 ExternalSource->ReadUsedVTables(VTables); 11879 SmallVector<VTableUse, 4> NewUses; 11880 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11881 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11882 = VTablesUsed.find(VTables[I].Record); 11883 // Even if a definition wasn't required before, it may be required now. 11884 if (Pos != VTablesUsed.end()) { 11885 if (!Pos->second && VTables[I].DefinitionRequired) 11886 Pos->second = true; 11887 continue; 11888 } 11889 11890 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11891 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11892 } 11893 11894 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11895} 11896 11897void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11898 bool DefinitionRequired) { 11899 // Ignore any vtable uses in unevaluated operands or for classes that do 11900 // not have a vtable. 11901 if (!Class->isDynamicClass() || Class->isDependentContext() || 11902 CurContext->isDependentContext() || isUnevaluatedContext()) 11903 return; 11904 11905 // Try to insert this class into the map. 11906 LoadExternalVTableUses(); 11907 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11908 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11909 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11910 if (!Pos.second) { 11911 // If we already had an entry, check to see if we are promoting this vtable 11912 // to required a definition. If so, we need to reappend to the VTableUses 11913 // list, since we may have already processed the first entry. 11914 if (DefinitionRequired && !Pos.first->second) { 11915 Pos.first->second = true; 11916 } else { 11917 // Otherwise, we can early exit. 11918 return; 11919 } 11920 } 11921 11922 // Local classes need to have their virtual members marked 11923 // immediately. For all other classes, we mark their virtual members 11924 // at the end of the translation unit. 11925 if (Class->isLocalClass()) 11926 MarkVirtualMembersReferenced(Loc, Class); 11927 else 11928 VTableUses.push_back(std::make_pair(Class, Loc)); 11929} 11930 11931bool Sema::DefineUsedVTables() { 11932 LoadExternalVTableUses(); 11933 if (VTableUses.empty()) 11934 return false; 11935 11936 // Note: The VTableUses vector could grow as a result of marking 11937 // the members of a class as "used", so we check the size each 11938 // time through the loop and prefer indices (which are stable) to 11939 // iterators (which are not). 11940 bool DefinedAnything = false; 11941 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11942 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11943 if (!Class) 11944 continue; 11945 11946 SourceLocation Loc = VTableUses[I].second; 11947 11948 bool DefineVTable = true; 11949 11950 // If this class has a key function, but that key function is 11951 // defined in another translation unit, we don't need to emit the 11952 // vtable even though we're using it. 11953 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11954 if (KeyFunction && !KeyFunction->hasBody()) { 11955 switch (KeyFunction->getTemplateSpecializationKind()) { 11956 case TSK_Undeclared: 11957 case TSK_ExplicitSpecialization: 11958 case TSK_ExplicitInstantiationDeclaration: 11959 // The key function is in another translation unit. 11960 DefineVTable = false; 11961 break; 11962 11963 case TSK_ExplicitInstantiationDefinition: 11964 case TSK_ImplicitInstantiation: 11965 // We will be instantiating the key function. 11966 break; 11967 } 11968 } else if (!KeyFunction) { 11969 // If we have a class with no key function that is the subject 11970 // of an explicit instantiation declaration, suppress the 11971 // vtable; it will live with the explicit instantiation 11972 // definition. 11973 bool IsExplicitInstantiationDeclaration 11974 = Class->getTemplateSpecializationKind() 11975 == TSK_ExplicitInstantiationDeclaration; 11976 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11977 REnd = Class->redecls_end(); 11978 R != REnd; ++R) { 11979 TemplateSpecializationKind TSK 11980 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11981 if (TSK == TSK_ExplicitInstantiationDeclaration) 11982 IsExplicitInstantiationDeclaration = true; 11983 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11984 IsExplicitInstantiationDeclaration = false; 11985 break; 11986 } 11987 } 11988 11989 if (IsExplicitInstantiationDeclaration) 11990 DefineVTable = false; 11991 } 11992 11993 // The exception specifications for all virtual members may be needed even 11994 // if we are not providing an authoritative form of the vtable in this TU. 11995 // We may choose to emit it available_externally anyway. 11996 if (!DefineVTable) { 11997 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11998 continue; 11999 } 12000 12001 // Mark all of the virtual members of this class as referenced, so 12002 // that we can build a vtable. Then, tell the AST consumer that a 12003 // vtable for this class is required. 12004 DefinedAnything = true; 12005 MarkVirtualMembersReferenced(Loc, Class); 12006 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12007 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12008 12009 // Optionally warn if we're emitting a weak vtable. 12010 if (Class->isExternallyVisible() && 12011 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12012 const FunctionDecl *KeyFunctionDef = 0; 12013 if (!KeyFunction || 12014 (KeyFunction->hasBody(KeyFunctionDef) && 12015 KeyFunctionDef->isInlined())) 12016 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12017 TSK_ExplicitInstantiationDefinition 12018 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12019 << Class; 12020 } 12021 } 12022 VTableUses.clear(); 12023 12024 return DefinedAnything; 12025} 12026 12027void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12028 const CXXRecordDecl *RD) { 12029 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 12030 E = RD->method_end(); I != E; ++I) 12031 if ((*I)->isVirtual() && !(*I)->isPure()) 12032 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 12033} 12034 12035void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12036 const CXXRecordDecl *RD) { 12037 // Mark all functions which will appear in RD's vtable as used. 12038 CXXFinalOverriderMap FinalOverriders; 12039 RD->getFinalOverriders(FinalOverriders); 12040 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12041 E = FinalOverriders.end(); 12042 I != E; ++I) { 12043 for (OverridingMethods::const_iterator OI = I->second.begin(), 12044 OE = I->second.end(); 12045 OI != OE; ++OI) { 12046 assert(OI->second.size() > 0 && "no final overrider"); 12047 CXXMethodDecl *Overrider = OI->second.front().Method; 12048 12049 // C++ [basic.def.odr]p2: 12050 // [...] A virtual member function is used if it is not pure. [...] 12051 if (!Overrider->isPure()) 12052 MarkFunctionReferenced(Loc, Overrider); 12053 } 12054 } 12055 12056 // Only classes that have virtual bases need a VTT. 12057 if (RD->getNumVBases() == 0) 12058 return; 12059 12060 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 12061 e = RD->bases_end(); i != e; ++i) { 12062 const CXXRecordDecl *Base = 12063 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 12064 if (Base->getNumVBases() == 0) 12065 continue; 12066 MarkVirtualMembersReferenced(Loc, Base); 12067 } 12068} 12069 12070/// SetIvarInitializers - This routine builds initialization ASTs for the 12071/// Objective-C implementation whose ivars need be initialized. 12072void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12073 if (!getLangOpts().CPlusPlus) 12074 return; 12075 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12076 SmallVector<ObjCIvarDecl*, 8> ivars; 12077 CollectIvarsToConstructOrDestruct(OID, ivars); 12078 if (ivars.empty()) 12079 return; 12080 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12081 for (unsigned i = 0; i < ivars.size(); i++) { 12082 FieldDecl *Field = ivars[i]; 12083 if (Field->isInvalidDecl()) 12084 continue; 12085 12086 CXXCtorInitializer *Member; 12087 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12088 InitializationKind InitKind = 12089 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12090 12091 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12092 ExprResult MemberInit = 12093 InitSeq.Perform(*this, InitEntity, InitKind, None); 12094 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12095 // Note, MemberInit could actually come back empty if no initialization 12096 // is required (e.g., because it would call a trivial default constructor) 12097 if (!MemberInit.get() || MemberInit.isInvalid()) 12098 continue; 12099 12100 Member = 12101 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12102 SourceLocation(), 12103 MemberInit.takeAs<Expr>(), 12104 SourceLocation()); 12105 AllToInit.push_back(Member); 12106 12107 // Be sure that the destructor is accessible and is marked as referenced. 12108 if (const RecordType *RecordTy 12109 = Context.getBaseElementType(Field->getType()) 12110 ->getAs<RecordType>()) { 12111 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12112 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12113 MarkFunctionReferenced(Field->getLocation(), Destructor); 12114 CheckDestructorAccess(Field->getLocation(), Destructor, 12115 PDiag(diag::err_access_dtor_ivar) 12116 << Context.getBaseElementType(Field->getType())); 12117 } 12118 } 12119 } 12120 ObjCImplementation->setIvarInitializers(Context, 12121 AllToInit.data(), AllToInit.size()); 12122 } 12123} 12124 12125static 12126void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12127 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12128 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12129 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12130 Sema &S) { 12131 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12132 CE = Current.end(); 12133 if (Ctor->isInvalidDecl()) 12134 return; 12135 12136 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12137 12138 // Target may not be determinable yet, for instance if this is a dependent 12139 // call in an uninstantiated template. 12140 if (Target) { 12141 const FunctionDecl *FNTarget = 0; 12142 (void)Target->hasBody(FNTarget); 12143 Target = const_cast<CXXConstructorDecl*>( 12144 cast_or_null<CXXConstructorDecl>(FNTarget)); 12145 } 12146 12147 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12148 // Avoid dereferencing a null pointer here. 12149 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12150 12151 if (!Current.insert(Canonical)) 12152 return; 12153 12154 // We know that beyond here, we aren't chaining into a cycle. 12155 if (!Target || !Target->isDelegatingConstructor() || 12156 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12157 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12158 Valid.insert(*CI); 12159 Current.clear(); 12160 // We've hit a cycle. 12161 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12162 Current.count(TCanonical)) { 12163 // If we haven't diagnosed this cycle yet, do so now. 12164 if (!Invalid.count(TCanonical)) { 12165 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12166 diag::warn_delegating_ctor_cycle) 12167 << Ctor; 12168 12169 // Don't add a note for a function delegating directly to itself. 12170 if (TCanonical != Canonical) 12171 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12172 12173 CXXConstructorDecl *C = Target; 12174 while (C->getCanonicalDecl() != Canonical) { 12175 const FunctionDecl *FNTarget = 0; 12176 (void)C->getTargetConstructor()->hasBody(FNTarget); 12177 assert(FNTarget && "Ctor cycle through bodiless function"); 12178 12179 C = const_cast<CXXConstructorDecl*>( 12180 cast<CXXConstructorDecl>(FNTarget)); 12181 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12182 } 12183 } 12184 12185 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12186 Invalid.insert(*CI); 12187 Current.clear(); 12188 } else { 12189 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12190 } 12191} 12192 12193 12194void Sema::CheckDelegatingCtorCycles() { 12195 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12196 12197 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12198 CE = Current.end(); 12199 12200 for (DelegatingCtorDeclsType::iterator 12201 I = DelegatingCtorDecls.begin(ExternalSource), 12202 E = DelegatingCtorDecls.end(); 12203 I != E; ++I) 12204 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12205 12206 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 12207 (*CI)->setInvalidDecl(); 12208} 12209 12210namespace { 12211 /// \brief AST visitor that finds references to the 'this' expression. 12212 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12213 Sema &S; 12214 12215 public: 12216 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12217 12218 bool VisitCXXThisExpr(CXXThisExpr *E) { 12219 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12220 << E->isImplicit(); 12221 return false; 12222 } 12223 }; 12224} 12225 12226bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12227 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12228 if (!TSInfo) 12229 return false; 12230 12231 TypeLoc TL = TSInfo->getTypeLoc(); 12232 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12233 if (!ProtoTL) 12234 return false; 12235 12236 // C++11 [expr.prim.general]p3: 12237 // [The expression this] shall not appear before the optional 12238 // cv-qualifier-seq and it shall not appear within the declaration of a 12239 // static member function (although its type and value category are defined 12240 // within a static member function as they are within a non-static member 12241 // function). [ Note: this is because declaration matching does not occur 12242 // until the complete declarator is known. - end note ] 12243 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12244 FindCXXThisExpr Finder(*this); 12245 12246 // If the return type came after the cv-qualifier-seq, check it now. 12247 if (Proto->hasTrailingReturn() && 12248 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12249 return true; 12250 12251 // Check the exception specification. 12252 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12253 return true; 12254 12255 return checkThisInStaticMemberFunctionAttributes(Method); 12256} 12257 12258bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12259 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12260 if (!TSInfo) 12261 return false; 12262 12263 TypeLoc TL = TSInfo->getTypeLoc(); 12264 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12265 if (!ProtoTL) 12266 return false; 12267 12268 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12269 FindCXXThisExpr Finder(*this); 12270 12271 switch (Proto->getExceptionSpecType()) { 12272 case EST_Uninstantiated: 12273 case EST_Unevaluated: 12274 case EST_BasicNoexcept: 12275 case EST_DynamicNone: 12276 case EST_MSAny: 12277 case EST_None: 12278 break; 12279 12280 case EST_ComputedNoexcept: 12281 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12282 return true; 12283 12284 case EST_Dynamic: 12285 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12286 EEnd = Proto->exception_end(); 12287 E != EEnd; ++E) { 12288 if (!Finder.TraverseType(*E)) 12289 return true; 12290 } 12291 break; 12292 } 12293 12294 return false; 12295} 12296 12297bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12298 FindCXXThisExpr Finder(*this); 12299 12300 // Check attributes. 12301 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12302 A != AEnd; ++A) { 12303 // FIXME: This should be emitted by tblgen. 12304 Expr *Arg = 0; 12305 ArrayRef<Expr *> Args; 12306 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12307 Arg = G->getArg(); 12308 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12309 Arg = G->getArg(); 12310 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12311 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12312 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12313 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12314 else if (ExclusiveLockFunctionAttr *ELF 12315 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12316 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12317 else if (SharedLockFunctionAttr *SLF 12318 = dyn_cast<SharedLockFunctionAttr>(*A)) 12319 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12320 else if (ExclusiveTrylockFunctionAttr *ETLF 12321 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12322 Arg = ETLF->getSuccessValue(); 12323 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12324 } else if (SharedTrylockFunctionAttr *STLF 12325 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12326 Arg = STLF->getSuccessValue(); 12327 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12328 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12329 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12330 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12331 Arg = LR->getArg(); 12332 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12333 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12334 else if (ExclusiveLocksRequiredAttr *ELR 12335 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12336 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12337 else if (SharedLocksRequiredAttr *SLR 12338 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12339 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12340 12341 if (Arg && !Finder.TraverseStmt(Arg)) 12342 return true; 12343 12344 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12345 if (!Finder.TraverseStmt(Args[I])) 12346 return true; 12347 } 12348 } 12349 12350 return false; 12351} 12352 12353void 12354Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12355 ArrayRef<ParsedType> DynamicExceptions, 12356 ArrayRef<SourceRange> DynamicExceptionRanges, 12357 Expr *NoexceptExpr, 12358 SmallVectorImpl<QualType> &Exceptions, 12359 FunctionProtoType::ExtProtoInfo &EPI) { 12360 Exceptions.clear(); 12361 EPI.ExceptionSpecType = EST; 12362 if (EST == EST_Dynamic) { 12363 Exceptions.reserve(DynamicExceptions.size()); 12364 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12365 // FIXME: Preserve type source info. 12366 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12367 12368 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12369 collectUnexpandedParameterPacks(ET, Unexpanded); 12370 if (!Unexpanded.empty()) { 12371 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12372 UPPC_ExceptionType, 12373 Unexpanded); 12374 continue; 12375 } 12376 12377 // Check that the type is valid for an exception spec, and 12378 // drop it if not. 12379 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12380 Exceptions.push_back(ET); 12381 } 12382 EPI.NumExceptions = Exceptions.size(); 12383 EPI.Exceptions = Exceptions.data(); 12384 return; 12385 } 12386 12387 if (EST == EST_ComputedNoexcept) { 12388 // If an error occurred, there's no expression here. 12389 if (NoexceptExpr) { 12390 assert((NoexceptExpr->isTypeDependent() || 12391 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12392 Context.BoolTy) && 12393 "Parser should have made sure that the expression is boolean"); 12394 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12395 EPI.ExceptionSpecType = EST_BasicNoexcept; 12396 return; 12397 } 12398 12399 if (!NoexceptExpr->isValueDependent()) 12400 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12401 diag::err_noexcept_needs_constant_expression, 12402 /*AllowFold*/ false).take(); 12403 EPI.NoexceptExpr = NoexceptExpr; 12404 } 12405 return; 12406 } 12407} 12408 12409/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12410Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12411 // Implicitly declared functions (e.g. copy constructors) are 12412 // __host__ __device__ 12413 if (D->isImplicit()) 12414 return CFT_HostDevice; 12415 12416 if (D->hasAttr<CUDAGlobalAttr>()) 12417 return CFT_Global; 12418 12419 if (D->hasAttr<CUDADeviceAttr>()) { 12420 if (D->hasAttr<CUDAHostAttr>()) 12421 return CFT_HostDevice; 12422 else 12423 return CFT_Device; 12424 } 12425 12426 return CFT_Host; 12427} 12428 12429bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12430 CUDAFunctionTarget CalleeTarget) { 12431 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12432 // Callable from the device only." 12433 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12434 return true; 12435 12436 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12437 // Callable from the host only." 12438 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12439 // Callable from the host only." 12440 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12441 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12442 return true; 12443 12444 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12445 return true; 12446 12447 return false; 12448} 12449 12450/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12451/// 12452MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12453 SourceLocation DeclStart, 12454 Declarator &D, Expr *BitWidth, 12455 InClassInitStyle InitStyle, 12456 AccessSpecifier AS, 12457 AttributeList *MSPropertyAttr) { 12458 IdentifierInfo *II = D.getIdentifier(); 12459 if (!II) { 12460 Diag(DeclStart, diag::err_anonymous_property); 12461 return NULL; 12462 } 12463 SourceLocation Loc = D.getIdentifierLoc(); 12464 12465 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12466 QualType T = TInfo->getType(); 12467 if (getLangOpts().CPlusPlus) { 12468 CheckExtraCXXDefaultArguments(D); 12469 12470 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12471 UPPC_DataMemberType)) { 12472 D.setInvalidType(); 12473 T = Context.IntTy; 12474 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12475 } 12476 } 12477 12478 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12479 12480 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12481 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12482 diag::err_invalid_thread) 12483 << DeclSpec::getSpecifierName(TSCS); 12484 12485 // Check to see if this name was declared as a member previously 12486 NamedDecl *PrevDecl = 0; 12487 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12488 LookupName(Previous, S); 12489 switch (Previous.getResultKind()) { 12490 case LookupResult::Found: 12491 case LookupResult::FoundUnresolvedValue: 12492 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12493 break; 12494 12495 case LookupResult::FoundOverloaded: 12496 PrevDecl = Previous.getRepresentativeDecl(); 12497 break; 12498 12499 case LookupResult::NotFound: 12500 case LookupResult::NotFoundInCurrentInstantiation: 12501 case LookupResult::Ambiguous: 12502 break; 12503 } 12504 12505 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12506 // Maybe we will complain about the shadowed template parameter. 12507 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12508 // Just pretend that we didn't see the previous declaration. 12509 PrevDecl = 0; 12510 } 12511 12512 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12513 PrevDecl = 0; 12514 12515 SourceLocation TSSL = D.getLocStart(); 12516 MSPropertyDecl *NewPD; 12517 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12518 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12519 II, T, TInfo, TSSL, 12520 Data.GetterId, Data.SetterId); 12521 ProcessDeclAttributes(TUScope, NewPD, D); 12522 NewPD->setAccess(AS); 12523 12524 if (NewPD->isInvalidDecl()) 12525 Record->setInvalidDecl(); 12526 12527 if (D.getDeclSpec().isModulePrivateSpecified()) 12528 NewPD->setModulePrivate(); 12529 12530 if (NewPD->isInvalidDecl() && PrevDecl) { 12531 // Don't introduce NewFD into scope; there's already something 12532 // with the same name in the same scope. 12533 } else if (II) { 12534 PushOnScopeChains(NewPD, S); 12535 } else 12536 Record->addDecl(NewPD); 12537 12538 return NewPD; 12539} 12540