SemaDeclCXX.cpp revision 8150da3796300bdc876775e1782331f0e43d2d94
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 407/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 408/// function, once we already know that they have the same 409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 410/// error, false otherwise. 411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 412 Scope *S) { 413 bool Invalid = false; 414 415 // C++ [dcl.fct.default]p4: 416 // For non-template functions, default arguments can be added in 417 // later declarations of a function in the same 418 // scope. Declarations in different scopes have completely 419 // distinct sets of default arguments. That is, declarations in 420 // inner scopes do not acquire default arguments from 421 // declarations in outer scopes, and vice versa. In a given 422 // function declaration, all parameters subsequent to a 423 // parameter with a default argument shall have default 424 // arguments supplied in this or previous declarations. A 425 // default argument shall not be redefined by a later 426 // declaration (not even to the same value). 427 // 428 // C++ [dcl.fct.default]p6: 429 // Except for member functions of class templates, the default arguments 430 // in a member function definition that appears outside of the class 431 // definition are added to the set of default arguments provided by the 432 // member function declaration in the class definition. 433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 434 ParmVarDecl *OldParam = Old->getParamDecl(p); 435 ParmVarDecl *NewParam = New->getParamDecl(p); 436 437 bool OldParamHasDfl = OldParam->hasDefaultArg(); 438 bool NewParamHasDfl = NewParam->hasDefaultArg(); 439 440 NamedDecl *ND = Old; 441 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 442 // Ignore default parameters of old decl if they are not in 443 // the same scope. 444 OldParamHasDfl = false; 445 446 if (OldParamHasDfl && NewParamHasDfl) { 447 448 unsigned DiagDefaultParamID = 449 diag::err_param_default_argument_redefinition; 450 451 // MSVC accepts that default parameters be redefined for member functions 452 // of template class. The new default parameter's value is ignored. 453 Invalid = true; 454 if (getLangOpts().MicrosoftExt) { 455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 456 if (MD && MD->getParent()->getDescribedClassTemplate()) { 457 // Merge the old default argument into the new parameter. 458 NewParam->setHasInheritedDefaultArg(); 459 if (OldParam->hasUninstantiatedDefaultArg()) 460 NewParam->setUninstantiatedDefaultArg( 461 OldParam->getUninstantiatedDefaultArg()); 462 else 463 NewParam->setDefaultArg(OldParam->getInit()); 464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 465 Invalid = false; 466 } 467 } 468 469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 470 // hint here. Alternatively, we could walk the type-source information 471 // for NewParam to find the last source location in the type... but it 472 // isn't worth the effort right now. This is the kind of test case that 473 // is hard to get right: 474 // int f(int); 475 // void g(int (*fp)(int) = f); 476 // void g(int (*fp)(int) = &f); 477 Diag(NewParam->getLocation(), DiagDefaultParamID) 478 << NewParam->getDefaultArgRange(); 479 480 // Look for the function declaration where the default argument was 481 // actually written, which may be a declaration prior to Old. 482 for (FunctionDecl *Older = Old->getPreviousDecl(); 483 Older; Older = Older->getPreviousDecl()) { 484 if (!Older->getParamDecl(p)->hasDefaultArg()) 485 break; 486 487 OldParam = Older->getParamDecl(p); 488 } 489 490 Diag(OldParam->getLocation(), diag::note_previous_definition) 491 << OldParam->getDefaultArgRange(); 492 } else if (OldParamHasDfl) { 493 // Merge the old default argument into the new parameter. 494 // It's important to use getInit() here; getDefaultArg() 495 // strips off any top-level ExprWithCleanups. 496 NewParam->setHasInheritedDefaultArg(); 497 if (OldParam->hasUninstantiatedDefaultArg()) 498 NewParam->setUninstantiatedDefaultArg( 499 OldParam->getUninstantiatedDefaultArg()); 500 else 501 NewParam->setDefaultArg(OldParam->getInit()); 502 } else if (NewParamHasDfl) { 503 if (New->getDescribedFunctionTemplate()) { 504 // Paragraph 4, quoted above, only applies to non-template functions. 505 Diag(NewParam->getLocation(), 506 diag::err_param_default_argument_template_redecl) 507 << NewParam->getDefaultArgRange(); 508 Diag(Old->getLocation(), diag::note_template_prev_declaration) 509 << false; 510 } else if (New->getTemplateSpecializationKind() 511 != TSK_ImplicitInstantiation && 512 New->getTemplateSpecializationKind() != TSK_Undeclared) { 513 // C++ [temp.expr.spec]p21: 514 // Default function arguments shall not be specified in a declaration 515 // or a definition for one of the following explicit specializations: 516 // - the explicit specialization of a function template; 517 // - the explicit specialization of a member function template; 518 // - the explicit specialization of a member function of a class 519 // template where the class template specialization to which the 520 // member function specialization belongs is implicitly 521 // instantiated. 522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 524 << New->getDeclName() 525 << NewParam->getDefaultArgRange(); 526 } else if (New->getDeclContext()->isDependentContext()) { 527 // C++ [dcl.fct.default]p6 (DR217): 528 // Default arguments for a member function of a class template shall 529 // be specified on the initial declaration of the member function 530 // within the class template. 531 // 532 // Reading the tea leaves a bit in DR217 and its reference to DR205 533 // leads me to the conclusion that one cannot add default function 534 // arguments for an out-of-line definition of a member function of a 535 // dependent type. 536 int WhichKind = 2; 537 if (CXXRecordDecl *Record 538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 539 if (Record->getDescribedClassTemplate()) 540 WhichKind = 0; 541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 542 WhichKind = 1; 543 else 544 WhichKind = 2; 545 } 546 547 Diag(NewParam->getLocation(), 548 diag::err_param_default_argument_member_template_redecl) 549 << WhichKind 550 << NewParam->getDefaultArgRange(); 551 } 552 } 553 } 554 555 // DR1344: If a default argument is added outside a class definition and that 556 // default argument makes the function a special member function, the program 557 // is ill-formed. This can only happen for constructors. 558 if (isa<CXXConstructorDecl>(New) && 559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 562 if (NewSM != OldSM) { 563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 564 assert(NewParam->hasDefaultArg()); 565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 566 << NewParam->getDefaultArgRange() << NewSM; 567 Diag(Old->getLocation(), diag::note_previous_declaration); 568 } 569 } 570 571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 572 // template has a constexpr specifier then all its declarations shall 573 // contain the constexpr specifier. 574 if (New->isConstexpr() != Old->isConstexpr()) { 575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 576 << New << New->isConstexpr(); 577 Diag(Old->getLocation(), diag::note_previous_declaration); 578 Invalid = true; 579 } 580 581 if (CheckEquivalentExceptionSpec(Old, New)) 582 Invalid = true; 583 584 return Invalid; 585} 586 587/// \brief Merge the exception specifications of two variable declarations. 588/// 589/// This is called when there's a redeclaration of a VarDecl. The function 590/// checks if the redeclaration might have an exception specification and 591/// validates compatibility and merges the specs if necessary. 592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 593 // Shortcut if exceptions are disabled. 594 if (!getLangOpts().CXXExceptions) 595 return; 596 597 assert(Context.hasSameType(New->getType(), Old->getType()) && 598 "Should only be called if types are otherwise the same."); 599 600 QualType NewType = New->getType(); 601 QualType OldType = Old->getType(); 602 603 // We're only interested in pointers and references to functions, as well 604 // as pointers to member functions. 605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 606 NewType = R->getPointeeType(); 607 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 608 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 609 NewType = P->getPointeeType(); 610 OldType = OldType->getAs<PointerType>()->getPointeeType(); 611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 612 NewType = M->getPointeeType(); 613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 614 } 615 616 if (!NewType->isFunctionProtoType()) 617 return; 618 619 // There's lots of special cases for functions. For function pointers, system 620 // libraries are hopefully not as broken so that we don't need these 621 // workarounds. 622 if (CheckEquivalentExceptionSpec( 623 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 624 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 625 New->setInvalidDecl(); 626 } 627} 628 629/// CheckCXXDefaultArguments - Verify that the default arguments for a 630/// function declaration are well-formed according to C++ 631/// [dcl.fct.default]. 632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 633 unsigned NumParams = FD->getNumParams(); 634 unsigned p; 635 636 // Find first parameter with a default argument 637 for (p = 0; p < NumParams; ++p) { 638 ParmVarDecl *Param = FD->getParamDecl(p); 639 if (Param->hasDefaultArg()) 640 break; 641 } 642 643 // C++ [dcl.fct.default]p4: 644 // In a given function declaration, all parameters 645 // subsequent to a parameter with a default argument shall 646 // have default arguments supplied in this or previous 647 // declarations. A default argument shall not be redefined 648 // by a later declaration (not even to the same value). 649 unsigned LastMissingDefaultArg = 0; 650 for (; p < NumParams; ++p) { 651 ParmVarDecl *Param = FD->getParamDecl(p); 652 if (!Param->hasDefaultArg()) { 653 if (Param->isInvalidDecl()) 654 /* We already complained about this parameter. */; 655 else if (Param->getIdentifier()) 656 Diag(Param->getLocation(), 657 diag::err_param_default_argument_missing_name) 658 << Param->getIdentifier(); 659 else 660 Diag(Param->getLocation(), 661 diag::err_param_default_argument_missing); 662 663 LastMissingDefaultArg = p; 664 } 665 } 666 667 if (LastMissingDefaultArg > 0) { 668 // Some default arguments were missing. Clear out all of the 669 // default arguments up to (and including) the last missing 670 // default argument, so that we leave the function parameters 671 // in a semantically valid state. 672 for (p = 0; p <= LastMissingDefaultArg; ++p) { 673 ParmVarDecl *Param = FD->getParamDecl(p); 674 if (Param->hasDefaultArg()) { 675 Param->setDefaultArg(0); 676 } 677 } 678 } 679} 680 681// CheckConstexprParameterTypes - Check whether a function's parameter types 682// are all literal types. If so, return true. If not, produce a suitable 683// diagnostic and return false. 684static bool CheckConstexprParameterTypes(Sema &SemaRef, 685 const FunctionDecl *FD) { 686 unsigned ArgIndex = 0; 687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 691 SourceLocation ParamLoc = PD->getLocation(); 692 if (!(*i)->isDependentType() && 693 SemaRef.RequireLiteralType(ParamLoc, *i, 694 diag::err_constexpr_non_literal_param, 695 ArgIndex+1, PD->getSourceRange(), 696 isa<CXXConstructorDecl>(FD))) 697 return false; 698 } 699 return true; 700} 701 702/// \brief Get diagnostic %select index for tag kind for 703/// record diagnostic message. 704/// WARNING: Indexes apply to particular diagnostics only! 705/// 706/// \returns diagnostic %select index. 707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 708 switch (Tag) { 709 case TTK_Struct: return 0; 710 case TTK_Interface: return 1; 711 case TTK_Class: return 2; 712 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 713 } 714} 715 716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 717// the requirements of a constexpr function definition or a constexpr 718// constructor definition. If so, return true. If not, produce appropriate 719// diagnostics and return false. 720// 721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 724 if (MD && MD->isInstance()) { 725 // C++11 [dcl.constexpr]p4: 726 // The definition of a constexpr constructor shall satisfy the following 727 // constraints: 728 // - the class shall not have any virtual base classes; 729 const CXXRecordDecl *RD = MD->getParent(); 730 if (RD->getNumVBases()) { 731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 732 << isa<CXXConstructorDecl>(NewFD) 733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 735 E = RD->vbases_end(); I != E; ++I) 736 Diag(I->getLocStart(), 737 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 738 return false; 739 } 740 } 741 742 if (!isa<CXXConstructorDecl>(NewFD)) { 743 // C++11 [dcl.constexpr]p3: 744 // The definition of a constexpr function shall satisfy the following 745 // constraints: 746 // - it shall not be virtual; 747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 748 if (Method && Method->isVirtual()) { 749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 750 751 // If it's not obvious why this function is virtual, find an overridden 752 // function which uses the 'virtual' keyword. 753 const CXXMethodDecl *WrittenVirtual = Method; 754 while (!WrittenVirtual->isVirtualAsWritten()) 755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 756 if (WrittenVirtual != Method) 757 Diag(WrittenVirtual->getLocation(), 758 diag::note_overridden_virtual_function); 759 return false; 760 } 761 762 // - its return type shall be a literal type; 763 QualType RT = NewFD->getResultType(); 764 if (!RT->isDependentType() && 765 RequireLiteralType(NewFD->getLocation(), RT, 766 diag::err_constexpr_non_literal_return)) 767 return false; 768 } 769 770 // - each of its parameter types shall be a literal type; 771 if (!CheckConstexprParameterTypes(*this, NewFD)) 772 return false; 773 774 return true; 775} 776 777/// Check the given declaration statement is legal within a constexpr function 778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 779/// 780/// \return true if the body is OK (maybe only as an extension), false if we 781/// have diagnosed a problem. 782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 783 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 784 // C++11 [dcl.constexpr]p3 and p4: 785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 786 // contain only 787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 789 switch ((*DclIt)->getKind()) { 790 case Decl::StaticAssert: 791 case Decl::Using: 792 case Decl::UsingShadow: 793 case Decl::UsingDirective: 794 case Decl::UnresolvedUsingTypename: 795 case Decl::UnresolvedUsingValue: 796 // - static_assert-declarations 797 // - using-declarations, 798 // - using-directives, 799 continue; 800 801 case Decl::Typedef: 802 case Decl::TypeAlias: { 803 // - typedef declarations and alias-declarations that do not define 804 // classes or enumerations, 805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 806 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 807 // Don't allow variably-modified types in constexpr functions. 808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 810 << TL.getSourceRange() << TL.getType() 811 << isa<CXXConstructorDecl>(Dcl); 812 return false; 813 } 814 continue; 815 } 816 817 case Decl::Enum: 818 case Decl::CXXRecord: 819 // C++1y allows types to be defined, not just declared. 820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 821 SemaRef.Diag(DS->getLocStart(), 822 SemaRef.getLangOpts().CPlusPlus1y 823 ? diag::warn_cxx11_compat_constexpr_type_definition 824 : diag::ext_constexpr_type_definition) 825 << isa<CXXConstructorDecl>(Dcl); 826 continue; 827 828 case Decl::EnumConstant: 829 case Decl::IndirectField: 830 case Decl::ParmVar: 831 // These can only appear with other declarations which are banned in 832 // C++11 and permitted in C++1y, so ignore them. 833 continue; 834 835 case Decl::Var: { 836 // C++1y [dcl.constexpr]p3 allows anything except: 837 // a definition of a variable of non-literal type or of static or 838 // thread storage duration or for which no initialization is performed. 839 VarDecl *VD = cast<VarDecl>(*DclIt); 840 if (VD->isThisDeclarationADefinition()) { 841 if (VD->isStaticLocal()) { 842 SemaRef.Diag(VD->getLocation(), 843 diag::err_constexpr_local_var_static) 844 << isa<CXXConstructorDecl>(Dcl) 845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 846 return false; 847 } 848 if (!VD->getType()->isDependentType() && 849 SemaRef.RequireLiteralType( 850 VD->getLocation(), VD->getType(), 851 diag::err_constexpr_local_var_non_literal_type, 852 isa<CXXConstructorDecl>(Dcl))) 853 return false; 854 if (!VD->hasInit()) { 855 SemaRef.Diag(VD->getLocation(), 856 diag::err_constexpr_local_var_no_init) 857 << isa<CXXConstructorDecl>(Dcl); 858 return false; 859 } 860 } 861 SemaRef.Diag(VD->getLocation(), 862 SemaRef.getLangOpts().CPlusPlus1y 863 ? diag::warn_cxx11_compat_constexpr_local_var 864 : diag::ext_constexpr_local_var) 865 << isa<CXXConstructorDecl>(Dcl); 866 continue; 867 } 868 869 case Decl::NamespaceAlias: 870 case Decl::Function: 871 // These are disallowed in C++11 and permitted in C++1y. Allow them 872 // everywhere as an extension. 873 if (!Cxx1yLoc.isValid()) 874 Cxx1yLoc = DS->getLocStart(); 875 continue; 876 877 default: 878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 879 << isa<CXXConstructorDecl>(Dcl); 880 return false; 881 } 882 } 883 884 return true; 885} 886 887/// Check that the given field is initialized within a constexpr constructor. 888/// 889/// \param Dcl The constexpr constructor being checked. 890/// \param Field The field being checked. This may be a member of an anonymous 891/// struct or union nested within the class being checked. 892/// \param Inits All declarations, including anonymous struct/union members and 893/// indirect members, for which any initialization was provided. 894/// \param Diagnosed Set to true if an error is produced. 895static void CheckConstexprCtorInitializer(Sema &SemaRef, 896 const FunctionDecl *Dcl, 897 FieldDecl *Field, 898 llvm::SmallSet<Decl*, 16> &Inits, 899 bool &Diagnosed) { 900 if (Field->isUnnamedBitfield()) 901 return; 902 903 if (Field->isAnonymousStructOrUnion() && 904 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 905 return; 906 907 if (!Inits.count(Field)) { 908 if (!Diagnosed) { 909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 910 Diagnosed = true; 911 } 912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 913 } else if (Field->isAnonymousStructOrUnion()) { 914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 916 I != E; ++I) 917 // If an anonymous union contains an anonymous struct of which any member 918 // is initialized, all members must be initialized. 919 if (!RD->isUnion() || Inits.count(*I)) 920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 921 } 922} 923 924/// Check the provided statement is allowed in a constexpr function 925/// definition. 926static bool 927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts, 929 SourceLocation &Cxx1yLoc) { 930 // - its function-body shall be [...] a compound-statement that contains only 931 switch (S->getStmtClass()) { 932 case Stmt::NullStmtClass: 933 // - null statements, 934 return true; 935 936 case Stmt::DeclStmtClass: 937 // - static_assert-declarations 938 // - using-declarations, 939 // - using-directives, 940 // - typedef declarations and alias-declarations that do not define 941 // classes or enumerations, 942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 943 return false; 944 return true; 945 946 case Stmt::ReturnStmtClass: 947 // - and exactly one return statement; 948 if (isa<CXXConstructorDecl>(Dcl)) { 949 // C++1y allows return statements in constexpr constructors. 950 if (!Cxx1yLoc.isValid()) 951 Cxx1yLoc = S->getLocStart(); 952 return true; 953 } 954 955 ReturnStmts.push_back(S->getLocStart()); 956 return true; 957 958 case Stmt::CompoundStmtClass: { 959 // C++1y allows compound-statements. 960 if (!Cxx1yLoc.isValid()) 961 Cxx1yLoc = S->getLocStart(); 962 963 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 967 Cxx1yLoc)) 968 return false; 969 } 970 return true; 971 } 972 973 case Stmt::AttributedStmtClass: 974 if (!Cxx1yLoc.isValid()) 975 Cxx1yLoc = S->getLocStart(); 976 return true; 977 978 case Stmt::IfStmtClass: { 979 // C++1y allows if-statements. 980 if (!Cxx1yLoc.isValid()) 981 Cxx1yLoc = S->getLocStart(); 982 983 IfStmt *If = cast<IfStmt>(S); 984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 985 Cxx1yLoc)) 986 return false; 987 if (If->getElse() && 988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 989 Cxx1yLoc)) 990 return false; 991 return true; 992 } 993 994 case Stmt::WhileStmtClass: 995 case Stmt::DoStmtClass: 996 case Stmt::ForStmtClass: 997 case Stmt::CXXForRangeStmtClass: 998 case Stmt::ContinueStmtClass: 999 // C++1y allows all of these. We don't allow them as extensions in C++11, 1000 // because they don't make sense without variable mutation. 1001 if (!SemaRef.getLangOpts().CPlusPlus1y) 1002 break; 1003 if (!Cxx1yLoc.isValid()) 1004 Cxx1yLoc = S->getLocStart(); 1005 for (Stmt::child_range Children = S->children(); Children; ++Children) 1006 if (*Children && 1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1008 Cxx1yLoc)) 1009 return false; 1010 return true; 1011 1012 case Stmt::SwitchStmtClass: 1013 case Stmt::CaseStmtClass: 1014 case Stmt::DefaultStmtClass: 1015 case Stmt::BreakStmtClass: 1016 // C++1y allows switch-statements, and since they don't need variable 1017 // mutation, we can reasonably allow them in C++11 as an extension. 1018 if (!Cxx1yLoc.isValid()) 1019 Cxx1yLoc = S->getLocStart(); 1020 for (Stmt::child_range Children = S->children(); Children; ++Children) 1021 if (*Children && 1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1023 Cxx1yLoc)) 1024 return false; 1025 return true; 1026 1027 default: 1028 if (!isa<Expr>(S)) 1029 break; 1030 1031 // C++1y allows expression-statements. 1032 if (!Cxx1yLoc.isValid()) 1033 Cxx1yLoc = S->getLocStart(); 1034 return true; 1035 } 1036 1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1038 << isa<CXXConstructorDecl>(Dcl); 1039 return false; 1040} 1041 1042/// Check the body for the given constexpr function declaration only contains 1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1044/// 1045/// \return true if the body is OK, false if we have diagnosed a problem. 1046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1047 if (isa<CXXTryStmt>(Body)) { 1048 // C++11 [dcl.constexpr]p3: 1049 // The definition of a constexpr function shall satisfy the following 1050 // constraints: [...] 1051 // - its function-body shall be = delete, = default, or a 1052 // compound-statement 1053 // 1054 // C++11 [dcl.constexpr]p4: 1055 // In the definition of a constexpr constructor, [...] 1056 // - its function-body shall not be a function-try-block; 1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1058 << isa<CXXConstructorDecl>(Dcl); 1059 return false; 1060 } 1061 1062 SmallVector<SourceLocation, 4> ReturnStmts; 1063 1064 // - its function-body shall be [...] a compound-statement that contains only 1065 // [... list of cases ...] 1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1067 SourceLocation Cxx1yLoc; 1068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1071 return false; 1072 } 1073 1074 if (Cxx1yLoc.isValid()) 1075 Diag(Cxx1yLoc, 1076 getLangOpts().CPlusPlus1y 1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1078 : diag::ext_constexpr_body_invalid_stmt) 1079 << isa<CXXConstructorDecl>(Dcl); 1080 1081 if (const CXXConstructorDecl *Constructor 1082 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1083 const CXXRecordDecl *RD = Constructor->getParent(); 1084 // DR1359: 1085 // - every non-variant non-static data member and base class sub-object 1086 // shall be initialized; 1087 // - if the class is a non-empty union, or for each non-empty anonymous 1088 // union member of a non-union class, exactly one non-static data member 1089 // shall be initialized; 1090 if (RD->isUnion()) { 1091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1093 return false; 1094 } 1095 } else if (!Constructor->isDependentContext() && 1096 !Constructor->isDelegatingConstructor()) { 1097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1098 1099 // Skip detailed checking if we have enough initializers, and we would 1100 // allow at most one initializer per member. 1101 bool AnyAnonStructUnionMembers = false; 1102 unsigned Fields = 0; 1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1104 E = RD->field_end(); I != E; ++I, ++Fields) { 1105 if (I->isAnonymousStructOrUnion()) { 1106 AnyAnonStructUnionMembers = true; 1107 break; 1108 } 1109 } 1110 if (AnyAnonStructUnionMembers || 1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1112 // Check initialization of non-static data members. Base classes are 1113 // always initialized so do not need to be checked. Dependent bases 1114 // might not have initializers in the member initializer list. 1115 llvm::SmallSet<Decl*, 16> Inits; 1116 for (CXXConstructorDecl::init_const_iterator 1117 I = Constructor->init_begin(), E = Constructor->init_end(); 1118 I != E; ++I) { 1119 if (FieldDecl *FD = (*I)->getMember()) 1120 Inits.insert(FD); 1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1122 Inits.insert(ID->chain_begin(), ID->chain_end()); 1123 } 1124 1125 bool Diagnosed = false; 1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1127 E = RD->field_end(); I != E; ++I) 1128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1129 if (Diagnosed) 1130 return false; 1131 } 1132 } 1133 } else { 1134 if (ReturnStmts.empty()) { 1135 // C++1y doesn't require constexpr functions to contain a 'return' 1136 // statement. We still do, unless the return type is void, because 1137 // otherwise if there's no return statement, the function cannot 1138 // be used in a core constant expression. 1139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1140 Diag(Dcl->getLocation(), 1141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1142 : diag::err_constexpr_body_no_return); 1143 return OK; 1144 } 1145 if (ReturnStmts.size() > 1) { 1146 Diag(ReturnStmts.back(), 1147 getLangOpts().CPlusPlus1y 1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1149 : diag::ext_constexpr_body_multiple_return); 1150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1152 } 1153 } 1154 1155 // C++11 [dcl.constexpr]p5: 1156 // if no function argument values exist such that the function invocation 1157 // substitution would produce a constant expression, the program is 1158 // ill-formed; no diagnostic required. 1159 // C++11 [dcl.constexpr]p3: 1160 // - every constructor call and implicit conversion used in initializing the 1161 // return value shall be one of those allowed in a constant expression. 1162 // C++11 [dcl.constexpr]p4: 1163 // - every constructor involved in initializing non-static data members and 1164 // base class sub-objects shall be a constexpr constructor. 1165 SmallVector<PartialDiagnosticAt, 8> Diags; 1166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1168 << isa<CXXConstructorDecl>(Dcl); 1169 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1170 Diag(Diags[I].first, Diags[I].second); 1171 // Don't return false here: we allow this for compatibility in 1172 // system headers. 1173 } 1174 1175 return true; 1176} 1177 1178/// isCurrentClassName - Determine whether the identifier II is the 1179/// name of the class type currently being defined. In the case of 1180/// nested classes, this will only return true if II is the name of 1181/// the innermost class. 1182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1183 const CXXScopeSpec *SS) { 1184 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1185 1186 CXXRecordDecl *CurDecl; 1187 if (SS && SS->isSet() && !SS->isInvalid()) { 1188 DeclContext *DC = computeDeclContext(*SS, true); 1189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1190 } else 1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1192 1193 if (CurDecl && CurDecl->getIdentifier()) 1194 return &II == CurDecl->getIdentifier(); 1195 else 1196 return false; 1197} 1198 1199/// \brief Determine whether the given class is a base class of the given 1200/// class, including looking at dependent bases. 1201static bool findCircularInheritance(const CXXRecordDecl *Class, 1202 const CXXRecordDecl *Current) { 1203 SmallVector<const CXXRecordDecl*, 8> Queue; 1204 1205 Class = Class->getCanonicalDecl(); 1206 while (true) { 1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1208 E = Current->bases_end(); 1209 I != E; ++I) { 1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1211 if (!Base) 1212 continue; 1213 1214 Base = Base->getDefinition(); 1215 if (!Base) 1216 continue; 1217 1218 if (Base->getCanonicalDecl() == Class) 1219 return true; 1220 1221 Queue.push_back(Base); 1222 } 1223 1224 if (Queue.empty()) 1225 return false; 1226 1227 Current = Queue.back(); 1228 Queue.pop_back(); 1229 } 1230 1231 return false; 1232} 1233 1234/// \brief Check the validity of a C++ base class specifier. 1235/// 1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1237/// and returns NULL otherwise. 1238CXXBaseSpecifier * 1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1240 SourceRange SpecifierRange, 1241 bool Virtual, AccessSpecifier Access, 1242 TypeSourceInfo *TInfo, 1243 SourceLocation EllipsisLoc) { 1244 QualType BaseType = TInfo->getType(); 1245 1246 // C++ [class.union]p1: 1247 // A union shall not have base classes. 1248 if (Class->isUnion()) { 1249 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1250 << SpecifierRange; 1251 return 0; 1252 } 1253 1254 if (EllipsisLoc.isValid() && 1255 !TInfo->getType()->containsUnexpandedParameterPack()) { 1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1257 << TInfo->getTypeLoc().getSourceRange(); 1258 EllipsisLoc = SourceLocation(); 1259 } 1260 1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1262 1263 if (BaseType->isDependentType()) { 1264 // Make sure that we don't have circular inheritance among our dependent 1265 // bases. For non-dependent bases, the check for completeness below handles 1266 // this. 1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1269 ((BaseDecl = BaseDecl->getDefinition()) && 1270 findCircularInheritance(Class, BaseDecl))) { 1271 Diag(BaseLoc, diag::err_circular_inheritance) 1272 << BaseType << Context.getTypeDeclType(Class); 1273 1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1276 << BaseType; 1277 1278 return 0; 1279 } 1280 } 1281 1282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1283 Class->getTagKind() == TTK_Class, 1284 Access, TInfo, EllipsisLoc); 1285 } 1286 1287 // Base specifiers must be record types. 1288 if (!BaseType->isRecordType()) { 1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1290 return 0; 1291 } 1292 1293 // C++ [class.union]p1: 1294 // A union shall not be used as a base class. 1295 if (BaseType->isUnionType()) { 1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1297 return 0; 1298 } 1299 1300 // C++ [class.derived]p2: 1301 // The class-name in a base-specifier shall not be an incompletely 1302 // defined class. 1303 if (RequireCompleteType(BaseLoc, BaseType, 1304 diag::err_incomplete_base_class, SpecifierRange)) { 1305 Class->setInvalidDecl(); 1306 return 0; 1307 } 1308 1309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1311 assert(BaseDecl && "Record type has no declaration"); 1312 BaseDecl = BaseDecl->getDefinition(); 1313 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1314 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1315 assert(CXXBaseDecl && "Base type is not a C++ type"); 1316 1317 // C++ [class]p3: 1318 // If a class is marked final and it appears as a base-type-specifier in 1319 // base-clause, the program is ill-formed. 1320 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1322 << CXXBaseDecl->getDeclName(); 1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1324 << CXXBaseDecl->getDeclName(); 1325 return 0; 1326 } 1327 1328 if (BaseDecl->isInvalidDecl()) 1329 Class->setInvalidDecl(); 1330 1331 // Create the base specifier. 1332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1333 Class->getTagKind() == TTK_Class, 1334 Access, TInfo, EllipsisLoc); 1335} 1336 1337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1338/// one entry in the base class list of a class specifier, for 1339/// example: 1340/// class foo : public bar, virtual private baz { 1341/// 'public bar' and 'virtual private baz' are each base-specifiers. 1342BaseResult 1343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1344 ParsedAttributes &Attributes, 1345 bool Virtual, AccessSpecifier Access, 1346 ParsedType basetype, SourceLocation BaseLoc, 1347 SourceLocation EllipsisLoc) { 1348 if (!classdecl) 1349 return true; 1350 1351 AdjustDeclIfTemplate(classdecl); 1352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1353 if (!Class) 1354 return true; 1355 1356 // We do not support any C++11 attributes on base-specifiers yet. 1357 // Diagnose any attributes we see. 1358 if (!Attributes.empty()) { 1359 for (AttributeList *Attr = Attributes.getList(); Attr; 1360 Attr = Attr->getNext()) { 1361 if (Attr->isInvalid() || 1362 Attr->getKind() == AttributeList::IgnoredAttribute) 1363 continue; 1364 Diag(Attr->getLoc(), 1365 Attr->getKind() == AttributeList::UnknownAttribute 1366 ? diag::warn_unknown_attribute_ignored 1367 : diag::err_base_specifier_attribute) 1368 << Attr->getName(); 1369 } 1370 } 1371 1372 TypeSourceInfo *TInfo = 0; 1373 GetTypeFromParser(basetype, &TInfo); 1374 1375 if (EllipsisLoc.isInvalid() && 1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1377 UPPC_BaseType)) 1378 return true; 1379 1380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1381 Virtual, Access, TInfo, 1382 EllipsisLoc)) 1383 return BaseSpec; 1384 else 1385 Class->setInvalidDecl(); 1386 1387 return true; 1388} 1389 1390/// \brief Performs the actual work of attaching the given base class 1391/// specifiers to a C++ class. 1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1393 unsigned NumBases) { 1394 if (NumBases == 0) 1395 return false; 1396 1397 // Used to keep track of which base types we have already seen, so 1398 // that we can properly diagnose redundant direct base types. Note 1399 // that the key is always the unqualified canonical type of the base 1400 // class. 1401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1402 1403 // Copy non-redundant base specifiers into permanent storage. 1404 unsigned NumGoodBases = 0; 1405 bool Invalid = false; 1406 for (unsigned idx = 0; idx < NumBases; ++idx) { 1407 QualType NewBaseType 1408 = Context.getCanonicalType(Bases[idx]->getType()); 1409 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1410 1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1412 if (KnownBase) { 1413 // C++ [class.mi]p3: 1414 // A class shall not be specified as a direct base class of a 1415 // derived class more than once. 1416 Diag(Bases[idx]->getLocStart(), 1417 diag::err_duplicate_base_class) 1418 << KnownBase->getType() 1419 << Bases[idx]->getSourceRange(); 1420 1421 // Delete the duplicate base class specifier; we're going to 1422 // overwrite its pointer later. 1423 Context.Deallocate(Bases[idx]); 1424 1425 Invalid = true; 1426 } else { 1427 // Okay, add this new base class. 1428 KnownBase = Bases[idx]; 1429 Bases[NumGoodBases++] = Bases[idx]; 1430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1432 if (Class->isInterface() && 1433 (!RD->isInterface() || 1434 KnownBase->getAccessSpecifier() != AS_public)) { 1435 // The Microsoft extension __interface does not permit bases that 1436 // are not themselves public interfaces. 1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1439 << RD->getSourceRange(); 1440 Invalid = true; 1441 } 1442 if (RD->hasAttr<WeakAttr>()) 1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1444 } 1445 } 1446 } 1447 1448 // Attach the remaining base class specifiers to the derived class. 1449 Class->setBases(Bases, NumGoodBases); 1450 1451 // Delete the remaining (good) base class specifiers, since their 1452 // data has been copied into the CXXRecordDecl. 1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1454 Context.Deallocate(Bases[idx]); 1455 1456 return Invalid; 1457} 1458 1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1460/// class, after checking whether there are any duplicate base 1461/// classes. 1462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1463 unsigned NumBases) { 1464 if (!ClassDecl || !Bases || !NumBases) 1465 return; 1466 1467 AdjustDeclIfTemplate(ClassDecl); 1468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1469 (CXXBaseSpecifier**)(Bases), NumBases); 1470} 1471 1472/// \brief Determine whether the type \p Derived is a C++ class that is 1473/// derived from the type \p Base. 1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1475 if (!getLangOpts().CPlusPlus) 1476 return false; 1477 1478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1479 if (!DerivedRD) 1480 return false; 1481 1482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1483 if (!BaseRD) 1484 return false; 1485 1486 // If either the base or the derived type is invalid, don't try to 1487 // check whether one is derived from the other. 1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1489 return false; 1490 1491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1493} 1494 1495/// \brief Determine whether the type \p Derived is a C++ class that is 1496/// derived from the type \p Base. 1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1498 if (!getLangOpts().CPlusPlus) 1499 return false; 1500 1501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1502 if (!DerivedRD) 1503 return false; 1504 1505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1506 if (!BaseRD) 1507 return false; 1508 1509 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1510} 1511 1512void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1513 CXXCastPath &BasePathArray) { 1514 assert(BasePathArray.empty() && "Base path array must be empty!"); 1515 assert(Paths.isRecordingPaths() && "Must record paths!"); 1516 1517 const CXXBasePath &Path = Paths.front(); 1518 1519 // We first go backward and check if we have a virtual base. 1520 // FIXME: It would be better if CXXBasePath had the base specifier for 1521 // the nearest virtual base. 1522 unsigned Start = 0; 1523 for (unsigned I = Path.size(); I != 0; --I) { 1524 if (Path[I - 1].Base->isVirtual()) { 1525 Start = I - 1; 1526 break; 1527 } 1528 } 1529 1530 // Now add all bases. 1531 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1533} 1534 1535/// \brief Determine whether the given base path includes a virtual 1536/// base class. 1537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1538 for (CXXCastPath::const_iterator B = BasePath.begin(), 1539 BEnd = BasePath.end(); 1540 B != BEnd; ++B) 1541 if ((*B)->isVirtual()) 1542 return true; 1543 1544 return false; 1545} 1546 1547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1548/// conversion (where Derived and Base are class types) is 1549/// well-formed, meaning that the conversion is unambiguous (and 1550/// that all of the base classes are accessible). Returns true 1551/// and emits a diagnostic if the code is ill-formed, returns false 1552/// otherwise. Loc is the location where this routine should point to 1553/// if there is an error, and Range is the source range to highlight 1554/// if there is an error. 1555bool 1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1557 unsigned InaccessibleBaseID, 1558 unsigned AmbigiousBaseConvID, 1559 SourceLocation Loc, SourceRange Range, 1560 DeclarationName Name, 1561 CXXCastPath *BasePath) { 1562 // First, determine whether the path from Derived to Base is 1563 // ambiguous. This is slightly more expensive than checking whether 1564 // the Derived to Base conversion exists, because here we need to 1565 // explore multiple paths to determine if there is an ambiguity. 1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1567 /*DetectVirtual=*/false); 1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1569 assert(DerivationOkay && 1570 "Can only be used with a derived-to-base conversion"); 1571 (void)DerivationOkay; 1572 1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1574 if (InaccessibleBaseID) { 1575 // Check that the base class can be accessed. 1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1577 InaccessibleBaseID)) { 1578 case AR_inaccessible: 1579 return true; 1580 case AR_accessible: 1581 case AR_dependent: 1582 case AR_delayed: 1583 break; 1584 } 1585 } 1586 1587 // Build a base path if necessary. 1588 if (BasePath) 1589 BuildBasePathArray(Paths, *BasePath); 1590 return false; 1591 } 1592 1593 // We know that the derived-to-base conversion is ambiguous, and 1594 // we're going to produce a diagnostic. Perform the derived-to-base 1595 // search just one more time to compute all of the possible paths so 1596 // that we can print them out. This is more expensive than any of 1597 // the previous derived-to-base checks we've done, but at this point 1598 // performance isn't as much of an issue. 1599 Paths.clear(); 1600 Paths.setRecordingPaths(true); 1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1602 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1603 (void)StillOkay; 1604 1605 // Build up a textual representation of the ambiguous paths, e.g., 1606 // D -> B -> A, that will be used to illustrate the ambiguous 1607 // conversions in the diagnostic. We only print one of the paths 1608 // to each base class subobject. 1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1610 1611 Diag(Loc, AmbigiousBaseConvID) 1612 << Derived << Base << PathDisplayStr << Range << Name; 1613 return true; 1614} 1615 1616bool 1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1618 SourceLocation Loc, SourceRange Range, 1619 CXXCastPath *BasePath, 1620 bool IgnoreAccess) { 1621 return CheckDerivedToBaseConversion(Derived, Base, 1622 IgnoreAccess ? 0 1623 : diag::err_upcast_to_inaccessible_base, 1624 diag::err_ambiguous_derived_to_base_conv, 1625 Loc, Range, DeclarationName(), 1626 BasePath); 1627} 1628 1629 1630/// @brief Builds a string representing ambiguous paths from a 1631/// specific derived class to different subobjects of the same base 1632/// class. 1633/// 1634/// This function builds a string that can be used in error messages 1635/// to show the different paths that one can take through the 1636/// inheritance hierarchy to go from the derived class to different 1637/// subobjects of a base class. The result looks something like this: 1638/// @code 1639/// struct D -> struct B -> struct A 1640/// struct D -> struct C -> struct A 1641/// @endcode 1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1643 std::string PathDisplayStr; 1644 std::set<unsigned> DisplayedPaths; 1645 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1646 Path != Paths.end(); ++Path) { 1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1648 // We haven't displayed a path to this particular base 1649 // class subobject yet. 1650 PathDisplayStr += "\n "; 1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1652 for (CXXBasePath::const_iterator Element = Path->begin(); 1653 Element != Path->end(); ++Element) 1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1655 } 1656 } 1657 1658 return PathDisplayStr; 1659} 1660 1661//===----------------------------------------------------------------------===// 1662// C++ class member Handling 1663//===----------------------------------------------------------------------===// 1664 1665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1667 SourceLocation ASLoc, 1668 SourceLocation ColonLoc, 1669 AttributeList *Attrs) { 1670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1672 ASLoc, ColonLoc); 1673 CurContext->addHiddenDecl(ASDecl); 1674 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1675} 1676 1677/// CheckOverrideControl - Check C++11 override control semantics. 1678void Sema::CheckOverrideControl(Decl *D) { 1679 if (D->isInvalidDecl()) 1680 return; 1681 1682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1683 1684 // Do we know which functions this declaration might be overriding? 1685 bool OverridesAreKnown = !MD || 1686 (!MD->getParent()->hasAnyDependentBases() && 1687 !MD->getType()->isDependentType()); 1688 1689 if (!MD || !MD->isVirtual()) { 1690 if (OverridesAreKnown) { 1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1692 Diag(OA->getLocation(), 1693 diag::override_keyword_only_allowed_on_virtual_member_functions) 1694 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1695 D->dropAttr<OverrideAttr>(); 1696 } 1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1698 Diag(FA->getLocation(), 1699 diag::override_keyword_only_allowed_on_virtual_member_functions) 1700 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1701 D->dropAttr<FinalAttr>(); 1702 } 1703 } 1704 return; 1705 } 1706 1707 if (!OverridesAreKnown) 1708 return; 1709 1710 // C++11 [class.virtual]p5: 1711 // If a virtual function is marked with the virt-specifier override and 1712 // does not override a member function of a base class, the program is 1713 // ill-formed. 1714 bool HasOverriddenMethods = 1715 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1718 << MD->getDeclName(); 1719} 1720 1721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1722/// function overrides a virtual member function marked 'final', according to 1723/// C++11 [class.virtual]p4. 1724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1725 const CXXMethodDecl *Old) { 1726 if (!Old->hasAttr<FinalAttr>()) 1727 return false; 1728 1729 Diag(New->getLocation(), diag::err_final_function_overridden) 1730 << New->getDeclName(); 1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1732 return true; 1733} 1734 1735static bool InitializationHasSideEffects(const FieldDecl &FD) { 1736 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1737 // FIXME: Destruction of ObjC lifetime types has side-effects. 1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1739 return !RD->isCompleteDefinition() || 1740 !RD->hasTrivialDefaultConstructor() || 1741 !RD->hasTrivialDestructor(); 1742 return false; 1743} 1744 1745static AttributeList *getMSPropertyAttr(AttributeList *list) { 1746 for (AttributeList* it = list; it != 0; it = it->getNext()) 1747 if (it->isDeclspecPropertyAttribute()) 1748 return it; 1749 return 0; 1750} 1751 1752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1754/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1756/// present (but parsing it has been deferred). 1757NamedDecl * 1758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1759 MultiTemplateParamsArg TemplateParameterLists, 1760 Expr *BW, const VirtSpecifiers &VS, 1761 InClassInitStyle InitStyle) { 1762 const DeclSpec &DS = D.getDeclSpec(); 1763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1764 DeclarationName Name = NameInfo.getName(); 1765 SourceLocation Loc = NameInfo.getLoc(); 1766 1767 // For anonymous bitfields, the location should point to the type. 1768 if (Loc.isInvalid()) 1769 Loc = D.getLocStart(); 1770 1771 Expr *BitWidth = static_cast<Expr*>(BW); 1772 1773 assert(isa<CXXRecordDecl>(CurContext)); 1774 assert(!DS.isFriendSpecified()); 1775 1776 bool isFunc = D.isDeclarationOfFunction(); 1777 1778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1779 // The Microsoft extension __interface only permits public member functions 1780 // and prohibits constructors, destructors, operators, non-public member 1781 // functions, static methods and data members. 1782 unsigned InvalidDecl; 1783 bool ShowDeclName = true; 1784 if (!isFunc) 1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1786 else if (AS != AS_public) 1787 InvalidDecl = 2; 1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1789 InvalidDecl = 3; 1790 else switch (Name.getNameKind()) { 1791 case DeclarationName::CXXConstructorName: 1792 InvalidDecl = 4; 1793 ShowDeclName = false; 1794 break; 1795 1796 case DeclarationName::CXXDestructorName: 1797 InvalidDecl = 5; 1798 ShowDeclName = false; 1799 break; 1800 1801 case DeclarationName::CXXOperatorName: 1802 case DeclarationName::CXXConversionFunctionName: 1803 InvalidDecl = 6; 1804 break; 1805 1806 default: 1807 InvalidDecl = 0; 1808 break; 1809 } 1810 1811 if (InvalidDecl) { 1812 if (ShowDeclName) 1813 Diag(Loc, diag::err_invalid_member_in_interface) 1814 << (InvalidDecl-1) << Name; 1815 else 1816 Diag(Loc, diag::err_invalid_member_in_interface) 1817 << (InvalidDecl-1) << ""; 1818 return 0; 1819 } 1820 } 1821 1822 // C++ 9.2p6: A member shall not be declared to have automatic storage 1823 // duration (auto, register) or with the extern storage-class-specifier. 1824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1825 // data members and cannot be applied to names declared const or static, 1826 // and cannot be applied to reference members. 1827 switch (DS.getStorageClassSpec()) { 1828 case DeclSpec::SCS_unspecified: 1829 case DeclSpec::SCS_typedef: 1830 case DeclSpec::SCS_static: 1831 break; 1832 case DeclSpec::SCS_mutable: 1833 if (isFunc) { 1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1835 1836 // FIXME: It would be nicer if the keyword was ignored only for this 1837 // declarator. Otherwise we could get follow-up errors. 1838 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1839 } 1840 break; 1841 default: 1842 Diag(DS.getStorageClassSpecLoc(), 1843 diag::err_storageclass_invalid_for_member); 1844 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1845 break; 1846 } 1847 1848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1850 !isFunc); 1851 1852 if (DS.isConstexprSpecified() && isInstField) { 1853 SemaDiagnosticBuilder B = 1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1856 if (InitStyle == ICIS_NoInit) { 1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1858 D.getMutableDeclSpec().ClearConstexprSpec(); 1859 const char *PrevSpec; 1860 unsigned DiagID; 1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1862 PrevSpec, DiagID, getLangOpts()); 1863 (void)Failed; 1864 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1865 } else { 1866 B << 1; 1867 const char *PrevSpec; 1868 unsigned DiagID; 1869 if (D.getMutableDeclSpec().SetStorageClassSpec( 1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1872 "This is the only DeclSpec that should fail to be applied"); 1873 B << 1; 1874 } else { 1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1876 isInstField = false; 1877 } 1878 } 1879 } 1880 1881 NamedDecl *Member; 1882 if (isInstField) { 1883 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1884 1885 // Data members must have identifiers for names. 1886 if (!Name.isIdentifier()) { 1887 Diag(Loc, diag::err_bad_variable_name) 1888 << Name; 1889 return 0; 1890 } 1891 1892 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1893 1894 // Member field could not be with "template" keyword. 1895 // So TemplateParameterLists should be empty in this case. 1896 if (TemplateParameterLists.size()) { 1897 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1898 if (TemplateParams->size()) { 1899 // There is no such thing as a member field template. 1900 Diag(D.getIdentifierLoc(), diag::err_template_member) 1901 << II 1902 << SourceRange(TemplateParams->getTemplateLoc(), 1903 TemplateParams->getRAngleLoc()); 1904 } else { 1905 // There is an extraneous 'template<>' for this member. 1906 Diag(TemplateParams->getTemplateLoc(), 1907 diag::err_template_member_noparams) 1908 << II 1909 << SourceRange(TemplateParams->getTemplateLoc(), 1910 TemplateParams->getRAngleLoc()); 1911 } 1912 return 0; 1913 } 1914 1915 if (SS.isSet() && !SS.isInvalid()) { 1916 // The user provided a superfluous scope specifier inside a class 1917 // definition: 1918 // 1919 // class X { 1920 // int X::member; 1921 // }; 1922 if (DeclContext *DC = computeDeclContext(SS, false)) 1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1924 else 1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1926 << Name << SS.getRange(); 1927 1928 SS.clear(); 1929 } 1930 1931 AttributeList *MSPropertyAttr = 1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 1933 if (MSPropertyAttr) { 1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1935 BitWidth, InitStyle, AS, MSPropertyAttr); 1936 isInstField = false; 1937 } else { 1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1939 BitWidth, InitStyle, AS); 1940 } 1941 assert(Member && "HandleField never returns null"); 1942 } else { 1943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1944 1945 Member = HandleDeclarator(S, D, TemplateParameterLists); 1946 if (!Member) { 1947 return 0; 1948 } 1949 1950 // Non-instance-fields can't have a bitfield. 1951 if (BitWidth) { 1952 if (Member->isInvalidDecl()) { 1953 // don't emit another diagnostic. 1954 } else if (isa<VarDecl>(Member)) { 1955 // C++ 9.6p3: A bit-field shall not be a static member. 1956 // "static member 'A' cannot be a bit-field" 1957 Diag(Loc, diag::err_static_not_bitfield) 1958 << Name << BitWidth->getSourceRange(); 1959 } else if (isa<TypedefDecl>(Member)) { 1960 // "typedef member 'x' cannot be a bit-field" 1961 Diag(Loc, diag::err_typedef_not_bitfield) 1962 << Name << BitWidth->getSourceRange(); 1963 } else { 1964 // A function typedef ("typedef int f(); f a;"). 1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1966 Diag(Loc, diag::err_not_integral_type_bitfield) 1967 << Name << cast<ValueDecl>(Member)->getType() 1968 << BitWidth->getSourceRange(); 1969 } 1970 1971 BitWidth = 0; 1972 Member->setInvalidDecl(); 1973 } 1974 1975 Member->setAccess(AS); 1976 1977 // If we have declared a member function template, set the access of the 1978 // templated declaration as well. 1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1980 FunTmpl->getTemplatedDecl()->setAccess(AS); 1981 } 1982 1983 if (VS.isOverrideSpecified()) 1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1985 if (VS.isFinalSpecified()) 1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1987 1988 if (VS.getLastLocation().isValid()) { 1989 // Update the end location of a method that has a virt-specifiers. 1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1991 MD->setRangeEnd(VS.getLastLocation()); 1992 } 1993 1994 CheckOverrideControl(Member); 1995 1996 assert((Name || isInstField) && "No identifier for non-field ?"); 1997 1998 if (isInstField) { 1999 FieldDecl *FD = cast<FieldDecl>(Member); 2000 FieldCollector->Add(FD); 2001 2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2003 FD->getLocation()) 2004 != DiagnosticsEngine::Ignored) { 2005 // Remember all explicit private FieldDecls that have a name, no side 2006 // effects and are not part of a dependent type declaration. 2007 if (!FD->isImplicit() && FD->getDeclName() && 2008 FD->getAccess() == AS_private && 2009 !FD->hasAttr<UnusedAttr>() && 2010 !FD->getParent()->isDependentContext() && 2011 !InitializationHasSideEffects(*FD)) 2012 UnusedPrivateFields.insert(FD); 2013 } 2014 } 2015 2016 return Member; 2017} 2018 2019namespace { 2020 class UninitializedFieldVisitor 2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2022 Sema &S; 2023 ValueDecl *VD; 2024 public: 2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2027 S(S) { 2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2029 this->VD = IFD->getAnonField(); 2030 else 2031 this->VD = VD; 2032 } 2033 2034 void HandleExpr(Expr *E) { 2035 if (!E) return; 2036 2037 // Expressions like x(x) sometimes lack the surrounding expressions 2038 // but need to be checked anyways. 2039 HandleValue(E); 2040 Visit(E); 2041 } 2042 2043 void HandleValue(Expr *E) { 2044 E = E->IgnoreParens(); 2045 2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2047 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2048 return; 2049 2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2051 // or union. 2052 MemberExpr *FieldME = ME; 2053 2054 Expr *Base = E; 2055 while (isa<MemberExpr>(Base)) { 2056 ME = cast<MemberExpr>(Base); 2057 2058 if (isa<VarDecl>(ME->getMemberDecl())) 2059 return; 2060 2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2062 if (!FD->isAnonymousStructOrUnion()) 2063 FieldME = ME; 2064 2065 Base = ME->getBase(); 2066 } 2067 2068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2069 unsigned diag = VD->getType()->isReferenceType() 2070 ? diag::warn_reference_field_is_uninit 2071 : diag::warn_field_is_uninit; 2072 S.Diag(FieldME->getExprLoc(), diag) << VD; 2073 } 2074 return; 2075 } 2076 2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2078 HandleValue(CO->getTrueExpr()); 2079 HandleValue(CO->getFalseExpr()); 2080 return; 2081 } 2082 2083 if (BinaryConditionalOperator *BCO = 2084 dyn_cast<BinaryConditionalOperator>(E)) { 2085 HandleValue(BCO->getCommon()); 2086 HandleValue(BCO->getFalseExpr()); 2087 return; 2088 } 2089 2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2091 switch (BO->getOpcode()) { 2092 default: 2093 return; 2094 case(BO_PtrMemD): 2095 case(BO_PtrMemI): 2096 HandleValue(BO->getLHS()); 2097 return; 2098 case(BO_Comma): 2099 HandleValue(BO->getRHS()); 2100 return; 2101 } 2102 } 2103 } 2104 2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2106 if (E->getCastKind() == CK_LValueToRValue) 2107 HandleValue(E->getSubExpr()); 2108 2109 Inherited::VisitImplicitCastExpr(E); 2110 } 2111 2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2113 Expr *Callee = E->getCallee(); 2114 if (isa<MemberExpr>(Callee)) 2115 HandleValue(Callee); 2116 2117 Inherited::VisitCXXMemberCallExpr(E); 2118 } 2119 }; 2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2121 ValueDecl *VD) { 2122 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2123 } 2124} // namespace 2125 2126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2127/// in-class initializer for a non-static C++ class member, and after 2128/// instantiating an in-class initializer in a class template. Such actions 2129/// are deferred until the class is complete. 2130void 2131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2132 Expr *InitExpr) { 2133 FieldDecl *FD = cast<FieldDecl>(D); 2134 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2135 "must set init style when field is created"); 2136 2137 if (!InitExpr) { 2138 FD->setInvalidDecl(); 2139 FD->removeInClassInitializer(); 2140 return; 2141 } 2142 2143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2144 FD->setInvalidDecl(); 2145 FD->removeInClassInitializer(); 2146 return; 2147 } 2148 2149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 2150 != DiagnosticsEngine::Ignored) { 2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 2152 } 2153 2154 ExprResult Init = InitExpr; 2155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 2157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 2158 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 2159 } 2160 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2161 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2162 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2163 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2164 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2165 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2166 if (Init.isInvalid()) { 2167 FD->setInvalidDecl(); 2168 return; 2169 } 2170 } 2171 2172 // C++11 [class.base.init]p7: 2173 // The initialization of each base and member constitutes a 2174 // full-expression. 2175 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2176 if (Init.isInvalid()) { 2177 FD->setInvalidDecl(); 2178 return; 2179 } 2180 2181 InitExpr = Init.release(); 2182 2183 FD->setInClassInitializer(InitExpr); 2184} 2185 2186/// \brief Find the direct and/or virtual base specifiers that 2187/// correspond to the given base type, for use in base initialization 2188/// within a constructor. 2189static bool FindBaseInitializer(Sema &SemaRef, 2190 CXXRecordDecl *ClassDecl, 2191 QualType BaseType, 2192 const CXXBaseSpecifier *&DirectBaseSpec, 2193 const CXXBaseSpecifier *&VirtualBaseSpec) { 2194 // First, check for a direct base class. 2195 DirectBaseSpec = 0; 2196 for (CXXRecordDecl::base_class_const_iterator Base 2197 = ClassDecl->bases_begin(); 2198 Base != ClassDecl->bases_end(); ++Base) { 2199 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2200 // We found a direct base of this type. That's what we're 2201 // initializing. 2202 DirectBaseSpec = &*Base; 2203 break; 2204 } 2205 } 2206 2207 // Check for a virtual base class. 2208 // FIXME: We might be able to short-circuit this if we know in advance that 2209 // there are no virtual bases. 2210 VirtualBaseSpec = 0; 2211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2212 // We haven't found a base yet; search the class hierarchy for a 2213 // virtual base class. 2214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2215 /*DetectVirtual=*/false); 2216 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2217 BaseType, Paths)) { 2218 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2219 Path != Paths.end(); ++Path) { 2220 if (Path->back().Base->isVirtual()) { 2221 VirtualBaseSpec = Path->back().Base; 2222 break; 2223 } 2224 } 2225 } 2226 } 2227 2228 return DirectBaseSpec || VirtualBaseSpec; 2229} 2230 2231/// \brief Handle a C++ member initializer using braced-init-list syntax. 2232MemInitResult 2233Sema::ActOnMemInitializer(Decl *ConstructorD, 2234 Scope *S, 2235 CXXScopeSpec &SS, 2236 IdentifierInfo *MemberOrBase, 2237 ParsedType TemplateTypeTy, 2238 const DeclSpec &DS, 2239 SourceLocation IdLoc, 2240 Expr *InitList, 2241 SourceLocation EllipsisLoc) { 2242 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2243 DS, IdLoc, InitList, 2244 EllipsisLoc); 2245} 2246 2247/// \brief Handle a C++ member initializer using parentheses syntax. 2248MemInitResult 2249Sema::ActOnMemInitializer(Decl *ConstructorD, 2250 Scope *S, 2251 CXXScopeSpec &SS, 2252 IdentifierInfo *MemberOrBase, 2253 ParsedType TemplateTypeTy, 2254 const DeclSpec &DS, 2255 SourceLocation IdLoc, 2256 SourceLocation LParenLoc, 2257 ArrayRef<Expr *> Args, 2258 SourceLocation RParenLoc, 2259 SourceLocation EllipsisLoc) { 2260 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2261 Args, RParenLoc); 2262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2263 DS, IdLoc, List, EllipsisLoc); 2264} 2265 2266namespace { 2267 2268// Callback to only accept typo corrections that can be a valid C++ member 2269// intializer: either a non-static field member or a base class. 2270class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2271 public: 2272 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2273 : ClassDecl(ClassDecl) {} 2274 2275 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2276 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2277 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2278 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2279 else 2280 return isa<TypeDecl>(ND); 2281 } 2282 return false; 2283 } 2284 2285 private: 2286 CXXRecordDecl *ClassDecl; 2287}; 2288 2289} 2290 2291/// \brief Handle a C++ member initializer. 2292MemInitResult 2293Sema::BuildMemInitializer(Decl *ConstructorD, 2294 Scope *S, 2295 CXXScopeSpec &SS, 2296 IdentifierInfo *MemberOrBase, 2297 ParsedType TemplateTypeTy, 2298 const DeclSpec &DS, 2299 SourceLocation IdLoc, 2300 Expr *Init, 2301 SourceLocation EllipsisLoc) { 2302 if (!ConstructorD) 2303 return true; 2304 2305 AdjustDeclIfTemplate(ConstructorD); 2306 2307 CXXConstructorDecl *Constructor 2308 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2309 if (!Constructor) { 2310 // The user wrote a constructor initializer on a function that is 2311 // not a C++ constructor. Ignore the error for now, because we may 2312 // have more member initializers coming; we'll diagnose it just 2313 // once in ActOnMemInitializers. 2314 return true; 2315 } 2316 2317 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2318 2319 // C++ [class.base.init]p2: 2320 // Names in a mem-initializer-id are looked up in the scope of the 2321 // constructor's class and, if not found in that scope, are looked 2322 // up in the scope containing the constructor's definition. 2323 // [Note: if the constructor's class contains a member with the 2324 // same name as a direct or virtual base class of the class, a 2325 // mem-initializer-id naming the member or base class and composed 2326 // of a single identifier refers to the class member. A 2327 // mem-initializer-id for the hidden base class may be specified 2328 // using a qualified name. ] 2329 if (!SS.getScopeRep() && !TemplateTypeTy) { 2330 // Look for a member, first. 2331 DeclContext::lookup_result Result 2332 = ClassDecl->lookup(MemberOrBase); 2333 if (!Result.empty()) { 2334 ValueDecl *Member; 2335 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2336 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2337 if (EllipsisLoc.isValid()) 2338 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2339 << MemberOrBase 2340 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2341 2342 return BuildMemberInitializer(Member, Init, IdLoc); 2343 } 2344 } 2345 } 2346 // It didn't name a member, so see if it names a class. 2347 QualType BaseType; 2348 TypeSourceInfo *TInfo = 0; 2349 2350 if (TemplateTypeTy) { 2351 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2352 } else if (DS.getTypeSpecType() == TST_decltype) { 2353 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2354 } else { 2355 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2356 LookupParsedName(R, S, &SS); 2357 2358 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2359 if (!TyD) { 2360 if (R.isAmbiguous()) return true; 2361 2362 // We don't want access-control diagnostics here. 2363 R.suppressDiagnostics(); 2364 2365 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2366 bool NotUnknownSpecialization = false; 2367 DeclContext *DC = computeDeclContext(SS, false); 2368 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2369 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2370 2371 if (!NotUnknownSpecialization) { 2372 // When the scope specifier can refer to a member of an unknown 2373 // specialization, we take it as a type name. 2374 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2375 SS.getWithLocInContext(Context), 2376 *MemberOrBase, IdLoc); 2377 if (BaseType.isNull()) 2378 return true; 2379 2380 R.clear(); 2381 R.setLookupName(MemberOrBase); 2382 } 2383 } 2384 2385 // If no results were found, try to correct typos. 2386 TypoCorrection Corr; 2387 MemInitializerValidatorCCC Validator(ClassDecl); 2388 if (R.empty() && BaseType.isNull() && 2389 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2390 Validator, ClassDecl))) { 2391 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2392 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2393 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2394 // We have found a non-static data member with a similar 2395 // name to what was typed; complain and initialize that 2396 // member. 2397 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2398 << MemberOrBase << true << CorrectedQuotedStr 2399 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2400 Diag(Member->getLocation(), diag::note_previous_decl) 2401 << CorrectedQuotedStr; 2402 2403 return BuildMemberInitializer(Member, Init, IdLoc); 2404 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2405 const CXXBaseSpecifier *DirectBaseSpec; 2406 const CXXBaseSpecifier *VirtualBaseSpec; 2407 if (FindBaseInitializer(*this, ClassDecl, 2408 Context.getTypeDeclType(Type), 2409 DirectBaseSpec, VirtualBaseSpec)) { 2410 // We have found a direct or virtual base class with a 2411 // similar name to what was typed; complain and initialize 2412 // that base class. 2413 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2414 << MemberOrBase << false << CorrectedQuotedStr 2415 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2416 2417 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2418 : VirtualBaseSpec; 2419 Diag(BaseSpec->getLocStart(), 2420 diag::note_base_class_specified_here) 2421 << BaseSpec->getType() 2422 << BaseSpec->getSourceRange(); 2423 2424 TyD = Type; 2425 } 2426 } 2427 } 2428 2429 if (!TyD && BaseType.isNull()) { 2430 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2431 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2432 return true; 2433 } 2434 } 2435 2436 if (BaseType.isNull()) { 2437 BaseType = Context.getTypeDeclType(TyD); 2438 if (SS.isSet()) { 2439 NestedNameSpecifier *Qualifier = 2440 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2441 2442 // FIXME: preserve source range information 2443 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2444 } 2445 } 2446 } 2447 2448 if (!TInfo) 2449 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2450 2451 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2452} 2453 2454/// Checks a member initializer expression for cases where reference (or 2455/// pointer) members are bound to by-value parameters (or their addresses). 2456static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2457 Expr *Init, 2458 SourceLocation IdLoc) { 2459 QualType MemberTy = Member->getType(); 2460 2461 // We only handle pointers and references currently. 2462 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2463 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2464 return; 2465 2466 const bool IsPointer = MemberTy->isPointerType(); 2467 if (IsPointer) { 2468 if (const UnaryOperator *Op 2469 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2470 // The only case we're worried about with pointers requires taking the 2471 // address. 2472 if (Op->getOpcode() != UO_AddrOf) 2473 return; 2474 2475 Init = Op->getSubExpr(); 2476 } else { 2477 // We only handle address-of expression initializers for pointers. 2478 return; 2479 } 2480 } 2481 2482 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2483 // Taking the address of a temporary will be diagnosed as a hard error. 2484 if (IsPointer) 2485 return; 2486 2487 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2488 << Member << Init->getSourceRange(); 2489 } else if (const DeclRefExpr *DRE 2490 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2491 // We only warn when referring to a non-reference parameter declaration. 2492 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2493 if (!Parameter || Parameter->getType()->isReferenceType()) 2494 return; 2495 2496 S.Diag(Init->getExprLoc(), 2497 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2498 : diag::warn_bind_ref_member_to_parameter) 2499 << Member << Parameter << Init->getSourceRange(); 2500 } else { 2501 // Other initializers are fine. 2502 return; 2503 } 2504 2505 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2506 << (unsigned)IsPointer; 2507} 2508 2509MemInitResult 2510Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2511 SourceLocation IdLoc) { 2512 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2513 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2514 assert((DirectMember || IndirectMember) && 2515 "Member must be a FieldDecl or IndirectFieldDecl"); 2516 2517 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2518 return true; 2519 2520 if (Member->isInvalidDecl()) 2521 return true; 2522 2523 // Diagnose value-uses of fields to initialize themselves, e.g. 2524 // foo(foo) 2525 // where foo is not also a parameter to the constructor. 2526 // TODO: implement -Wuninitialized and fold this into that framework. 2527 MultiExprArg Args; 2528 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2529 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2530 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2531 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2532 } else { 2533 // Template instantiation doesn't reconstruct ParenListExprs for us. 2534 Args = Init; 2535 } 2536 2537 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2538 != DiagnosticsEngine::Ignored) 2539 for (unsigned i = 0, e = Args.size(); i != e; ++i) 2540 // FIXME: Warn about the case when other fields are used before being 2541 // initialized. For example, let this field be the i'th field. When 2542 // initializing the i'th field, throw a warning if any of the >= i'th 2543 // fields are used, as they are not yet initialized. 2544 // Right now we are only handling the case where the i'th field uses 2545 // itself in its initializer. 2546 // Also need to take into account that some fields may be initialized by 2547 // in-class initializers, see C++11 [class.base.init]p9. 2548 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2549 2550 SourceRange InitRange = Init->getSourceRange(); 2551 2552 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2553 // Can't check initialization for a member of dependent type or when 2554 // any of the arguments are type-dependent expressions. 2555 DiscardCleanupsInEvaluationContext(); 2556 } else { 2557 bool InitList = false; 2558 if (isa<InitListExpr>(Init)) { 2559 InitList = true; 2560 Args = Init; 2561 2562 if (isStdInitializerList(Member->getType(), 0)) { 2563 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2564 << /*at end of ctor*/1 << InitRange; 2565 } 2566 } 2567 2568 // Initialize the member. 2569 InitializedEntity MemberEntity = 2570 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2571 : InitializedEntity::InitializeMember(IndirectMember, 0); 2572 InitializationKind Kind = 2573 InitList ? InitializationKind::CreateDirectList(IdLoc) 2574 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2575 InitRange.getEnd()); 2576 2577 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2578 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2579 if (MemberInit.isInvalid()) 2580 return true; 2581 2582 // C++11 [class.base.init]p7: 2583 // The initialization of each base and member constitutes a 2584 // full-expression. 2585 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2586 if (MemberInit.isInvalid()) 2587 return true; 2588 2589 Init = MemberInit.get(); 2590 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2591 } 2592 2593 if (DirectMember) { 2594 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2595 InitRange.getBegin(), Init, 2596 InitRange.getEnd()); 2597 } else { 2598 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2599 InitRange.getBegin(), Init, 2600 InitRange.getEnd()); 2601 } 2602} 2603 2604MemInitResult 2605Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2606 CXXRecordDecl *ClassDecl) { 2607 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2608 if (!LangOpts.CPlusPlus11) 2609 return Diag(NameLoc, diag::err_delegating_ctor) 2610 << TInfo->getTypeLoc().getLocalSourceRange(); 2611 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2612 2613 bool InitList = true; 2614 MultiExprArg Args = Init; 2615 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2616 InitList = false; 2617 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2618 } 2619 2620 SourceRange InitRange = Init->getSourceRange(); 2621 // Initialize the object. 2622 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2623 QualType(ClassDecl->getTypeForDecl(), 0)); 2624 InitializationKind Kind = 2625 InitList ? InitializationKind::CreateDirectList(NameLoc) 2626 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2627 InitRange.getEnd()); 2628 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2629 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2630 Args, 0); 2631 if (DelegationInit.isInvalid()) 2632 return true; 2633 2634 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2635 "Delegating constructor with no target?"); 2636 2637 // C++11 [class.base.init]p7: 2638 // The initialization of each base and member constitutes a 2639 // full-expression. 2640 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2641 InitRange.getBegin()); 2642 if (DelegationInit.isInvalid()) 2643 return true; 2644 2645 // If we are in a dependent context, template instantiation will 2646 // perform this type-checking again. Just save the arguments that we 2647 // received in a ParenListExpr. 2648 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2649 // of the information that we have about the base 2650 // initializer. However, deconstructing the ASTs is a dicey process, 2651 // and this approach is far more likely to get the corner cases right. 2652 if (CurContext->isDependentContext()) 2653 DelegationInit = Owned(Init); 2654 2655 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2656 DelegationInit.takeAs<Expr>(), 2657 InitRange.getEnd()); 2658} 2659 2660MemInitResult 2661Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2662 Expr *Init, CXXRecordDecl *ClassDecl, 2663 SourceLocation EllipsisLoc) { 2664 SourceLocation BaseLoc 2665 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2666 2667 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2668 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2669 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2670 2671 // C++ [class.base.init]p2: 2672 // [...] Unless the mem-initializer-id names a nonstatic data 2673 // member of the constructor's class or a direct or virtual base 2674 // of that class, the mem-initializer is ill-formed. A 2675 // mem-initializer-list can initialize a base class using any 2676 // name that denotes that base class type. 2677 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2678 2679 SourceRange InitRange = Init->getSourceRange(); 2680 if (EllipsisLoc.isValid()) { 2681 // This is a pack expansion. 2682 if (!BaseType->containsUnexpandedParameterPack()) { 2683 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2684 << SourceRange(BaseLoc, InitRange.getEnd()); 2685 2686 EllipsisLoc = SourceLocation(); 2687 } 2688 } else { 2689 // Check for any unexpanded parameter packs. 2690 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2691 return true; 2692 2693 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2694 return true; 2695 } 2696 2697 // Check for direct and virtual base classes. 2698 const CXXBaseSpecifier *DirectBaseSpec = 0; 2699 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2700 if (!Dependent) { 2701 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2702 BaseType)) 2703 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2704 2705 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2706 VirtualBaseSpec); 2707 2708 // C++ [base.class.init]p2: 2709 // Unless the mem-initializer-id names a nonstatic data member of the 2710 // constructor's class or a direct or virtual base of that class, the 2711 // mem-initializer is ill-formed. 2712 if (!DirectBaseSpec && !VirtualBaseSpec) { 2713 // If the class has any dependent bases, then it's possible that 2714 // one of those types will resolve to the same type as 2715 // BaseType. Therefore, just treat this as a dependent base 2716 // class initialization. FIXME: Should we try to check the 2717 // initialization anyway? It seems odd. 2718 if (ClassDecl->hasAnyDependentBases()) 2719 Dependent = true; 2720 else 2721 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2722 << BaseType << Context.getTypeDeclType(ClassDecl) 2723 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2724 } 2725 } 2726 2727 if (Dependent) { 2728 DiscardCleanupsInEvaluationContext(); 2729 2730 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2731 /*IsVirtual=*/false, 2732 InitRange.getBegin(), Init, 2733 InitRange.getEnd(), EllipsisLoc); 2734 } 2735 2736 // C++ [base.class.init]p2: 2737 // If a mem-initializer-id is ambiguous because it designates both 2738 // a direct non-virtual base class and an inherited virtual base 2739 // class, the mem-initializer is ill-formed. 2740 if (DirectBaseSpec && VirtualBaseSpec) 2741 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2742 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2743 2744 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2745 if (!BaseSpec) 2746 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2747 2748 // Initialize the base. 2749 bool InitList = true; 2750 MultiExprArg Args = Init; 2751 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2752 InitList = false; 2753 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2754 } 2755 2756 InitializedEntity BaseEntity = 2757 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2758 InitializationKind Kind = 2759 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2760 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2761 InitRange.getEnd()); 2762 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2763 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2764 if (BaseInit.isInvalid()) 2765 return true; 2766 2767 // C++11 [class.base.init]p7: 2768 // The initialization of each base and member constitutes a 2769 // full-expression. 2770 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2771 if (BaseInit.isInvalid()) 2772 return true; 2773 2774 // If we are in a dependent context, template instantiation will 2775 // perform this type-checking again. Just save the arguments that we 2776 // received in a ParenListExpr. 2777 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2778 // of the information that we have about the base 2779 // initializer. However, deconstructing the ASTs is a dicey process, 2780 // and this approach is far more likely to get the corner cases right. 2781 if (CurContext->isDependentContext()) 2782 BaseInit = Owned(Init); 2783 2784 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2785 BaseSpec->isVirtual(), 2786 InitRange.getBegin(), 2787 BaseInit.takeAs<Expr>(), 2788 InitRange.getEnd(), EllipsisLoc); 2789} 2790 2791// Create a static_cast\<T&&>(expr). 2792static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2793 if (T.isNull()) T = E->getType(); 2794 QualType TargetType = SemaRef.BuildReferenceType( 2795 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2796 SourceLocation ExprLoc = E->getLocStart(); 2797 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2798 TargetType, ExprLoc); 2799 2800 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2801 SourceRange(ExprLoc, ExprLoc), 2802 E->getSourceRange()).take(); 2803} 2804 2805/// ImplicitInitializerKind - How an implicit base or member initializer should 2806/// initialize its base or member. 2807enum ImplicitInitializerKind { 2808 IIK_Default, 2809 IIK_Copy, 2810 IIK_Move, 2811 IIK_Inherit 2812}; 2813 2814static bool 2815BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2816 ImplicitInitializerKind ImplicitInitKind, 2817 CXXBaseSpecifier *BaseSpec, 2818 bool IsInheritedVirtualBase, 2819 CXXCtorInitializer *&CXXBaseInit) { 2820 InitializedEntity InitEntity 2821 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2822 IsInheritedVirtualBase); 2823 2824 ExprResult BaseInit; 2825 2826 switch (ImplicitInitKind) { 2827 case IIK_Inherit: { 2828 const CXXRecordDecl *Inherited = 2829 Constructor->getInheritedConstructor()->getParent(); 2830 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2831 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2832 // C++11 [class.inhctor]p8: 2833 // Each expression in the expression-list is of the form 2834 // static_cast<T&&>(p), where p is the name of the corresponding 2835 // constructor parameter and T is the declared type of p. 2836 SmallVector<Expr*, 16> Args; 2837 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2838 ParmVarDecl *PD = Constructor->getParamDecl(I); 2839 ExprResult ArgExpr = 2840 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2841 VK_LValue, SourceLocation()); 2842 if (ArgExpr.isInvalid()) 2843 return true; 2844 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2845 } 2846 2847 InitializationKind InitKind = InitializationKind::CreateDirect( 2848 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2849 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2850 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2851 break; 2852 } 2853 } 2854 // Fall through. 2855 case IIK_Default: { 2856 InitializationKind InitKind 2857 = InitializationKind::CreateDefault(Constructor->getLocation()); 2858 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2859 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2860 break; 2861 } 2862 2863 case IIK_Move: 2864 case IIK_Copy: { 2865 bool Moving = ImplicitInitKind == IIK_Move; 2866 ParmVarDecl *Param = Constructor->getParamDecl(0); 2867 QualType ParamType = Param->getType().getNonReferenceType(); 2868 2869 Expr *CopyCtorArg = 2870 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2871 SourceLocation(), Param, false, 2872 Constructor->getLocation(), ParamType, 2873 VK_LValue, 0); 2874 2875 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2876 2877 // Cast to the base class to avoid ambiguities. 2878 QualType ArgTy = 2879 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2880 ParamType.getQualifiers()); 2881 2882 if (Moving) { 2883 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2884 } 2885 2886 CXXCastPath BasePath; 2887 BasePath.push_back(BaseSpec); 2888 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2889 CK_UncheckedDerivedToBase, 2890 Moving ? VK_XValue : VK_LValue, 2891 &BasePath).take(); 2892 2893 InitializationKind InitKind 2894 = InitializationKind::CreateDirect(Constructor->getLocation(), 2895 SourceLocation(), SourceLocation()); 2896 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 2897 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 2898 break; 2899 } 2900 } 2901 2902 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2903 if (BaseInit.isInvalid()) 2904 return true; 2905 2906 CXXBaseInit = 2907 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2908 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2909 SourceLocation()), 2910 BaseSpec->isVirtual(), 2911 SourceLocation(), 2912 BaseInit.takeAs<Expr>(), 2913 SourceLocation(), 2914 SourceLocation()); 2915 2916 return false; 2917} 2918 2919static bool RefersToRValueRef(Expr *MemRef) { 2920 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2921 return Referenced->getType()->isRValueReferenceType(); 2922} 2923 2924static bool 2925BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2926 ImplicitInitializerKind ImplicitInitKind, 2927 FieldDecl *Field, IndirectFieldDecl *Indirect, 2928 CXXCtorInitializer *&CXXMemberInit) { 2929 if (Field->isInvalidDecl()) 2930 return true; 2931 2932 SourceLocation Loc = Constructor->getLocation(); 2933 2934 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2935 bool Moving = ImplicitInitKind == IIK_Move; 2936 ParmVarDecl *Param = Constructor->getParamDecl(0); 2937 QualType ParamType = Param->getType().getNonReferenceType(); 2938 2939 // Suppress copying zero-width bitfields. 2940 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2941 return false; 2942 2943 Expr *MemberExprBase = 2944 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2945 SourceLocation(), Param, false, 2946 Loc, ParamType, VK_LValue, 0); 2947 2948 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2949 2950 if (Moving) { 2951 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2952 } 2953 2954 // Build a reference to this field within the parameter. 2955 CXXScopeSpec SS; 2956 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2957 Sema::LookupMemberName); 2958 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2959 : cast<ValueDecl>(Field), AS_public); 2960 MemberLookup.resolveKind(); 2961 ExprResult CtorArg 2962 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2963 ParamType, Loc, 2964 /*IsArrow=*/false, 2965 SS, 2966 /*TemplateKWLoc=*/SourceLocation(), 2967 /*FirstQualifierInScope=*/0, 2968 MemberLookup, 2969 /*TemplateArgs=*/0); 2970 if (CtorArg.isInvalid()) 2971 return true; 2972 2973 // C++11 [class.copy]p15: 2974 // - if a member m has rvalue reference type T&&, it is direct-initialized 2975 // with static_cast<T&&>(x.m); 2976 if (RefersToRValueRef(CtorArg.get())) { 2977 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2978 } 2979 2980 // When the field we are copying is an array, create index variables for 2981 // each dimension of the array. We use these index variables to subscript 2982 // the source array, and other clients (e.g., CodeGen) will perform the 2983 // necessary iteration with these index variables. 2984 SmallVector<VarDecl *, 4> IndexVariables; 2985 QualType BaseType = Field->getType(); 2986 QualType SizeType = SemaRef.Context.getSizeType(); 2987 bool InitializingArray = false; 2988 while (const ConstantArrayType *Array 2989 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2990 InitializingArray = true; 2991 // Create the iteration variable for this array index. 2992 IdentifierInfo *IterationVarName = 0; 2993 { 2994 SmallString<8> Str; 2995 llvm::raw_svector_ostream OS(Str); 2996 OS << "__i" << IndexVariables.size(); 2997 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2998 } 2999 VarDecl *IterationVar 3000 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3001 IterationVarName, SizeType, 3002 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3003 SC_None); 3004 IndexVariables.push_back(IterationVar); 3005 3006 // Create a reference to the iteration variable. 3007 ExprResult IterationVarRef 3008 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3009 assert(!IterationVarRef.isInvalid() && 3010 "Reference to invented variable cannot fail!"); 3011 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3012 assert(!IterationVarRef.isInvalid() && 3013 "Conversion of invented variable cannot fail!"); 3014 3015 // Subscript the array with this iteration variable. 3016 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3017 IterationVarRef.take(), 3018 Loc); 3019 if (CtorArg.isInvalid()) 3020 return true; 3021 3022 BaseType = Array->getElementType(); 3023 } 3024 3025 // The array subscript expression is an lvalue, which is wrong for moving. 3026 if (Moving && InitializingArray) 3027 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3028 3029 // Construct the entity that we will be initializing. For an array, this 3030 // will be first element in the array, which may require several levels 3031 // of array-subscript entities. 3032 SmallVector<InitializedEntity, 4> Entities; 3033 Entities.reserve(1 + IndexVariables.size()); 3034 if (Indirect) 3035 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3036 else 3037 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3038 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3039 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3040 0, 3041 Entities.back())); 3042 3043 // Direct-initialize to use the copy constructor. 3044 InitializationKind InitKind = 3045 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3046 3047 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3048 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3049 3050 ExprResult MemberInit 3051 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3052 MultiExprArg(&CtorArgE, 1)); 3053 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3054 if (MemberInit.isInvalid()) 3055 return true; 3056 3057 if (Indirect) { 3058 assert(IndexVariables.size() == 0 && 3059 "Indirect field improperly initialized"); 3060 CXXMemberInit 3061 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3062 Loc, Loc, 3063 MemberInit.takeAs<Expr>(), 3064 Loc); 3065 } else 3066 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3067 Loc, MemberInit.takeAs<Expr>(), 3068 Loc, 3069 IndexVariables.data(), 3070 IndexVariables.size()); 3071 return false; 3072 } 3073 3074 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3075 "Unhandled implicit init kind!"); 3076 3077 QualType FieldBaseElementType = 3078 SemaRef.Context.getBaseElementType(Field->getType()); 3079 3080 if (FieldBaseElementType->isRecordType()) { 3081 InitializedEntity InitEntity 3082 = Indirect? InitializedEntity::InitializeMember(Indirect) 3083 : InitializedEntity::InitializeMember(Field); 3084 InitializationKind InitKind = 3085 InitializationKind::CreateDefault(Loc); 3086 3087 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3088 ExprResult MemberInit = 3089 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3090 3091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3092 if (MemberInit.isInvalid()) 3093 return true; 3094 3095 if (Indirect) 3096 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3097 Indirect, Loc, 3098 Loc, 3099 MemberInit.get(), 3100 Loc); 3101 else 3102 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3103 Field, Loc, Loc, 3104 MemberInit.get(), 3105 Loc); 3106 return false; 3107 } 3108 3109 if (!Field->getParent()->isUnion()) { 3110 if (FieldBaseElementType->isReferenceType()) { 3111 SemaRef.Diag(Constructor->getLocation(), 3112 diag::err_uninitialized_member_in_ctor) 3113 << (int)Constructor->isImplicit() 3114 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3115 << 0 << Field->getDeclName(); 3116 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3117 return true; 3118 } 3119 3120 if (FieldBaseElementType.isConstQualified()) { 3121 SemaRef.Diag(Constructor->getLocation(), 3122 diag::err_uninitialized_member_in_ctor) 3123 << (int)Constructor->isImplicit() 3124 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3125 << 1 << Field->getDeclName(); 3126 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3127 return true; 3128 } 3129 } 3130 3131 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3132 FieldBaseElementType->isObjCRetainableType() && 3133 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3134 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3135 // ARC: 3136 // Default-initialize Objective-C pointers to NULL. 3137 CXXMemberInit 3138 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3139 Loc, Loc, 3140 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3141 Loc); 3142 return false; 3143 } 3144 3145 // Nothing to initialize. 3146 CXXMemberInit = 0; 3147 return false; 3148} 3149 3150namespace { 3151struct BaseAndFieldInfo { 3152 Sema &S; 3153 CXXConstructorDecl *Ctor; 3154 bool AnyErrorsInInits; 3155 ImplicitInitializerKind IIK; 3156 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3157 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3158 3159 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3160 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3161 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3162 if (Generated && Ctor->isCopyConstructor()) 3163 IIK = IIK_Copy; 3164 else if (Generated && Ctor->isMoveConstructor()) 3165 IIK = IIK_Move; 3166 else if (Ctor->getInheritedConstructor()) 3167 IIK = IIK_Inherit; 3168 else 3169 IIK = IIK_Default; 3170 } 3171 3172 bool isImplicitCopyOrMove() const { 3173 switch (IIK) { 3174 case IIK_Copy: 3175 case IIK_Move: 3176 return true; 3177 3178 case IIK_Default: 3179 case IIK_Inherit: 3180 return false; 3181 } 3182 3183 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3184 } 3185 3186 bool addFieldInitializer(CXXCtorInitializer *Init) { 3187 AllToInit.push_back(Init); 3188 3189 // Check whether this initializer makes the field "used". 3190 if (Init->getInit()->HasSideEffects(S.Context)) 3191 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3192 3193 return false; 3194 } 3195}; 3196} 3197 3198/// \brief Determine whether the given indirect field declaration is somewhere 3199/// within an anonymous union. 3200static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3201 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3202 CEnd = F->chain_end(); 3203 C != CEnd; ++C) 3204 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3205 if (Record->isUnion()) 3206 return true; 3207 3208 return false; 3209} 3210 3211/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3212/// array type. 3213static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3214 if (T->isIncompleteArrayType()) 3215 return true; 3216 3217 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3218 if (!ArrayT->getSize()) 3219 return true; 3220 3221 T = ArrayT->getElementType(); 3222 } 3223 3224 return false; 3225} 3226 3227static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3228 FieldDecl *Field, 3229 IndirectFieldDecl *Indirect = 0) { 3230 3231 // Overwhelmingly common case: we have a direct initializer for this field. 3232 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3233 return Info.addFieldInitializer(Init); 3234 3235 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3236 // has a brace-or-equal-initializer, the entity is initialized as specified 3237 // in [dcl.init]. 3238 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3239 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3240 Info.Ctor->getLocation(), Field); 3241 CXXCtorInitializer *Init; 3242 if (Indirect) 3243 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3244 SourceLocation(), 3245 SourceLocation(), DIE, 3246 SourceLocation()); 3247 else 3248 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3249 SourceLocation(), 3250 SourceLocation(), DIE, 3251 SourceLocation()); 3252 return Info.addFieldInitializer(Init); 3253 } 3254 3255 // Don't build an implicit initializer for union members if none was 3256 // explicitly specified. 3257 if (Field->getParent()->isUnion() || 3258 (Indirect && isWithinAnonymousUnion(Indirect))) 3259 return false; 3260 3261 // Don't initialize incomplete or zero-length arrays. 3262 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3263 return false; 3264 3265 // Don't try to build an implicit initializer if there were semantic 3266 // errors in any of the initializers (and therefore we might be 3267 // missing some that the user actually wrote). 3268 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3269 return false; 3270 3271 CXXCtorInitializer *Init = 0; 3272 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3273 Indirect, Init)) 3274 return true; 3275 3276 if (!Init) 3277 return false; 3278 3279 return Info.addFieldInitializer(Init); 3280} 3281 3282bool 3283Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3284 CXXCtorInitializer *Initializer) { 3285 assert(Initializer->isDelegatingInitializer()); 3286 Constructor->setNumCtorInitializers(1); 3287 CXXCtorInitializer **initializer = 3288 new (Context) CXXCtorInitializer*[1]; 3289 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3290 Constructor->setCtorInitializers(initializer); 3291 3292 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3293 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3294 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3295 } 3296 3297 DelegatingCtorDecls.push_back(Constructor); 3298 3299 return false; 3300} 3301 3302bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3303 ArrayRef<CXXCtorInitializer *> Initializers) { 3304 if (Constructor->isDependentContext()) { 3305 // Just store the initializers as written, they will be checked during 3306 // instantiation. 3307 if (!Initializers.empty()) { 3308 Constructor->setNumCtorInitializers(Initializers.size()); 3309 CXXCtorInitializer **baseOrMemberInitializers = 3310 new (Context) CXXCtorInitializer*[Initializers.size()]; 3311 memcpy(baseOrMemberInitializers, Initializers.data(), 3312 Initializers.size() * sizeof(CXXCtorInitializer*)); 3313 Constructor->setCtorInitializers(baseOrMemberInitializers); 3314 } 3315 3316 // Let template instantiation know whether we had errors. 3317 if (AnyErrors) 3318 Constructor->setInvalidDecl(); 3319 3320 return false; 3321 } 3322 3323 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3324 3325 // We need to build the initializer AST according to order of construction 3326 // and not what user specified in the Initializers list. 3327 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3328 if (!ClassDecl) 3329 return true; 3330 3331 bool HadError = false; 3332 3333 for (unsigned i = 0; i < Initializers.size(); i++) { 3334 CXXCtorInitializer *Member = Initializers[i]; 3335 3336 if (Member->isBaseInitializer()) 3337 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3338 else 3339 Info.AllBaseFields[Member->getAnyMember()] = Member; 3340 } 3341 3342 // Keep track of the direct virtual bases. 3343 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3344 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3345 E = ClassDecl->bases_end(); I != E; ++I) { 3346 if (I->isVirtual()) 3347 DirectVBases.insert(I); 3348 } 3349 3350 // Push virtual bases before others. 3351 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3352 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3353 3354 if (CXXCtorInitializer *Value 3355 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3356 Info.AllToInit.push_back(Value); 3357 } else if (!AnyErrors) { 3358 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3359 CXXCtorInitializer *CXXBaseInit; 3360 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3361 VBase, IsInheritedVirtualBase, 3362 CXXBaseInit)) { 3363 HadError = true; 3364 continue; 3365 } 3366 3367 Info.AllToInit.push_back(CXXBaseInit); 3368 } 3369 } 3370 3371 // Non-virtual bases. 3372 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3373 E = ClassDecl->bases_end(); Base != E; ++Base) { 3374 // Virtuals are in the virtual base list and already constructed. 3375 if (Base->isVirtual()) 3376 continue; 3377 3378 if (CXXCtorInitializer *Value 3379 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3380 Info.AllToInit.push_back(Value); 3381 } else if (!AnyErrors) { 3382 CXXCtorInitializer *CXXBaseInit; 3383 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3384 Base, /*IsInheritedVirtualBase=*/false, 3385 CXXBaseInit)) { 3386 HadError = true; 3387 continue; 3388 } 3389 3390 Info.AllToInit.push_back(CXXBaseInit); 3391 } 3392 } 3393 3394 // Fields. 3395 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3396 MemEnd = ClassDecl->decls_end(); 3397 Mem != MemEnd; ++Mem) { 3398 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3399 // C++ [class.bit]p2: 3400 // A declaration for a bit-field that omits the identifier declares an 3401 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3402 // initialized. 3403 if (F->isUnnamedBitfield()) 3404 continue; 3405 3406 // If we're not generating the implicit copy/move constructor, then we'll 3407 // handle anonymous struct/union fields based on their individual 3408 // indirect fields. 3409 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3410 continue; 3411 3412 if (CollectFieldInitializer(*this, Info, F)) 3413 HadError = true; 3414 continue; 3415 } 3416 3417 // Beyond this point, we only consider default initialization. 3418 if (Info.isImplicitCopyOrMove()) 3419 continue; 3420 3421 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3422 if (F->getType()->isIncompleteArrayType()) { 3423 assert(ClassDecl->hasFlexibleArrayMember() && 3424 "Incomplete array type is not valid"); 3425 continue; 3426 } 3427 3428 // Initialize each field of an anonymous struct individually. 3429 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3430 HadError = true; 3431 3432 continue; 3433 } 3434 } 3435 3436 unsigned NumInitializers = Info.AllToInit.size(); 3437 if (NumInitializers > 0) { 3438 Constructor->setNumCtorInitializers(NumInitializers); 3439 CXXCtorInitializer **baseOrMemberInitializers = 3440 new (Context) CXXCtorInitializer*[NumInitializers]; 3441 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3442 NumInitializers * sizeof(CXXCtorInitializer*)); 3443 Constructor->setCtorInitializers(baseOrMemberInitializers); 3444 3445 // Constructors implicitly reference the base and member 3446 // destructors. 3447 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3448 Constructor->getParent()); 3449 } 3450 3451 return HadError; 3452} 3453 3454static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3455 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3456 const RecordDecl *RD = RT->getDecl(); 3457 if (RD->isAnonymousStructOrUnion()) { 3458 for (RecordDecl::field_iterator Field = RD->field_begin(), 3459 E = RD->field_end(); Field != E; ++Field) 3460 PopulateKeysForFields(*Field, IdealInits); 3461 return; 3462 } 3463 } 3464 IdealInits.push_back(Field); 3465} 3466 3467static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3468 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3469} 3470 3471static void *GetKeyForMember(ASTContext &Context, 3472 CXXCtorInitializer *Member) { 3473 if (!Member->isAnyMemberInitializer()) 3474 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3475 3476 return Member->getAnyMember(); 3477} 3478 3479static void DiagnoseBaseOrMemInitializerOrder( 3480 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3481 ArrayRef<CXXCtorInitializer *> Inits) { 3482 if (Constructor->getDeclContext()->isDependentContext()) 3483 return; 3484 3485 // Don't check initializers order unless the warning is enabled at the 3486 // location of at least one initializer. 3487 bool ShouldCheckOrder = false; 3488 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3489 CXXCtorInitializer *Init = Inits[InitIndex]; 3490 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3491 Init->getSourceLocation()) 3492 != DiagnosticsEngine::Ignored) { 3493 ShouldCheckOrder = true; 3494 break; 3495 } 3496 } 3497 if (!ShouldCheckOrder) 3498 return; 3499 3500 // Build the list of bases and members in the order that they'll 3501 // actually be initialized. The explicit initializers should be in 3502 // this same order but may be missing things. 3503 SmallVector<const void*, 32> IdealInitKeys; 3504 3505 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3506 3507 // 1. Virtual bases. 3508 for (CXXRecordDecl::base_class_const_iterator VBase = 3509 ClassDecl->vbases_begin(), 3510 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3511 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3512 3513 // 2. Non-virtual bases. 3514 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3515 E = ClassDecl->bases_end(); Base != E; ++Base) { 3516 if (Base->isVirtual()) 3517 continue; 3518 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3519 } 3520 3521 // 3. Direct fields. 3522 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3523 E = ClassDecl->field_end(); Field != E; ++Field) { 3524 if (Field->isUnnamedBitfield()) 3525 continue; 3526 3527 PopulateKeysForFields(*Field, IdealInitKeys); 3528 } 3529 3530 unsigned NumIdealInits = IdealInitKeys.size(); 3531 unsigned IdealIndex = 0; 3532 3533 CXXCtorInitializer *PrevInit = 0; 3534 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3535 CXXCtorInitializer *Init = Inits[InitIndex]; 3536 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3537 3538 // Scan forward to try to find this initializer in the idealized 3539 // initializers list. 3540 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3541 if (InitKey == IdealInitKeys[IdealIndex]) 3542 break; 3543 3544 // If we didn't find this initializer, it must be because we 3545 // scanned past it on a previous iteration. That can only 3546 // happen if we're out of order; emit a warning. 3547 if (IdealIndex == NumIdealInits && PrevInit) { 3548 Sema::SemaDiagnosticBuilder D = 3549 SemaRef.Diag(PrevInit->getSourceLocation(), 3550 diag::warn_initializer_out_of_order); 3551 3552 if (PrevInit->isAnyMemberInitializer()) 3553 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3554 else 3555 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3556 3557 if (Init->isAnyMemberInitializer()) 3558 D << 0 << Init->getAnyMember()->getDeclName(); 3559 else 3560 D << 1 << Init->getTypeSourceInfo()->getType(); 3561 3562 // Move back to the initializer's location in the ideal list. 3563 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3564 if (InitKey == IdealInitKeys[IdealIndex]) 3565 break; 3566 3567 assert(IdealIndex != NumIdealInits && 3568 "initializer not found in initializer list"); 3569 } 3570 3571 PrevInit = Init; 3572 } 3573} 3574 3575namespace { 3576bool CheckRedundantInit(Sema &S, 3577 CXXCtorInitializer *Init, 3578 CXXCtorInitializer *&PrevInit) { 3579 if (!PrevInit) { 3580 PrevInit = Init; 3581 return false; 3582 } 3583 3584 if (FieldDecl *Field = Init->getAnyMember()) 3585 S.Diag(Init->getSourceLocation(), 3586 diag::err_multiple_mem_initialization) 3587 << Field->getDeclName() 3588 << Init->getSourceRange(); 3589 else { 3590 const Type *BaseClass = Init->getBaseClass(); 3591 assert(BaseClass && "neither field nor base"); 3592 S.Diag(Init->getSourceLocation(), 3593 diag::err_multiple_base_initialization) 3594 << QualType(BaseClass, 0) 3595 << Init->getSourceRange(); 3596 } 3597 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3598 << 0 << PrevInit->getSourceRange(); 3599 3600 return true; 3601} 3602 3603typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3604typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3605 3606bool CheckRedundantUnionInit(Sema &S, 3607 CXXCtorInitializer *Init, 3608 RedundantUnionMap &Unions) { 3609 FieldDecl *Field = Init->getAnyMember(); 3610 RecordDecl *Parent = Field->getParent(); 3611 NamedDecl *Child = Field; 3612 3613 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3614 if (Parent->isUnion()) { 3615 UnionEntry &En = Unions[Parent]; 3616 if (En.first && En.first != Child) { 3617 S.Diag(Init->getSourceLocation(), 3618 diag::err_multiple_mem_union_initialization) 3619 << Field->getDeclName() 3620 << Init->getSourceRange(); 3621 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3622 << 0 << En.second->getSourceRange(); 3623 return true; 3624 } 3625 if (!En.first) { 3626 En.first = Child; 3627 En.second = Init; 3628 } 3629 if (!Parent->isAnonymousStructOrUnion()) 3630 return false; 3631 } 3632 3633 Child = Parent; 3634 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3635 } 3636 3637 return false; 3638} 3639} 3640 3641/// ActOnMemInitializers - Handle the member initializers for a constructor. 3642void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3643 SourceLocation ColonLoc, 3644 ArrayRef<CXXCtorInitializer*> MemInits, 3645 bool AnyErrors) { 3646 if (!ConstructorDecl) 3647 return; 3648 3649 AdjustDeclIfTemplate(ConstructorDecl); 3650 3651 CXXConstructorDecl *Constructor 3652 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3653 3654 if (!Constructor) { 3655 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3656 return; 3657 } 3658 3659 // Mapping for the duplicate initializers check. 3660 // For member initializers, this is keyed with a FieldDecl*. 3661 // For base initializers, this is keyed with a Type*. 3662 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3663 3664 // Mapping for the inconsistent anonymous-union initializers check. 3665 RedundantUnionMap MemberUnions; 3666 3667 bool HadError = false; 3668 for (unsigned i = 0; i < MemInits.size(); i++) { 3669 CXXCtorInitializer *Init = MemInits[i]; 3670 3671 // Set the source order index. 3672 Init->setSourceOrder(i); 3673 3674 if (Init->isAnyMemberInitializer()) { 3675 FieldDecl *Field = Init->getAnyMember(); 3676 if (CheckRedundantInit(*this, Init, Members[Field]) || 3677 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3678 HadError = true; 3679 } else if (Init->isBaseInitializer()) { 3680 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3681 if (CheckRedundantInit(*this, Init, Members[Key])) 3682 HadError = true; 3683 } else { 3684 assert(Init->isDelegatingInitializer()); 3685 // This must be the only initializer 3686 if (MemInits.size() != 1) { 3687 Diag(Init->getSourceLocation(), 3688 diag::err_delegating_initializer_alone) 3689 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3690 // We will treat this as being the only initializer. 3691 } 3692 SetDelegatingInitializer(Constructor, MemInits[i]); 3693 // Return immediately as the initializer is set. 3694 return; 3695 } 3696 } 3697 3698 if (HadError) 3699 return; 3700 3701 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3702 3703 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3704} 3705 3706void 3707Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3708 CXXRecordDecl *ClassDecl) { 3709 // Ignore dependent contexts. Also ignore unions, since their members never 3710 // have destructors implicitly called. 3711 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3712 return; 3713 3714 // FIXME: all the access-control diagnostics are positioned on the 3715 // field/base declaration. That's probably good; that said, the 3716 // user might reasonably want to know why the destructor is being 3717 // emitted, and we currently don't say. 3718 3719 // Non-static data members. 3720 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3721 E = ClassDecl->field_end(); I != E; ++I) { 3722 FieldDecl *Field = *I; 3723 if (Field->isInvalidDecl()) 3724 continue; 3725 3726 // Don't destroy incomplete or zero-length arrays. 3727 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3728 continue; 3729 3730 QualType FieldType = Context.getBaseElementType(Field->getType()); 3731 3732 const RecordType* RT = FieldType->getAs<RecordType>(); 3733 if (!RT) 3734 continue; 3735 3736 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3737 if (FieldClassDecl->isInvalidDecl()) 3738 continue; 3739 if (FieldClassDecl->hasIrrelevantDestructor()) 3740 continue; 3741 // The destructor for an implicit anonymous union member is never invoked. 3742 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3743 continue; 3744 3745 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3746 assert(Dtor && "No dtor found for FieldClassDecl!"); 3747 CheckDestructorAccess(Field->getLocation(), Dtor, 3748 PDiag(diag::err_access_dtor_field) 3749 << Field->getDeclName() 3750 << FieldType); 3751 3752 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3753 DiagnoseUseOfDecl(Dtor, Location); 3754 } 3755 3756 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3757 3758 // Bases. 3759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3760 E = ClassDecl->bases_end(); Base != E; ++Base) { 3761 // Bases are always records in a well-formed non-dependent class. 3762 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3763 3764 // Remember direct virtual bases. 3765 if (Base->isVirtual()) 3766 DirectVirtualBases.insert(RT); 3767 3768 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3769 // If our base class is invalid, we probably can't get its dtor anyway. 3770 if (BaseClassDecl->isInvalidDecl()) 3771 continue; 3772 if (BaseClassDecl->hasIrrelevantDestructor()) 3773 continue; 3774 3775 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3776 assert(Dtor && "No dtor found for BaseClassDecl!"); 3777 3778 // FIXME: caret should be on the start of the class name 3779 CheckDestructorAccess(Base->getLocStart(), Dtor, 3780 PDiag(diag::err_access_dtor_base) 3781 << Base->getType() 3782 << Base->getSourceRange(), 3783 Context.getTypeDeclType(ClassDecl)); 3784 3785 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3786 DiagnoseUseOfDecl(Dtor, Location); 3787 } 3788 3789 // Virtual bases. 3790 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3791 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3792 3793 // Bases are always records in a well-formed non-dependent class. 3794 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3795 3796 // Ignore direct virtual bases. 3797 if (DirectVirtualBases.count(RT)) 3798 continue; 3799 3800 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3801 // If our base class is invalid, we probably can't get its dtor anyway. 3802 if (BaseClassDecl->isInvalidDecl()) 3803 continue; 3804 if (BaseClassDecl->hasIrrelevantDestructor()) 3805 continue; 3806 3807 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3808 assert(Dtor && "No dtor found for BaseClassDecl!"); 3809 if (CheckDestructorAccess( 3810 ClassDecl->getLocation(), Dtor, 3811 PDiag(diag::err_access_dtor_vbase) 3812 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 3813 Context.getTypeDeclType(ClassDecl)) == 3814 AR_accessible) { 3815 CheckDerivedToBaseConversion( 3816 Context.getTypeDeclType(ClassDecl), VBase->getType(), 3817 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 3818 SourceRange(), DeclarationName(), 0); 3819 } 3820 3821 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3822 DiagnoseUseOfDecl(Dtor, Location); 3823 } 3824} 3825 3826void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3827 if (!CDtorDecl) 3828 return; 3829 3830 if (CXXConstructorDecl *Constructor 3831 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3832 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3833} 3834 3835bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3836 unsigned DiagID, AbstractDiagSelID SelID) { 3837 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3838 unsigned DiagID; 3839 AbstractDiagSelID SelID; 3840 3841 public: 3842 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3843 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3844 3845 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3846 if (Suppressed) return; 3847 if (SelID == -1) 3848 S.Diag(Loc, DiagID) << T; 3849 else 3850 S.Diag(Loc, DiagID) << SelID << T; 3851 } 3852 } Diagnoser(DiagID, SelID); 3853 3854 return RequireNonAbstractType(Loc, T, Diagnoser); 3855} 3856 3857bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3858 TypeDiagnoser &Diagnoser) { 3859 if (!getLangOpts().CPlusPlus) 3860 return false; 3861 3862 if (const ArrayType *AT = Context.getAsArrayType(T)) 3863 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3864 3865 if (const PointerType *PT = T->getAs<PointerType>()) { 3866 // Find the innermost pointer type. 3867 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3868 PT = T; 3869 3870 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3871 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3872 } 3873 3874 const RecordType *RT = T->getAs<RecordType>(); 3875 if (!RT) 3876 return false; 3877 3878 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3879 3880 // We can't answer whether something is abstract until it has a 3881 // definition. If it's currently being defined, we'll walk back 3882 // over all the declarations when we have a full definition. 3883 const CXXRecordDecl *Def = RD->getDefinition(); 3884 if (!Def || Def->isBeingDefined()) 3885 return false; 3886 3887 if (!RD->isAbstract()) 3888 return false; 3889 3890 Diagnoser.diagnose(*this, Loc, T); 3891 DiagnoseAbstractType(RD); 3892 3893 return true; 3894} 3895 3896void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3897 // Check if we've already emitted the list of pure virtual functions 3898 // for this class. 3899 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3900 return; 3901 3902 CXXFinalOverriderMap FinalOverriders; 3903 RD->getFinalOverriders(FinalOverriders); 3904 3905 // Keep a set of seen pure methods so we won't diagnose the same method 3906 // more than once. 3907 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3908 3909 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3910 MEnd = FinalOverriders.end(); 3911 M != MEnd; 3912 ++M) { 3913 for (OverridingMethods::iterator SO = M->second.begin(), 3914 SOEnd = M->second.end(); 3915 SO != SOEnd; ++SO) { 3916 // C++ [class.abstract]p4: 3917 // A class is abstract if it contains or inherits at least one 3918 // pure virtual function for which the final overrider is pure 3919 // virtual. 3920 3921 // 3922 if (SO->second.size() != 1) 3923 continue; 3924 3925 if (!SO->second.front().Method->isPure()) 3926 continue; 3927 3928 if (!SeenPureMethods.insert(SO->second.front().Method)) 3929 continue; 3930 3931 Diag(SO->second.front().Method->getLocation(), 3932 diag::note_pure_virtual_function) 3933 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3934 } 3935 } 3936 3937 if (!PureVirtualClassDiagSet) 3938 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3939 PureVirtualClassDiagSet->insert(RD); 3940} 3941 3942namespace { 3943struct AbstractUsageInfo { 3944 Sema &S; 3945 CXXRecordDecl *Record; 3946 CanQualType AbstractType; 3947 bool Invalid; 3948 3949 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3950 : S(S), Record(Record), 3951 AbstractType(S.Context.getCanonicalType( 3952 S.Context.getTypeDeclType(Record))), 3953 Invalid(false) {} 3954 3955 void DiagnoseAbstractType() { 3956 if (Invalid) return; 3957 S.DiagnoseAbstractType(Record); 3958 Invalid = true; 3959 } 3960 3961 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3962}; 3963 3964struct CheckAbstractUsage { 3965 AbstractUsageInfo &Info; 3966 const NamedDecl *Ctx; 3967 3968 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3969 : Info(Info), Ctx(Ctx) {} 3970 3971 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3972 switch (TL.getTypeLocClass()) { 3973#define ABSTRACT_TYPELOC(CLASS, PARENT) 3974#define TYPELOC(CLASS, PARENT) \ 3975 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 3976#include "clang/AST/TypeLocNodes.def" 3977 } 3978 } 3979 3980 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3981 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3982 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3983 if (!TL.getArg(I)) 3984 continue; 3985 3986 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3987 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3988 } 3989 } 3990 3991 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3992 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3993 } 3994 3995 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3996 // Visit the type parameters from a permissive context. 3997 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3998 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3999 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4000 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4001 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4002 // TODO: other template argument types? 4003 } 4004 } 4005 4006 // Visit pointee types from a permissive context. 4007#define CheckPolymorphic(Type) \ 4008 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4009 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4010 } 4011 CheckPolymorphic(PointerTypeLoc) 4012 CheckPolymorphic(ReferenceTypeLoc) 4013 CheckPolymorphic(MemberPointerTypeLoc) 4014 CheckPolymorphic(BlockPointerTypeLoc) 4015 CheckPolymorphic(AtomicTypeLoc) 4016 4017 /// Handle all the types we haven't given a more specific 4018 /// implementation for above. 4019 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4020 // Every other kind of type that we haven't called out already 4021 // that has an inner type is either (1) sugar or (2) contains that 4022 // inner type in some way as a subobject. 4023 if (TypeLoc Next = TL.getNextTypeLoc()) 4024 return Visit(Next, Sel); 4025 4026 // If there's no inner type and we're in a permissive context, 4027 // don't diagnose. 4028 if (Sel == Sema::AbstractNone) return; 4029 4030 // Check whether the type matches the abstract type. 4031 QualType T = TL.getType(); 4032 if (T->isArrayType()) { 4033 Sel = Sema::AbstractArrayType; 4034 T = Info.S.Context.getBaseElementType(T); 4035 } 4036 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4037 if (CT != Info.AbstractType) return; 4038 4039 // It matched; do some magic. 4040 if (Sel == Sema::AbstractArrayType) { 4041 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4042 << T << TL.getSourceRange(); 4043 } else { 4044 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4045 << Sel << T << TL.getSourceRange(); 4046 } 4047 Info.DiagnoseAbstractType(); 4048 } 4049}; 4050 4051void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4052 Sema::AbstractDiagSelID Sel) { 4053 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4054} 4055 4056} 4057 4058/// Check for invalid uses of an abstract type in a method declaration. 4059static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4060 CXXMethodDecl *MD) { 4061 // No need to do the check on definitions, which require that 4062 // the return/param types be complete. 4063 if (MD->doesThisDeclarationHaveABody()) 4064 return; 4065 4066 // For safety's sake, just ignore it if we don't have type source 4067 // information. This should never happen for non-implicit methods, 4068 // but... 4069 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4070 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4071} 4072 4073/// Check for invalid uses of an abstract type within a class definition. 4074static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4075 CXXRecordDecl *RD) { 4076 for (CXXRecordDecl::decl_iterator 4077 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4078 Decl *D = *I; 4079 if (D->isImplicit()) continue; 4080 4081 // Methods and method templates. 4082 if (isa<CXXMethodDecl>(D)) { 4083 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4084 } else if (isa<FunctionTemplateDecl>(D)) { 4085 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4086 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4087 4088 // Fields and static variables. 4089 } else if (isa<FieldDecl>(D)) { 4090 FieldDecl *FD = cast<FieldDecl>(D); 4091 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4092 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4093 } else if (isa<VarDecl>(D)) { 4094 VarDecl *VD = cast<VarDecl>(D); 4095 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4096 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4097 4098 // Nested classes and class templates. 4099 } else if (isa<CXXRecordDecl>(D)) { 4100 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4101 } else if (isa<ClassTemplateDecl>(D)) { 4102 CheckAbstractClassUsage(Info, 4103 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4104 } 4105 } 4106} 4107 4108/// \brief Perform semantic checks on a class definition that has been 4109/// completing, introducing implicitly-declared members, checking for 4110/// abstract types, etc. 4111void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4112 if (!Record) 4113 return; 4114 4115 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4116 AbstractUsageInfo Info(*this, Record); 4117 CheckAbstractClassUsage(Info, Record); 4118 } 4119 4120 // If this is not an aggregate type and has no user-declared constructor, 4121 // complain about any non-static data members of reference or const scalar 4122 // type, since they will never get initializers. 4123 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4124 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4125 !Record->isLambda()) { 4126 bool Complained = false; 4127 for (RecordDecl::field_iterator F = Record->field_begin(), 4128 FEnd = Record->field_end(); 4129 F != FEnd; ++F) { 4130 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4131 continue; 4132 4133 if (F->getType()->isReferenceType() || 4134 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4135 if (!Complained) { 4136 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4137 << Record->getTagKind() << Record; 4138 Complained = true; 4139 } 4140 4141 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4142 << F->getType()->isReferenceType() 4143 << F->getDeclName(); 4144 } 4145 } 4146 } 4147 4148 if (Record->isDynamicClass() && !Record->isDependentType()) 4149 DynamicClasses.push_back(Record); 4150 4151 if (Record->getIdentifier()) { 4152 // C++ [class.mem]p13: 4153 // If T is the name of a class, then each of the following shall have a 4154 // name different from T: 4155 // - every member of every anonymous union that is a member of class T. 4156 // 4157 // C++ [class.mem]p14: 4158 // In addition, if class T has a user-declared constructor (12.1), every 4159 // non-static data member of class T shall have a name different from T. 4160 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4161 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4162 ++I) { 4163 NamedDecl *D = *I; 4164 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4165 isa<IndirectFieldDecl>(D)) { 4166 Diag(D->getLocation(), diag::err_member_name_of_class) 4167 << D->getDeclName(); 4168 break; 4169 } 4170 } 4171 } 4172 4173 // Warn if the class has virtual methods but non-virtual public destructor. 4174 if (Record->isPolymorphic() && !Record->isDependentType()) { 4175 CXXDestructorDecl *dtor = Record->getDestructor(); 4176 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4177 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4178 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4179 } 4180 4181 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4182 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4183 DiagnoseAbstractType(Record); 4184 } 4185 4186 if (!Record->isDependentType()) { 4187 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4188 MEnd = Record->method_end(); 4189 M != MEnd; ++M) { 4190 // See if a method overloads virtual methods in a base 4191 // class without overriding any. 4192 if (!M->isStatic()) 4193 DiagnoseHiddenVirtualMethods(Record, *M); 4194 4195 // Check whether the explicitly-defaulted special members are valid. 4196 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4197 CheckExplicitlyDefaultedSpecialMember(*M); 4198 4199 // For an explicitly defaulted or deleted special member, we defer 4200 // determining triviality until the class is complete. That time is now! 4201 if (!M->isImplicit() && !M->isUserProvided()) { 4202 CXXSpecialMember CSM = getSpecialMember(*M); 4203 if (CSM != CXXInvalid) { 4204 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4205 4206 // Inform the class that we've finished declaring this member. 4207 Record->finishedDefaultedOrDeletedMember(*M); 4208 } 4209 } 4210 } 4211 } 4212 4213 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4214 // function that is not a constructor declares that member function to be 4215 // const. [...] The class of which that function is a member shall be 4216 // a literal type. 4217 // 4218 // If the class has virtual bases, any constexpr members will already have 4219 // been diagnosed by the checks performed on the member declaration, so 4220 // suppress this (less useful) diagnostic. 4221 // 4222 // We delay this until we know whether an explicitly-defaulted (or deleted) 4223 // destructor for the class is trivial. 4224 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4225 !Record->isLiteral() && !Record->getNumVBases()) { 4226 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4227 MEnd = Record->method_end(); 4228 M != MEnd; ++M) { 4229 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4230 switch (Record->getTemplateSpecializationKind()) { 4231 case TSK_ImplicitInstantiation: 4232 case TSK_ExplicitInstantiationDeclaration: 4233 case TSK_ExplicitInstantiationDefinition: 4234 // If a template instantiates to a non-literal type, but its members 4235 // instantiate to constexpr functions, the template is technically 4236 // ill-formed, but we allow it for sanity. 4237 continue; 4238 4239 case TSK_Undeclared: 4240 case TSK_ExplicitSpecialization: 4241 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4242 diag::err_constexpr_method_non_literal); 4243 break; 4244 } 4245 4246 // Only produce one error per class. 4247 break; 4248 } 4249 } 4250 } 4251 4252 // Declare inheriting constructors. We do this eagerly here because: 4253 // - The standard requires an eager diagnostic for conflicting inheriting 4254 // constructors from different classes. 4255 // - The lazy declaration of the other implicit constructors is so as to not 4256 // waste space and performance on classes that are not meant to be 4257 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4258 // have inheriting constructors. 4259 DeclareInheritingConstructors(Record); 4260} 4261 4262/// Is the special member function which would be selected to perform the 4263/// specified operation on the specified class type a constexpr constructor? 4264static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4265 Sema::CXXSpecialMember CSM, 4266 bool ConstArg) { 4267 Sema::SpecialMemberOverloadResult *SMOR = 4268 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4269 false, false, false, false); 4270 if (!SMOR || !SMOR->getMethod()) 4271 // A constructor we wouldn't select can't be "involved in initializing" 4272 // anything. 4273 return true; 4274 return SMOR->getMethod()->isConstexpr(); 4275} 4276 4277/// Determine whether the specified special member function would be constexpr 4278/// if it were implicitly defined. 4279static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4280 Sema::CXXSpecialMember CSM, 4281 bool ConstArg) { 4282 if (!S.getLangOpts().CPlusPlus11) 4283 return false; 4284 4285 // C++11 [dcl.constexpr]p4: 4286 // In the definition of a constexpr constructor [...] 4287 bool Ctor = true; 4288 switch (CSM) { 4289 case Sema::CXXDefaultConstructor: 4290 // Since default constructor lookup is essentially trivial (and cannot 4291 // involve, for instance, template instantiation), we compute whether a 4292 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4293 // 4294 // This is important for performance; we need to know whether the default 4295 // constructor is constexpr to determine whether the type is a literal type. 4296 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4297 4298 case Sema::CXXCopyConstructor: 4299 case Sema::CXXMoveConstructor: 4300 // For copy or move constructors, we need to perform overload resolution. 4301 break; 4302 4303 case Sema::CXXCopyAssignment: 4304 case Sema::CXXMoveAssignment: 4305 if (!S.getLangOpts().CPlusPlus1y) 4306 return false; 4307 // In C++1y, we need to perform overload resolution. 4308 Ctor = false; 4309 break; 4310 4311 case Sema::CXXDestructor: 4312 case Sema::CXXInvalid: 4313 return false; 4314 } 4315 4316 // -- if the class is a non-empty union, or for each non-empty anonymous 4317 // union member of a non-union class, exactly one non-static data member 4318 // shall be initialized; [DR1359] 4319 // 4320 // If we squint, this is guaranteed, since exactly one non-static data member 4321 // will be initialized (if the constructor isn't deleted), we just don't know 4322 // which one. 4323 if (Ctor && ClassDecl->isUnion()) 4324 return true; 4325 4326 // -- the class shall not have any virtual base classes; 4327 if (Ctor && ClassDecl->getNumVBases()) 4328 return false; 4329 4330 // C++1y [class.copy]p26: 4331 // -- [the class] is a literal type, and 4332 if (!Ctor && !ClassDecl->isLiteral()) 4333 return false; 4334 4335 // -- every constructor involved in initializing [...] base class 4336 // sub-objects shall be a constexpr constructor; 4337 // -- the assignment operator selected to copy/move each direct base 4338 // class is a constexpr function, and 4339 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4340 BEnd = ClassDecl->bases_end(); 4341 B != BEnd; ++B) { 4342 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4343 if (!BaseType) continue; 4344 4345 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4346 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4347 return false; 4348 } 4349 4350 // -- every constructor involved in initializing non-static data members 4351 // [...] shall be a constexpr constructor; 4352 // -- every non-static data member and base class sub-object shall be 4353 // initialized 4354 // -- for each non-stastic data member of X that is of class type (or array 4355 // thereof), the assignment operator selected to copy/move that member is 4356 // a constexpr function 4357 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4358 FEnd = ClassDecl->field_end(); 4359 F != FEnd; ++F) { 4360 if (F->isInvalidDecl()) 4361 continue; 4362 if (const RecordType *RecordTy = 4363 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4364 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4365 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4366 return false; 4367 } 4368 } 4369 4370 // All OK, it's constexpr! 4371 return true; 4372} 4373 4374static Sema::ImplicitExceptionSpecification 4375computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4376 switch (S.getSpecialMember(MD)) { 4377 case Sema::CXXDefaultConstructor: 4378 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4379 case Sema::CXXCopyConstructor: 4380 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4381 case Sema::CXXCopyAssignment: 4382 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4383 case Sema::CXXMoveConstructor: 4384 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4385 case Sema::CXXMoveAssignment: 4386 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4387 case Sema::CXXDestructor: 4388 return S.ComputeDefaultedDtorExceptionSpec(MD); 4389 case Sema::CXXInvalid: 4390 break; 4391 } 4392 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4393 "only special members have implicit exception specs"); 4394 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4395} 4396 4397static void 4398updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4399 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4400 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4401 ExceptSpec.getEPI(EPI); 4402 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4403 FPT->getArgTypes(), EPI)); 4404} 4405 4406void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4407 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4408 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4409 return; 4410 4411 // Evaluate the exception specification. 4412 ImplicitExceptionSpecification ExceptSpec = 4413 computeImplicitExceptionSpec(*this, Loc, MD); 4414 4415 // Update the type of the special member to use it. 4416 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4417 4418 // A user-provided destructor can be defined outside the class. When that 4419 // happens, be sure to update the exception specification on both 4420 // declarations. 4421 const FunctionProtoType *CanonicalFPT = 4422 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4423 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4424 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4425 CanonicalFPT, ExceptSpec); 4426} 4427 4428void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4429 CXXRecordDecl *RD = MD->getParent(); 4430 CXXSpecialMember CSM = getSpecialMember(MD); 4431 4432 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4433 "not an explicitly-defaulted special member"); 4434 4435 // Whether this was the first-declared instance of the constructor. 4436 // This affects whether we implicitly add an exception spec and constexpr. 4437 bool First = MD == MD->getCanonicalDecl(); 4438 4439 bool HadError = false; 4440 4441 // C++11 [dcl.fct.def.default]p1: 4442 // A function that is explicitly defaulted shall 4443 // -- be a special member function (checked elsewhere), 4444 // -- have the same type (except for ref-qualifiers, and except that a 4445 // copy operation can take a non-const reference) as an implicit 4446 // declaration, and 4447 // -- not have default arguments. 4448 unsigned ExpectedParams = 1; 4449 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4450 ExpectedParams = 0; 4451 if (MD->getNumParams() != ExpectedParams) { 4452 // This also checks for default arguments: a copy or move constructor with a 4453 // default argument is classified as a default constructor, and assignment 4454 // operations and destructors can't have default arguments. 4455 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4456 << CSM << MD->getSourceRange(); 4457 HadError = true; 4458 } else if (MD->isVariadic()) { 4459 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4460 << CSM << MD->getSourceRange(); 4461 HadError = true; 4462 } 4463 4464 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4465 4466 bool CanHaveConstParam = false; 4467 if (CSM == CXXCopyConstructor) 4468 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4469 else if (CSM == CXXCopyAssignment) 4470 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4471 4472 QualType ReturnType = Context.VoidTy; 4473 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4474 // Check for return type matching. 4475 ReturnType = Type->getResultType(); 4476 QualType ExpectedReturnType = 4477 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4478 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4479 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4480 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4481 HadError = true; 4482 } 4483 4484 // A defaulted special member cannot have cv-qualifiers. 4485 if (Type->getTypeQuals()) { 4486 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4487 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4488 HadError = true; 4489 } 4490 } 4491 4492 // Check for parameter type matching. 4493 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4494 bool HasConstParam = false; 4495 if (ExpectedParams && ArgType->isReferenceType()) { 4496 // Argument must be reference to possibly-const T. 4497 QualType ReferentType = ArgType->getPointeeType(); 4498 HasConstParam = ReferentType.isConstQualified(); 4499 4500 if (ReferentType.isVolatileQualified()) { 4501 Diag(MD->getLocation(), 4502 diag::err_defaulted_special_member_volatile_param) << CSM; 4503 HadError = true; 4504 } 4505 4506 if (HasConstParam && !CanHaveConstParam) { 4507 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4508 Diag(MD->getLocation(), 4509 diag::err_defaulted_special_member_copy_const_param) 4510 << (CSM == CXXCopyAssignment); 4511 // FIXME: Explain why this special member can't be const. 4512 } else { 4513 Diag(MD->getLocation(), 4514 diag::err_defaulted_special_member_move_const_param) 4515 << (CSM == CXXMoveAssignment); 4516 } 4517 HadError = true; 4518 } 4519 } else if (ExpectedParams) { 4520 // A copy assignment operator can take its argument by value, but a 4521 // defaulted one cannot. 4522 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4523 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4524 HadError = true; 4525 } 4526 4527 // C++11 [dcl.fct.def.default]p2: 4528 // An explicitly-defaulted function may be declared constexpr only if it 4529 // would have been implicitly declared as constexpr, 4530 // Do not apply this rule to members of class templates, since core issue 1358 4531 // makes such functions always instantiate to constexpr functions. For 4532 // functions which cannot be constexpr (for non-constructors in C++11 and for 4533 // destructors in C++1y), this is checked elsewhere. 4534 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4535 HasConstParam); 4536 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4537 : isa<CXXConstructorDecl>(MD)) && 4538 MD->isConstexpr() && !Constexpr && 4539 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4540 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4541 // FIXME: Explain why the special member can't be constexpr. 4542 HadError = true; 4543 } 4544 4545 // and may have an explicit exception-specification only if it is compatible 4546 // with the exception-specification on the implicit declaration. 4547 if (Type->hasExceptionSpec()) { 4548 // Delay the check if this is the first declaration of the special member, 4549 // since we may not have parsed some necessary in-class initializers yet. 4550 if (First) { 4551 // If the exception specification needs to be instantiated, do so now, 4552 // before we clobber it with an EST_Unevaluated specification below. 4553 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4554 InstantiateExceptionSpec(MD->getLocStart(), MD); 4555 Type = MD->getType()->getAs<FunctionProtoType>(); 4556 } 4557 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4558 } else 4559 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4560 } 4561 4562 // If a function is explicitly defaulted on its first declaration, 4563 if (First) { 4564 // -- it is implicitly considered to be constexpr if the implicit 4565 // definition would be, 4566 MD->setConstexpr(Constexpr); 4567 4568 // -- it is implicitly considered to have the same exception-specification 4569 // as if it had been implicitly declared, 4570 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4571 EPI.ExceptionSpecType = EST_Unevaluated; 4572 EPI.ExceptionSpecDecl = MD; 4573 MD->setType(Context.getFunctionType(ReturnType, 4574 ArrayRef<QualType>(&ArgType, 4575 ExpectedParams), 4576 EPI)); 4577 } 4578 4579 if (ShouldDeleteSpecialMember(MD, CSM)) { 4580 if (First) { 4581 SetDeclDeleted(MD, MD->getLocation()); 4582 } else { 4583 // C++11 [dcl.fct.def.default]p4: 4584 // [For a] user-provided explicitly-defaulted function [...] if such a 4585 // function is implicitly defined as deleted, the program is ill-formed. 4586 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4587 HadError = true; 4588 } 4589 } 4590 4591 if (HadError) 4592 MD->setInvalidDecl(); 4593} 4594 4595/// Check whether the exception specification provided for an 4596/// explicitly-defaulted special member matches the exception specification 4597/// that would have been generated for an implicit special member, per 4598/// C++11 [dcl.fct.def.default]p2. 4599void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4600 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4601 // Compute the implicit exception specification. 4602 FunctionProtoType::ExtProtoInfo EPI; 4603 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4604 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4605 Context.getFunctionType(Context.VoidTy, None, EPI)); 4606 4607 // Ensure that it matches. 4608 CheckEquivalentExceptionSpec( 4609 PDiag(diag::err_incorrect_defaulted_exception_spec) 4610 << getSpecialMember(MD), PDiag(), 4611 ImplicitType, SourceLocation(), 4612 SpecifiedType, MD->getLocation()); 4613} 4614 4615void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4616 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4617 I != N; ++I) 4618 CheckExplicitlyDefaultedMemberExceptionSpec( 4619 DelayedDefaultedMemberExceptionSpecs[I].first, 4620 DelayedDefaultedMemberExceptionSpecs[I].second); 4621 4622 DelayedDefaultedMemberExceptionSpecs.clear(); 4623} 4624 4625namespace { 4626struct SpecialMemberDeletionInfo { 4627 Sema &S; 4628 CXXMethodDecl *MD; 4629 Sema::CXXSpecialMember CSM; 4630 bool Diagnose; 4631 4632 // Properties of the special member, computed for convenience. 4633 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4634 SourceLocation Loc; 4635 4636 bool AllFieldsAreConst; 4637 4638 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4639 Sema::CXXSpecialMember CSM, bool Diagnose) 4640 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4641 IsConstructor(false), IsAssignment(false), IsMove(false), 4642 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4643 AllFieldsAreConst(true) { 4644 switch (CSM) { 4645 case Sema::CXXDefaultConstructor: 4646 case Sema::CXXCopyConstructor: 4647 IsConstructor = true; 4648 break; 4649 case Sema::CXXMoveConstructor: 4650 IsConstructor = true; 4651 IsMove = true; 4652 break; 4653 case Sema::CXXCopyAssignment: 4654 IsAssignment = true; 4655 break; 4656 case Sema::CXXMoveAssignment: 4657 IsAssignment = true; 4658 IsMove = true; 4659 break; 4660 case Sema::CXXDestructor: 4661 break; 4662 case Sema::CXXInvalid: 4663 llvm_unreachable("invalid special member kind"); 4664 } 4665 4666 if (MD->getNumParams()) { 4667 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4668 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4669 } 4670 } 4671 4672 bool inUnion() const { return MD->getParent()->isUnion(); } 4673 4674 /// Look up the corresponding special member in the given class. 4675 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4676 unsigned Quals) { 4677 unsigned TQ = MD->getTypeQualifiers(); 4678 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4679 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4680 Quals = 0; 4681 return S.LookupSpecialMember(Class, CSM, 4682 ConstArg || (Quals & Qualifiers::Const), 4683 VolatileArg || (Quals & Qualifiers::Volatile), 4684 MD->getRefQualifier() == RQ_RValue, 4685 TQ & Qualifiers::Const, 4686 TQ & Qualifiers::Volatile); 4687 } 4688 4689 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4690 4691 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4692 bool shouldDeleteForField(FieldDecl *FD); 4693 bool shouldDeleteForAllConstMembers(); 4694 4695 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4696 unsigned Quals); 4697 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4698 Sema::SpecialMemberOverloadResult *SMOR, 4699 bool IsDtorCallInCtor); 4700 4701 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4702}; 4703} 4704 4705/// Is the given special member inaccessible when used on the given 4706/// sub-object. 4707bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4708 CXXMethodDecl *target) { 4709 /// If we're operating on a base class, the object type is the 4710 /// type of this special member. 4711 QualType objectTy; 4712 AccessSpecifier access = target->getAccess(); 4713 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4714 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4715 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4716 4717 // If we're operating on a field, the object type is the type of the field. 4718 } else { 4719 objectTy = S.Context.getTypeDeclType(target->getParent()); 4720 } 4721 4722 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4723} 4724 4725/// Check whether we should delete a special member due to the implicit 4726/// definition containing a call to a special member of a subobject. 4727bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4728 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4729 bool IsDtorCallInCtor) { 4730 CXXMethodDecl *Decl = SMOR->getMethod(); 4731 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4732 4733 int DiagKind = -1; 4734 4735 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4736 DiagKind = !Decl ? 0 : 1; 4737 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4738 DiagKind = 2; 4739 else if (!isAccessible(Subobj, Decl)) 4740 DiagKind = 3; 4741 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4742 !Decl->isTrivial()) { 4743 // A member of a union must have a trivial corresponding special member. 4744 // As a weird special case, a destructor call from a union's constructor 4745 // must be accessible and non-deleted, but need not be trivial. Such a 4746 // destructor is never actually called, but is semantically checked as 4747 // if it were. 4748 DiagKind = 4; 4749 } 4750 4751 if (DiagKind == -1) 4752 return false; 4753 4754 if (Diagnose) { 4755 if (Field) { 4756 S.Diag(Field->getLocation(), 4757 diag::note_deleted_special_member_class_subobject) 4758 << CSM << MD->getParent() << /*IsField*/true 4759 << Field << DiagKind << IsDtorCallInCtor; 4760 } else { 4761 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4762 S.Diag(Base->getLocStart(), 4763 diag::note_deleted_special_member_class_subobject) 4764 << CSM << MD->getParent() << /*IsField*/false 4765 << Base->getType() << DiagKind << IsDtorCallInCtor; 4766 } 4767 4768 if (DiagKind == 1) 4769 S.NoteDeletedFunction(Decl); 4770 // FIXME: Explain inaccessibility if DiagKind == 3. 4771 } 4772 4773 return true; 4774} 4775 4776/// Check whether we should delete a special member function due to having a 4777/// direct or virtual base class or non-static data member of class type M. 4778bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4779 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4780 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4781 4782 // C++11 [class.ctor]p5: 4783 // -- any direct or virtual base class, or non-static data member with no 4784 // brace-or-equal-initializer, has class type M (or array thereof) and 4785 // either M has no default constructor or overload resolution as applied 4786 // to M's default constructor results in an ambiguity or in a function 4787 // that is deleted or inaccessible 4788 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4789 // -- a direct or virtual base class B that cannot be copied/moved because 4790 // overload resolution, as applied to B's corresponding special member, 4791 // results in an ambiguity or a function that is deleted or inaccessible 4792 // from the defaulted special member 4793 // C++11 [class.dtor]p5: 4794 // -- any direct or virtual base class [...] has a type with a destructor 4795 // that is deleted or inaccessible 4796 if (!(CSM == Sema::CXXDefaultConstructor && 4797 Field && Field->hasInClassInitializer()) && 4798 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4799 return true; 4800 4801 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4802 // -- any direct or virtual base class or non-static data member has a 4803 // type with a destructor that is deleted or inaccessible 4804 if (IsConstructor) { 4805 Sema::SpecialMemberOverloadResult *SMOR = 4806 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4807 false, false, false, false, false); 4808 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4809 return true; 4810 } 4811 4812 return false; 4813} 4814 4815/// Check whether we should delete a special member function due to the class 4816/// having a particular direct or virtual base class. 4817bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4818 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4819 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4820} 4821 4822/// Check whether we should delete a special member function due to the class 4823/// having a particular non-static data member. 4824bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4825 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4826 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4827 4828 if (CSM == Sema::CXXDefaultConstructor) { 4829 // For a default constructor, all references must be initialized in-class 4830 // and, if a union, it must have a non-const member. 4831 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4832 if (Diagnose) 4833 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4834 << MD->getParent() << FD << FieldType << /*Reference*/0; 4835 return true; 4836 } 4837 // C++11 [class.ctor]p5: any non-variant non-static data member of 4838 // const-qualified type (or array thereof) with no 4839 // brace-or-equal-initializer does not have a user-provided default 4840 // constructor. 4841 if (!inUnion() && FieldType.isConstQualified() && 4842 !FD->hasInClassInitializer() && 4843 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4844 if (Diagnose) 4845 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4846 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4847 return true; 4848 } 4849 4850 if (inUnion() && !FieldType.isConstQualified()) 4851 AllFieldsAreConst = false; 4852 } else if (CSM == Sema::CXXCopyConstructor) { 4853 // For a copy constructor, data members must not be of rvalue reference 4854 // type. 4855 if (FieldType->isRValueReferenceType()) { 4856 if (Diagnose) 4857 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4858 << MD->getParent() << FD << FieldType; 4859 return true; 4860 } 4861 } else if (IsAssignment) { 4862 // For an assignment operator, data members must not be of reference type. 4863 if (FieldType->isReferenceType()) { 4864 if (Diagnose) 4865 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4866 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4867 return true; 4868 } 4869 if (!FieldRecord && FieldType.isConstQualified()) { 4870 // C++11 [class.copy]p23: 4871 // -- a non-static data member of const non-class type (or array thereof) 4872 if (Diagnose) 4873 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4874 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4875 return true; 4876 } 4877 } 4878 4879 if (FieldRecord) { 4880 // Some additional restrictions exist on the variant members. 4881 if (!inUnion() && FieldRecord->isUnion() && 4882 FieldRecord->isAnonymousStructOrUnion()) { 4883 bool AllVariantFieldsAreConst = true; 4884 4885 // FIXME: Handle anonymous unions declared within anonymous unions. 4886 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4887 UE = FieldRecord->field_end(); 4888 UI != UE; ++UI) { 4889 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4890 4891 if (!UnionFieldType.isConstQualified()) 4892 AllVariantFieldsAreConst = false; 4893 4894 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4895 if (UnionFieldRecord && 4896 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4897 UnionFieldType.getCVRQualifiers())) 4898 return true; 4899 } 4900 4901 // At least one member in each anonymous union must be non-const 4902 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4903 FieldRecord->field_begin() != FieldRecord->field_end()) { 4904 if (Diagnose) 4905 S.Diag(FieldRecord->getLocation(), 4906 diag::note_deleted_default_ctor_all_const) 4907 << MD->getParent() << /*anonymous union*/1; 4908 return true; 4909 } 4910 4911 // Don't check the implicit member of the anonymous union type. 4912 // This is technically non-conformant, but sanity demands it. 4913 return false; 4914 } 4915 4916 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4917 FieldType.getCVRQualifiers())) 4918 return true; 4919 } 4920 4921 return false; 4922} 4923 4924/// C++11 [class.ctor] p5: 4925/// A defaulted default constructor for a class X is defined as deleted if 4926/// X is a union and all of its variant members are of const-qualified type. 4927bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4928 // This is a silly definition, because it gives an empty union a deleted 4929 // default constructor. Don't do that. 4930 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4931 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4932 if (Diagnose) 4933 S.Diag(MD->getParent()->getLocation(), 4934 diag::note_deleted_default_ctor_all_const) 4935 << MD->getParent() << /*not anonymous union*/0; 4936 return true; 4937 } 4938 return false; 4939} 4940 4941/// Determine whether a defaulted special member function should be defined as 4942/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4943/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4944bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4945 bool Diagnose) { 4946 if (MD->isInvalidDecl()) 4947 return false; 4948 CXXRecordDecl *RD = MD->getParent(); 4949 assert(!RD->isDependentType() && "do deletion after instantiation"); 4950 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4951 return false; 4952 4953 // C++11 [expr.lambda.prim]p19: 4954 // The closure type associated with a lambda-expression has a 4955 // deleted (8.4.3) default constructor and a deleted copy 4956 // assignment operator. 4957 if (RD->isLambda() && 4958 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4959 if (Diagnose) 4960 Diag(RD->getLocation(), diag::note_lambda_decl); 4961 return true; 4962 } 4963 4964 // For an anonymous struct or union, the copy and assignment special members 4965 // will never be used, so skip the check. For an anonymous union declared at 4966 // namespace scope, the constructor and destructor are used. 4967 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4968 RD->isAnonymousStructOrUnion()) 4969 return false; 4970 4971 // C++11 [class.copy]p7, p18: 4972 // If the class definition declares a move constructor or move assignment 4973 // operator, an implicitly declared copy constructor or copy assignment 4974 // operator is defined as deleted. 4975 if (MD->isImplicit() && 4976 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4977 CXXMethodDecl *UserDeclaredMove = 0; 4978 4979 // In Microsoft mode, a user-declared move only causes the deletion of the 4980 // corresponding copy operation, not both copy operations. 4981 if (RD->hasUserDeclaredMoveConstructor() && 4982 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4983 if (!Diagnose) return true; 4984 4985 // Find any user-declared move constructor. 4986 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4987 E = RD->ctor_end(); I != E; ++I) { 4988 if (I->isMoveConstructor()) { 4989 UserDeclaredMove = *I; 4990 break; 4991 } 4992 } 4993 assert(UserDeclaredMove); 4994 } else if (RD->hasUserDeclaredMoveAssignment() && 4995 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4996 if (!Diagnose) return true; 4997 4998 // Find any user-declared move assignment operator. 4999 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5000 E = RD->method_end(); I != E; ++I) { 5001 if (I->isMoveAssignmentOperator()) { 5002 UserDeclaredMove = *I; 5003 break; 5004 } 5005 } 5006 assert(UserDeclaredMove); 5007 } 5008 5009 if (UserDeclaredMove) { 5010 Diag(UserDeclaredMove->getLocation(), 5011 diag::note_deleted_copy_user_declared_move) 5012 << (CSM == CXXCopyAssignment) << RD 5013 << UserDeclaredMove->isMoveAssignmentOperator(); 5014 return true; 5015 } 5016 } 5017 5018 // Do access control from the special member function 5019 ContextRAII MethodContext(*this, MD); 5020 5021 // C++11 [class.dtor]p5: 5022 // -- for a virtual destructor, lookup of the non-array deallocation function 5023 // results in an ambiguity or in a function that is deleted or inaccessible 5024 if (CSM == CXXDestructor && MD->isVirtual()) { 5025 FunctionDecl *OperatorDelete = 0; 5026 DeclarationName Name = 5027 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5028 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5029 OperatorDelete, false)) { 5030 if (Diagnose) 5031 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5032 return true; 5033 } 5034 } 5035 5036 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5037 5038 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5039 BE = RD->bases_end(); BI != BE; ++BI) 5040 if (!BI->isVirtual() && 5041 SMI.shouldDeleteForBase(BI)) 5042 return true; 5043 5044 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5045 BE = RD->vbases_end(); BI != BE; ++BI) 5046 if (SMI.shouldDeleteForBase(BI)) 5047 return true; 5048 5049 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5050 FE = RD->field_end(); FI != FE; ++FI) 5051 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5052 SMI.shouldDeleteForField(*FI)) 5053 return true; 5054 5055 if (SMI.shouldDeleteForAllConstMembers()) 5056 return true; 5057 5058 return false; 5059} 5060 5061/// Perform lookup for a special member of the specified kind, and determine 5062/// whether it is trivial. If the triviality can be determined without the 5063/// lookup, skip it. This is intended for use when determining whether a 5064/// special member of a containing object is trivial, and thus does not ever 5065/// perform overload resolution for default constructors. 5066/// 5067/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5068/// member that was most likely to be intended to be trivial, if any. 5069static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5070 Sema::CXXSpecialMember CSM, unsigned Quals, 5071 CXXMethodDecl **Selected) { 5072 if (Selected) 5073 *Selected = 0; 5074 5075 switch (CSM) { 5076 case Sema::CXXInvalid: 5077 llvm_unreachable("not a special member"); 5078 5079 case Sema::CXXDefaultConstructor: 5080 // C++11 [class.ctor]p5: 5081 // A default constructor is trivial if: 5082 // - all the [direct subobjects] have trivial default constructors 5083 // 5084 // Note, no overload resolution is performed in this case. 5085 if (RD->hasTrivialDefaultConstructor()) 5086 return true; 5087 5088 if (Selected) { 5089 // If there's a default constructor which could have been trivial, dig it 5090 // out. Otherwise, if there's any user-provided default constructor, point 5091 // to that as an example of why there's not a trivial one. 5092 CXXConstructorDecl *DefCtor = 0; 5093 if (RD->needsImplicitDefaultConstructor()) 5094 S.DeclareImplicitDefaultConstructor(RD); 5095 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5096 CE = RD->ctor_end(); CI != CE; ++CI) { 5097 if (!CI->isDefaultConstructor()) 5098 continue; 5099 DefCtor = *CI; 5100 if (!DefCtor->isUserProvided()) 5101 break; 5102 } 5103 5104 *Selected = DefCtor; 5105 } 5106 5107 return false; 5108 5109 case Sema::CXXDestructor: 5110 // C++11 [class.dtor]p5: 5111 // A destructor is trivial if: 5112 // - all the direct [subobjects] have trivial destructors 5113 if (RD->hasTrivialDestructor()) 5114 return true; 5115 5116 if (Selected) { 5117 if (RD->needsImplicitDestructor()) 5118 S.DeclareImplicitDestructor(RD); 5119 *Selected = RD->getDestructor(); 5120 } 5121 5122 return false; 5123 5124 case Sema::CXXCopyConstructor: 5125 // C++11 [class.copy]p12: 5126 // A copy constructor is trivial if: 5127 // - the constructor selected to copy each direct [subobject] is trivial 5128 if (RD->hasTrivialCopyConstructor()) { 5129 if (Quals == Qualifiers::Const) 5130 // We must either select the trivial copy constructor or reach an 5131 // ambiguity; no need to actually perform overload resolution. 5132 return true; 5133 } else if (!Selected) { 5134 return false; 5135 } 5136 // In C++98, we are not supposed to perform overload resolution here, but we 5137 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5138 // cases like B as having a non-trivial copy constructor: 5139 // struct A { template<typename T> A(T&); }; 5140 // struct B { mutable A a; }; 5141 goto NeedOverloadResolution; 5142 5143 case Sema::CXXCopyAssignment: 5144 // C++11 [class.copy]p25: 5145 // A copy assignment operator is trivial if: 5146 // - the assignment operator selected to copy each direct [subobject] is 5147 // trivial 5148 if (RD->hasTrivialCopyAssignment()) { 5149 if (Quals == Qualifiers::Const) 5150 return true; 5151 } else if (!Selected) { 5152 return false; 5153 } 5154 // In C++98, we are not supposed to perform overload resolution here, but we 5155 // treat that as a language defect. 5156 goto NeedOverloadResolution; 5157 5158 case Sema::CXXMoveConstructor: 5159 case Sema::CXXMoveAssignment: 5160 NeedOverloadResolution: 5161 Sema::SpecialMemberOverloadResult *SMOR = 5162 S.LookupSpecialMember(RD, CSM, 5163 Quals & Qualifiers::Const, 5164 Quals & Qualifiers::Volatile, 5165 /*RValueThis*/false, /*ConstThis*/false, 5166 /*VolatileThis*/false); 5167 5168 // The standard doesn't describe how to behave if the lookup is ambiguous. 5169 // We treat it as not making the member non-trivial, just like the standard 5170 // mandates for the default constructor. This should rarely matter, because 5171 // the member will also be deleted. 5172 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5173 return true; 5174 5175 if (!SMOR->getMethod()) { 5176 assert(SMOR->getKind() == 5177 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5178 return false; 5179 } 5180 5181 // We deliberately don't check if we found a deleted special member. We're 5182 // not supposed to! 5183 if (Selected) 5184 *Selected = SMOR->getMethod(); 5185 return SMOR->getMethod()->isTrivial(); 5186 } 5187 5188 llvm_unreachable("unknown special method kind"); 5189} 5190 5191static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5192 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5193 CI != CE; ++CI) 5194 if (!CI->isImplicit()) 5195 return *CI; 5196 5197 // Look for constructor templates. 5198 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5199 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5200 if (CXXConstructorDecl *CD = 5201 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5202 return CD; 5203 } 5204 5205 return 0; 5206} 5207 5208/// The kind of subobject we are checking for triviality. The values of this 5209/// enumeration are used in diagnostics. 5210enum TrivialSubobjectKind { 5211 /// The subobject is a base class. 5212 TSK_BaseClass, 5213 /// The subobject is a non-static data member. 5214 TSK_Field, 5215 /// The object is actually the complete object. 5216 TSK_CompleteObject 5217}; 5218 5219/// Check whether the special member selected for a given type would be trivial. 5220static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5221 QualType SubType, 5222 Sema::CXXSpecialMember CSM, 5223 TrivialSubobjectKind Kind, 5224 bool Diagnose) { 5225 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5226 if (!SubRD) 5227 return true; 5228 5229 CXXMethodDecl *Selected; 5230 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5231 Diagnose ? &Selected : 0)) 5232 return true; 5233 5234 if (Diagnose) { 5235 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5236 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5237 << Kind << SubType.getUnqualifiedType(); 5238 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5239 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5240 } else if (!Selected) 5241 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5242 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5243 else if (Selected->isUserProvided()) { 5244 if (Kind == TSK_CompleteObject) 5245 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5246 << Kind << SubType.getUnqualifiedType() << CSM; 5247 else { 5248 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5249 << Kind << SubType.getUnqualifiedType() << CSM; 5250 S.Diag(Selected->getLocation(), diag::note_declared_at); 5251 } 5252 } else { 5253 if (Kind != TSK_CompleteObject) 5254 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5255 << Kind << SubType.getUnqualifiedType() << CSM; 5256 5257 // Explain why the defaulted or deleted special member isn't trivial. 5258 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5259 } 5260 } 5261 5262 return false; 5263} 5264 5265/// Check whether the members of a class type allow a special member to be 5266/// trivial. 5267static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5268 Sema::CXXSpecialMember CSM, 5269 bool ConstArg, bool Diagnose) { 5270 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5271 FE = RD->field_end(); FI != FE; ++FI) { 5272 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5273 continue; 5274 5275 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5276 5277 // Pretend anonymous struct or union members are members of this class. 5278 if (FI->isAnonymousStructOrUnion()) { 5279 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5280 CSM, ConstArg, Diagnose)) 5281 return false; 5282 continue; 5283 } 5284 5285 // C++11 [class.ctor]p5: 5286 // A default constructor is trivial if [...] 5287 // -- no non-static data member of its class has a 5288 // brace-or-equal-initializer 5289 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5290 if (Diagnose) 5291 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5292 return false; 5293 } 5294 5295 // Objective C ARC 4.3.5: 5296 // [...] nontrivally ownership-qualified types are [...] not trivially 5297 // default constructible, copy constructible, move constructible, copy 5298 // assignable, move assignable, or destructible [...] 5299 if (S.getLangOpts().ObjCAutoRefCount && 5300 FieldType.hasNonTrivialObjCLifetime()) { 5301 if (Diagnose) 5302 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5303 << RD << FieldType.getObjCLifetime(); 5304 return false; 5305 } 5306 5307 if (ConstArg && !FI->isMutable()) 5308 FieldType.addConst(); 5309 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5310 TSK_Field, Diagnose)) 5311 return false; 5312 } 5313 5314 return true; 5315} 5316 5317/// Diagnose why the specified class does not have a trivial special member of 5318/// the given kind. 5319void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5320 QualType Ty = Context.getRecordType(RD); 5321 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5322 Ty.addConst(); 5323 5324 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5325 TSK_CompleteObject, /*Diagnose*/true); 5326} 5327 5328/// Determine whether a defaulted or deleted special member function is trivial, 5329/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5330/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5331bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5332 bool Diagnose) { 5333 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5334 5335 CXXRecordDecl *RD = MD->getParent(); 5336 5337 bool ConstArg = false; 5338 5339 // C++11 [class.copy]p12, p25: 5340 // A [special member] is trivial if its declared parameter type is the same 5341 // as if it had been implicitly declared [...] 5342 switch (CSM) { 5343 case CXXDefaultConstructor: 5344 case CXXDestructor: 5345 // Trivial default constructors and destructors cannot have parameters. 5346 break; 5347 5348 case CXXCopyConstructor: 5349 case CXXCopyAssignment: { 5350 // Trivial copy operations always have const, non-volatile parameter types. 5351 ConstArg = true; 5352 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5353 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5354 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5355 if (Diagnose) 5356 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5357 << Param0->getSourceRange() << Param0->getType() 5358 << Context.getLValueReferenceType( 5359 Context.getRecordType(RD).withConst()); 5360 return false; 5361 } 5362 break; 5363 } 5364 5365 case CXXMoveConstructor: 5366 case CXXMoveAssignment: { 5367 // Trivial move operations always have non-cv-qualified parameters. 5368 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5369 const RValueReferenceType *RT = 5370 Param0->getType()->getAs<RValueReferenceType>(); 5371 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5372 if (Diagnose) 5373 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5374 << Param0->getSourceRange() << Param0->getType() 5375 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5376 return false; 5377 } 5378 break; 5379 } 5380 5381 case CXXInvalid: 5382 llvm_unreachable("not a special member"); 5383 } 5384 5385 // FIXME: We require that the parameter-declaration-clause is equivalent to 5386 // that of an implicit declaration, not just that the declared parameter type 5387 // matches, in order to prevent absuridities like a function simultaneously 5388 // being a trivial copy constructor and a non-trivial default constructor. 5389 // This issue has not yet been assigned a core issue number. 5390 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5391 if (Diagnose) 5392 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5393 diag::note_nontrivial_default_arg) 5394 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5395 return false; 5396 } 5397 if (MD->isVariadic()) { 5398 if (Diagnose) 5399 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5400 return false; 5401 } 5402 5403 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5404 // A copy/move [constructor or assignment operator] is trivial if 5405 // -- the [member] selected to copy/move each direct base class subobject 5406 // is trivial 5407 // 5408 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5409 // A [default constructor or destructor] is trivial if 5410 // -- all the direct base classes have trivial [default constructors or 5411 // destructors] 5412 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5413 BE = RD->bases_end(); BI != BE; ++BI) 5414 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5415 ConstArg ? BI->getType().withConst() 5416 : BI->getType(), 5417 CSM, TSK_BaseClass, Diagnose)) 5418 return false; 5419 5420 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5421 // A copy/move [constructor or assignment operator] for a class X is 5422 // trivial if 5423 // -- for each non-static data member of X that is of class type (or array 5424 // thereof), the constructor selected to copy/move that member is 5425 // trivial 5426 // 5427 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5428 // A [default constructor or destructor] is trivial if 5429 // -- for all of the non-static data members of its class that are of class 5430 // type (or array thereof), each such class has a trivial [default 5431 // constructor or destructor] 5432 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5433 return false; 5434 5435 // C++11 [class.dtor]p5: 5436 // A destructor is trivial if [...] 5437 // -- the destructor is not virtual 5438 if (CSM == CXXDestructor && MD->isVirtual()) { 5439 if (Diagnose) 5440 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5441 return false; 5442 } 5443 5444 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5445 // A [special member] for class X is trivial if [...] 5446 // -- class X has no virtual functions and no virtual base classes 5447 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5448 if (!Diagnose) 5449 return false; 5450 5451 if (RD->getNumVBases()) { 5452 // Check for virtual bases. We already know that the corresponding 5453 // member in all bases is trivial, so vbases must all be direct. 5454 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5455 assert(BS.isVirtual()); 5456 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5457 return false; 5458 } 5459 5460 // Must have a virtual method. 5461 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5462 ME = RD->method_end(); MI != ME; ++MI) { 5463 if (MI->isVirtual()) { 5464 SourceLocation MLoc = MI->getLocStart(); 5465 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5466 return false; 5467 } 5468 } 5469 5470 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5471 } 5472 5473 // Looks like it's trivial! 5474 return true; 5475} 5476 5477/// \brief Data used with FindHiddenVirtualMethod 5478namespace { 5479 struct FindHiddenVirtualMethodData { 5480 Sema *S; 5481 CXXMethodDecl *Method; 5482 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5483 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5484 }; 5485} 5486 5487/// \brief Check whether any most overriden method from MD in Methods 5488static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5489 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5490 if (MD->size_overridden_methods() == 0) 5491 return Methods.count(MD->getCanonicalDecl()); 5492 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5493 E = MD->end_overridden_methods(); 5494 I != E; ++I) 5495 if (CheckMostOverridenMethods(*I, Methods)) 5496 return true; 5497 return false; 5498} 5499 5500/// \brief Member lookup function that determines whether a given C++ 5501/// method overloads virtual methods in a base class without overriding any, 5502/// to be used with CXXRecordDecl::lookupInBases(). 5503static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5504 CXXBasePath &Path, 5505 void *UserData) { 5506 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5507 5508 FindHiddenVirtualMethodData &Data 5509 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5510 5511 DeclarationName Name = Data.Method->getDeclName(); 5512 assert(Name.getNameKind() == DeclarationName::Identifier); 5513 5514 bool foundSameNameMethod = false; 5515 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5516 for (Path.Decls = BaseRecord->lookup(Name); 5517 !Path.Decls.empty(); 5518 Path.Decls = Path.Decls.slice(1)) { 5519 NamedDecl *D = Path.Decls.front(); 5520 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5521 MD = MD->getCanonicalDecl(); 5522 foundSameNameMethod = true; 5523 // Interested only in hidden virtual methods. 5524 if (!MD->isVirtual()) 5525 continue; 5526 // If the method we are checking overrides a method from its base 5527 // don't warn about the other overloaded methods. 5528 if (!Data.S->IsOverload(Data.Method, MD, false)) 5529 return true; 5530 // Collect the overload only if its hidden. 5531 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5532 overloadedMethods.push_back(MD); 5533 } 5534 } 5535 5536 if (foundSameNameMethod) 5537 Data.OverloadedMethods.append(overloadedMethods.begin(), 5538 overloadedMethods.end()); 5539 return foundSameNameMethod; 5540} 5541 5542/// \brief Add the most overriden methods from MD to Methods 5543static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5544 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5545 if (MD->size_overridden_methods() == 0) 5546 Methods.insert(MD->getCanonicalDecl()); 5547 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5548 E = MD->end_overridden_methods(); 5549 I != E; ++I) 5550 AddMostOverridenMethods(*I, Methods); 5551} 5552 5553/// \brief See if a method overloads virtual methods in a base class without 5554/// overriding any. 5555void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5556 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5557 MD->getLocation()) == DiagnosticsEngine::Ignored) 5558 return; 5559 if (!MD->getDeclName().isIdentifier()) 5560 return; 5561 5562 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5563 /*bool RecordPaths=*/false, 5564 /*bool DetectVirtual=*/false); 5565 FindHiddenVirtualMethodData Data; 5566 Data.Method = MD; 5567 Data.S = this; 5568 5569 // Keep the base methods that were overriden or introduced in the subclass 5570 // by 'using' in a set. A base method not in this set is hidden. 5571 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5572 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5573 NamedDecl *ND = *I; 5574 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5575 ND = shad->getTargetDecl(); 5576 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5577 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5578 } 5579 5580 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5581 !Data.OverloadedMethods.empty()) { 5582 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5583 << MD << (Data.OverloadedMethods.size() > 1); 5584 5585 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5586 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5587 PartialDiagnostic PD = PDiag( 5588 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5589 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5590 Diag(overloadedMD->getLocation(), PD); 5591 } 5592 } 5593} 5594 5595void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5596 Decl *TagDecl, 5597 SourceLocation LBrac, 5598 SourceLocation RBrac, 5599 AttributeList *AttrList) { 5600 if (!TagDecl) 5601 return; 5602 5603 AdjustDeclIfTemplate(TagDecl); 5604 5605 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5606 if (l->getKind() != AttributeList::AT_Visibility) 5607 continue; 5608 l->setInvalid(); 5609 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5610 l->getName(); 5611 } 5612 5613 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5614 // strict aliasing violation! 5615 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5616 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5617 5618 CheckCompletedCXXClass( 5619 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5620} 5621 5622/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5623/// special functions, such as the default constructor, copy 5624/// constructor, or destructor, to the given C++ class (C++ 5625/// [special]p1). This routine can only be executed just before the 5626/// definition of the class is complete. 5627void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5628 if (!ClassDecl->hasUserDeclaredConstructor()) 5629 ++ASTContext::NumImplicitDefaultConstructors; 5630 5631 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5632 ++ASTContext::NumImplicitCopyConstructors; 5633 5634 // If the properties or semantics of the copy constructor couldn't be 5635 // determined while the class was being declared, force a declaration 5636 // of it now. 5637 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5638 DeclareImplicitCopyConstructor(ClassDecl); 5639 } 5640 5641 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5642 ++ASTContext::NumImplicitMoveConstructors; 5643 5644 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5645 DeclareImplicitMoveConstructor(ClassDecl); 5646 } 5647 5648 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5649 ++ASTContext::NumImplicitCopyAssignmentOperators; 5650 5651 // If we have a dynamic class, then the copy assignment operator may be 5652 // virtual, so we have to declare it immediately. This ensures that, e.g., 5653 // it shows up in the right place in the vtable and that we diagnose 5654 // problems with the implicit exception specification. 5655 if (ClassDecl->isDynamicClass() || 5656 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5657 DeclareImplicitCopyAssignment(ClassDecl); 5658 } 5659 5660 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5661 ++ASTContext::NumImplicitMoveAssignmentOperators; 5662 5663 // Likewise for the move assignment operator. 5664 if (ClassDecl->isDynamicClass() || 5665 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5666 DeclareImplicitMoveAssignment(ClassDecl); 5667 } 5668 5669 if (!ClassDecl->hasUserDeclaredDestructor()) { 5670 ++ASTContext::NumImplicitDestructors; 5671 5672 // If we have a dynamic class, then the destructor may be virtual, so we 5673 // have to declare the destructor immediately. This ensures that, e.g., it 5674 // shows up in the right place in the vtable and that we diagnose problems 5675 // with the implicit exception specification. 5676 if (ClassDecl->isDynamicClass() || 5677 ClassDecl->needsOverloadResolutionForDestructor()) 5678 DeclareImplicitDestructor(ClassDecl); 5679 } 5680} 5681 5682void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5683 if (!D) 5684 return; 5685 5686 int NumParamList = D->getNumTemplateParameterLists(); 5687 for (int i = 0; i < NumParamList; i++) { 5688 TemplateParameterList* Params = D->getTemplateParameterList(i); 5689 for (TemplateParameterList::iterator Param = Params->begin(), 5690 ParamEnd = Params->end(); 5691 Param != ParamEnd; ++Param) { 5692 NamedDecl *Named = cast<NamedDecl>(*Param); 5693 if (Named->getDeclName()) { 5694 S->AddDecl(Named); 5695 IdResolver.AddDecl(Named); 5696 } 5697 } 5698 } 5699} 5700 5701void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5702 if (!D) 5703 return; 5704 5705 TemplateParameterList *Params = 0; 5706 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5707 Params = Template->getTemplateParameters(); 5708 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5709 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5710 Params = PartialSpec->getTemplateParameters(); 5711 else 5712 return; 5713 5714 for (TemplateParameterList::iterator Param = Params->begin(), 5715 ParamEnd = Params->end(); 5716 Param != ParamEnd; ++Param) { 5717 NamedDecl *Named = cast<NamedDecl>(*Param); 5718 if (Named->getDeclName()) { 5719 S->AddDecl(Named); 5720 IdResolver.AddDecl(Named); 5721 } 5722 } 5723} 5724 5725void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5726 if (!RecordD) return; 5727 AdjustDeclIfTemplate(RecordD); 5728 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5729 PushDeclContext(S, Record); 5730} 5731 5732void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5733 if (!RecordD) return; 5734 PopDeclContext(); 5735} 5736 5737/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5738/// parsing a top-level (non-nested) C++ class, and we are now 5739/// parsing those parts of the given Method declaration that could 5740/// not be parsed earlier (C++ [class.mem]p2), such as default 5741/// arguments. This action should enter the scope of the given 5742/// Method declaration as if we had just parsed the qualified method 5743/// name. However, it should not bring the parameters into scope; 5744/// that will be performed by ActOnDelayedCXXMethodParameter. 5745void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5746} 5747 5748/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5749/// C++ method declaration. We're (re-)introducing the given 5750/// function parameter into scope for use in parsing later parts of 5751/// the method declaration. For example, we could see an 5752/// ActOnParamDefaultArgument event for this parameter. 5753void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5754 if (!ParamD) 5755 return; 5756 5757 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5758 5759 // If this parameter has an unparsed default argument, clear it out 5760 // to make way for the parsed default argument. 5761 if (Param->hasUnparsedDefaultArg()) 5762 Param->setDefaultArg(0); 5763 5764 S->AddDecl(Param); 5765 if (Param->getDeclName()) 5766 IdResolver.AddDecl(Param); 5767} 5768 5769/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5770/// processing the delayed method declaration for Method. The method 5771/// declaration is now considered finished. There may be a separate 5772/// ActOnStartOfFunctionDef action later (not necessarily 5773/// immediately!) for this method, if it was also defined inside the 5774/// class body. 5775void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5776 if (!MethodD) 5777 return; 5778 5779 AdjustDeclIfTemplate(MethodD); 5780 5781 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5782 5783 // Now that we have our default arguments, check the constructor 5784 // again. It could produce additional diagnostics or affect whether 5785 // the class has implicitly-declared destructors, among other 5786 // things. 5787 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5788 CheckConstructor(Constructor); 5789 5790 // Check the default arguments, which we may have added. 5791 if (!Method->isInvalidDecl()) 5792 CheckCXXDefaultArguments(Method); 5793} 5794 5795/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5796/// the well-formedness of the constructor declarator @p D with type @p 5797/// R. If there are any errors in the declarator, this routine will 5798/// emit diagnostics and set the invalid bit to true. In any case, the type 5799/// will be updated to reflect a well-formed type for the constructor and 5800/// returned. 5801QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5802 StorageClass &SC) { 5803 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5804 5805 // C++ [class.ctor]p3: 5806 // A constructor shall not be virtual (10.3) or static (9.4). A 5807 // constructor can be invoked for a const, volatile or const 5808 // volatile object. A constructor shall not be declared const, 5809 // volatile, or const volatile (9.3.2). 5810 if (isVirtual) { 5811 if (!D.isInvalidType()) 5812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5813 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5814 << SourceRange(D.getIdentifierLoc()); 5815 D.setInvalidType(); 5816 } 5817 if (SC == SC_Static) { 5818 if (!D.isInvalidType()) 5819 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5820 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5821 << SourceRange(D.getIdentifierLoc()); 5822 D.setInvalidType(); 5823 SC = SC_None; 5824 } 5825 5826 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5827 if (FTI.TypeQuals != 0) { 5828 if (FTI.TypeQuals & Qualifiers::Const) 5829 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5830 << "const" << SourceRange(D.getIdentifierLoc()); 5831 if (FTI.TypeQuals & Qualifiers::Volatile) 5832 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5833 << "volatile" << SourceRange(D.getIdentifierLoc()); 5834 if (FTI.TypeQuals & Qualifiers::Restrict) 5835 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5836 << "restrict" << SourceRange(D.getIdentifierLoc()); 5837 D.setInvalidType(); 5838 } 5839 5840 // C++0x [class.ctor]p4: 5841 // A constructor shall not be declared with a ref-qualifier. 5842 if (FTI.hasRefQualifier()) { 5843 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5844 << FTI.RefQualifierIsLValueRef 5845 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5846 D.setInvalidType(); 5847 } 5848 5849 // Rebuild the function type "R" without any type qualifiers (in 5850 // case any of the errors above fired) and with "void" as the 5851 // return type, since constructors don't have return types. 5852 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5853 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5854 return R; 5855 5856 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5857 EPI.TypeQuals = 0; 5858 EPI.RefQualifier = RQ_None; 5859 5860 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5861} 5862 5863/// CheckConstructor - Checks a fully-formed constructor for 5864/// well-formedness, issuing any diagnostics required. Returns true if 5865/// the constructor declarator is invalid. 5866void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5867 CXXRecordDecl *ClassDecl 5868 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5869 if (!ClassDecl) 5870 return Constructor->setInvalidDecl(); 5871 5872 // C++ [class.copy]p3: 5873 // A declaration of a constructor for a class X is ill-formed if 5874 // its first parameter is of type (optionally cv-qualified) X and 5875 // either there are no other parameters or else all other 5876 // parameters have default arguments. 5877 if (!Constructor->isInvalidDecl() && 5878 ((Constructor->getNumParams() == 1) || 5879 (Constructor->getNumParams() > 1 && 5880 Constructor->getParamDecl(1)->hasDefaultArg())) && 5881 Constructor->getTemplateSpecializationKind() 5882 != TSK_ImplicitInstantiation) { 5883 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5884 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5885 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5886 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5887 const char *ConstRef 5888 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5889 : " const &"; 5890 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5891 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5892 5893 // FIXME: Rather that making the constructor invalid, we should endeavor 5894 // to fix the type. 5895 Constructor->setInvalidDecl(); 5896 } 5897 } 5898} 5899 5900/// CheckDestructor - Checks a fully-formed destructor definition for 5901/// well-formedness, issuing any diagnostics required. Returns true 5902/// on error. 5903bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5904 CXXRecordDecl *RD = Destructor->getParent(); 5905 5906 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 5907 SourceLocation Loc; 5908 5909 if (!Destructor->isImplicit()) 5910 Loc = Destructor->getLocation(); 5911 else 5912 Loc = RD->getLocation(); 5913 5914 // If we have a virtual destructor, look up the deallocation function 5915 FunctionDecl *OperatorDelete = 0; 5916 DeclarationName Name = 5917 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5918 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5919 return true; 5920 5921 MarkFunctionReferenced(Loc, OperatorDelete); 5922 5923 Destructor->setOperatorDelete(OperatorDelete); 5924 } 5925 5926 return false; 5927} 5928 5929static inline bool 5930FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5931 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5932 FTI.ArgInfo[0].Param && 5933 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5934} 5935 5936/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5937/// the well-formednes of the destructor declarator @p D with type @p 5938/// R. If there are any errors in the declarator, this routine will 5939/// emit diagnostics and set the declarator to invalid. Even if this happens, 5940/// will be updated to reflect a well-formed type for the destructor and 5941/// returned. 5942QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5943 StorageClass& SC) { 5944 // C++ [class.dtor]p1: 5945 // [...] A typedef-name that names a class is a class-name 5946 // (7.1.3); however, a typedef-name that names a class shall not 5947 // be used as the identifier in the declarator for a destructor 5948 // declaration. 5949 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5950 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5951 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5952 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5953 else if (const TemplateSpecializationType *TST = 5954 DeclaratorType->getAs<TemplateSpecializationType>()) 5955 if (TST->isTypeAlias()) 5956 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5957 << DeclaratorType << 1; 5958 5959 // C++ [class.dtor]p2: 5960 // A destructor is used to destroy objects of its class type. A 5961 // destructor takes no parameters, and no return type can be 5962 // specified for it (not even void). The address of a destructor 5963 // shall not be taken. A destructor shall not be static. A 5964 // destructor can be invoked for a const, volatile or const 5965 // volatile object. A destructor shall not be declared const, 5966 // volatile or const volatile (9.3.2). 5967 if (SC == SC_Static) { 5968 if (!D.isInvalidType()) 5969 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5970 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5971 << SourceRange(D.getIdentifierLoc()) 5972 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5973 5974 SC = SC_None; 5975 } 5976 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5977 // Destructors don't have return types, but the parser will 5978 // happily parse something like: 5979 // 5980 // class X { 5981 // float ~X(); 5982 // }; 5983 // 5984 // The return type will be eliminated later. 5985 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5986 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5987 << SourceRange(D.getIdentifierLoc()); 5988 } 5989 5990 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5991 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5992 if (FTI.TypeQuals & Qualifiers::Const) 5993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5994 << "const" << SourceRange(D.getIdentifierLoc()); 5995 if (FTI.TypeQuals & Qualifiers::Volatile) 5996 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5997 << "volatile" << SourceRange(D.getIdentifierLoc()); 5998 if (FTI.TypeQuals & Qualifiers::Restrict) 5999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6000 << "restrict" << SourceRange(D.getIdentifierLoc()); 6001 D.setInvalidType(); 6002 } 6003 6004 // C++0x [class.dtor]p2: 6005 // A destructor shall not be declared with a ref-qualifier. 6006 if (FTI.hasRefQualifier()) { 6007 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6008 << FTI.RefQualifierIsLValueRef 6009 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6010 D.setInvalidType(); 6011 } 6012 6013 // Make sure we don't have any parameters. 6014 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6015 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6016 6017 // Delete the parameters. 6018 FTI.freeArgs(); 6019 D.setInvalidType(); 6020 } 6021 6022 // Make sure the destructor isn't variadic. 6023 if (FTI.isVariadic) { 6024 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6025 D.setInvalidType(); 6026 } 6027 6028 // Rebuild the function type "R" without any type qualifiers or 6029 // parameters (in case any of the errors above fired) and with 6030 // "void" as the return type, since destructors don't have return 6031 // types. 6032 if (!D.isInvalidType()) 6033 return R; 6034 6035 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6036 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6037 EPI.Variadic = false; 6038 EPI.TypeQuals = 0; 6039 EPI.RefQualifier = RQ_None; 6040 return Context.getFunctionType(Context.VoidTy, None, EPI); 6041} 6042 6043/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6044/// well-formednes of the conversion function declarator @p D with 6045/// type @p R. If there are any errors in the declarator, this routine 6046/// will emit diagnostics and return true. Otherwise, it will return 6047/// false. Either way, the type @p R will be updated to reflect a 6048/// well-formed type for the conversion operator. 6049void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6050 StorageClass& SC) { 6051 // C++ [class.conv.fct]p1: 6052 // Neither parameter types nor return type can be specified. The 6053 // type of a conversion function (8.3.5) is "function taking no 6054 // parameter returning conversion-type-id." 6055 if (SC == SC_Static) { 6056 if (!D.isInvalidType()) 6057 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6058 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6059 << SourceRange(D.getIdentifierLoc()); 6060 D.setInvalidType(); 6061 SC = SC_None; 6062 } 6063 6064 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6065 6066 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6067 // Conversion functions don't have return types, but the parser will 6068 // happily parse something like: 6069 // 6070 // class X { 6071 // float operator bool(); 6072 // }; 6073 // 6074 // The return type will be changed later anyway. 6075 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6076 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6077 << SourceRange(D.getIdentifierLoc()); 6078 D.setInvalidType(); 6079 } 6080 6081 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6082 6083 // Make sure we don't have any parameters. 6084 if (Proto->getNumArgs() > 0) { 6085 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6086 6087 // Delete the parameters. 6088 D.getFunctionTypeInfo().freeArgs(); 6089 D.setInvalidType(); 6090 } else if (Proto->isVariadic()) { 6091 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6092 D.setInvalidType(); 6093 } 6094 6095 // Diagnose "&operator bool()" and other such nonsense. This 6096 // is actually a gcc extension which we don't support. 6097 if (Proto->getResultType() != ConvType) { 6098 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6099 << Proto->getResultType(); 6100 D.setInvalidType(); 6101 ConvType = Proto->getResultType(); 6102 } 6103 6104 // C++ [class.conv.fct]p4: 6105 // The conversion-type-id shall not represent a function type nor 6106 // an array type. 6107 if (ConvType->isArrayType()) { 6108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6109 ConvType = Context.getPointerType(ConvType); 6110 D.setInvalidType(); 6111 } else if (ConvType->isFunctionType()) { 6112 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6113 ConvType = Context.getPointerType(ConvType); 6114 D.setInvalidType(); 6115 } 6116 6117 // Rebuild the function type "R" without any parameters (in case any 6118 // of the errors above fired) and with the conversion type as the 6119 // return type. 6120 if (D.isInvalidType()) 6121 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6122 6123 // C++0x explicit conversion operators. 6124 if (D.getDeclSpec().isExplicitSpecified()) 6125 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6126 getLangOpts().CPlusPlus11 ? 6127 diag::warn_cxx98_compat_explicit_conversion_functions : 6128 diag::ext_explicit_conversion_functions) 6129 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6130} 6131 6132/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6133/// the declaration of the given C++ conversion function. This routine 6134/// is responsible for recording the conversion function in the C++ 6135/// class, if possible. 6136Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6137 assert(Conversion && "Expected to receive a conversion function declaration"); 6138 6139 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6140 6141 // Make sure we aren't redeclaring the conversion function. 6142 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6143 6144 // C++ [class.conv.fct]p1: 6145 // [...] A conversion function is never used to convert a 6146 // (possibly cv-qualified) object to the (possibly cv-qualified) 6147 // same object type (or a reference to it), to a (possibly 6148 // cv-qualified) base class of that type (or a reference to it), 6149 // or to (possibly cv-qualified) void. 6150 // FIXME: Suppress this warning if the conversion function ends up being a 6151 // virtual function that overrides a virtual function in a base class. 6152 QualType ClassType 6153 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6154 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6155 ConvType = ConvTypeRef->getPointeeType(); 6156 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6157 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6158 /* Suppress diagnostics for instantiations. */; 6159 else if (ConvType->isRecordType()) { 6160 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6161 if (ConvType == ClassType) 6162 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6163 << ClassType; 6164 else if (IsDerivedFrom(ClassType, ConvType)) 6165 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6166 << ClassType << ConvType; 6167 } else if (ConvType->isVoidType()) { 6168 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6169 << ClassType << ConvType; 6170 } 6171 6172 if (FunctionTemplateDecl *ConversionTemplate 6173 = Conversion->getDescribedFunctionTemplate()) 6174 return ConversionTemplate; 6175 6176 return Conversion; 6177} 6178 6179//===----------------------------------------------------------------------===// 6180// Namespace Handling 6181//===----------------------------------------------------------------------===// 6182 6183/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6184/// reopened. 6185static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6186 SourceLocation Loc, 6187 IdentifierInfo *II, bool *IsInline, 6188 NamespaceDecl *PrevNS) { 6189 assert(*IsInline != PrevNS->isInline()); 6190 6191 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6192 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6193 // inline namespaces, with the intention of bringing names into namespace std. 6194 // 6195 // We support this just well enough to get that case working; this is not 6196 // sufficient to support reopening namespaces as inline in general. 6197 if (*IsInline && II && II->getName().startswith("__atomic") && 6198 S.getSourceManager().isInSystemHeader(Loc)) { 6199 // Mark all prior declarations of the namespace as inline. 6200 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6201 NS = NS->getPreviousDecl()) 6202 NS->setInline(*IsInline); 6203 // Patch up the lookup table for the containing namespace. This isn't really 6204 // correct, but it's good enough for this particular case. 6205 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6206 E = PrevNS->decls_end(); I != E; ++I) 6207 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6208 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6209 return; 6210 } 6211 6212 if (PrevNS->isInline()) 6213 // The user probably just forgot the 'inline', so suggest that it 6214 // be added back. 6215 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6216 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6217 else 6218 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6219 << IsInline; 6220 6221 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6222 *IsInline = PrevNS->isInline(); 6223} 6224 6225/// ActOnStartNamespaceDef - This is called at the start of a namespace 6226/// definition. 6227Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6228 SourceLocation InlineLoc, 6229 SourceLocation NamespaceLoc, 6230 SourceLocation IdentLoc, 6231 IdentifierInfo *II, 6232 SourceLocation LBrace, 6233 AttributeList *AttrList) { 6234 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6235 // For anonymous namespace, take the location of the left brace. 6236 SourceLocation Loc = II ? IdentLoc : LBrace; 6237 bool IsInline = InlineLoc.isValid(); 6238 bool IsInvalid = false; 6239 bool IsStd = false; 6240 bool AddToKnown = false; 6241 Scope *DeclRegionScope = NamespcScope->getParent(); 6242 6243 NamespaceDecl *PrevNS = 0; 6244 if (II) { 6245 // C++ [namespace.def]p2: 6246 // The identifier in an original-namespace-definition shall not 6247 // have been previously defined in the declarative region in 6248 // which the original-namespace-definition appears. The 6249 // identifier in an original-namespace-definition is the name of 6250 // the namespace. Subsequently in that declarative region, it is 6251 // treated as an original-namespace-name. 6252 // 6253 // Since namespace names are unique in their scope, and we don't 6254 // look through using directives, just look for any ordinary names. 6255 6256 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6257 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6258 Decl::IDNS_Namespace; 6259 NamedDecl *PrevDecl = 0; 6260 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6261 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6262 ++I) { 6263 if ((*I)->getIdentifierNamespace() & IDNS) { 6264 PrevDecl = *I; 6265 break; 6266 } 6267 } 6268 6269 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6270 6271 if (PrevNS) { 6272 // This is an extended namespace definition. 6273 if (IsInline != PrevNS->isInline()) 6274 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6275 &IsInline, PrevNS); 6276 } else if (PrevDecl) { 6277 // This is an invalid name redefinition. 6278 Diag(Loc, diag::err_redefinition_different_kind) 6279 << II; 6280 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6281 IsInvalid = true; 6282 // Continue on to push Namespc as current DeclContext and return it. 6283 } else if (II->isStr("std") && 6284 CurContext->getRedeclContext()->isTranslationUnit()) { 6285 // This is the first "real" definition of the namespace "std", so update 6286 // our cache of the "std" namespace to point at this definition. 6287 PrevNS = getStdNamespace(); 6288 IsStd = true; 6289 AddToKnown = !IsInline; 6290 } else { 6291 // We've seen this namespace for the first time. 6292 AddToKnown = !IsInline; 6293 } 6294 } else { 6295 // Anonymous namespaces. 6296 6297 // Determine whether the parent already has an anonymous namespace. 6298 DeclContext *Parent = CurContext->getRedeclContext(); 6299 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6300 PrevNS = TU->getAnonymousNamespace(); 6301 } else { 6302 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6303 PrevNS = ND->getAnonymousNamespace(); 6304 } 6305 6306 if (PrevNS && IsInline != PrevNS->isInline()) 6307 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6308 &IsInline, PrevNS); 6309 } 6310 6311 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6312 StartLoc, Loc, II, PrevNS); 6313 if (IsInvalid) 6314 Namespc->setInvalidDecl(); 6315 6316 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6317 6318 // FIXME: Should we be merging attributes? 6319 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6320 PushNamespaceVisibilityAttr(Attr, Loc); 6321 6322 if (IsStd) 6323 StdNamespace = Namespc; 6324 if (AddToKnown) 6325 KnownNamespaces[Namespc] = false; 6326 6327 if (II) { 6328 PushOnScopeChains(Namespc, DeclRegionScope); 6329 } else { 6330 // Link the anonymous namespace into its parent. 6331 DeclContext *Parent = CurContext->getRedeclContext(); 6332 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6333 TU->setAnonymousNamespace(Namespc); 6334 } else { 6335 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6336 } 6337 6338 CurContext->addDecl(Namespc); 6339 6340 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6341 // behaves as if it were replaced by 6342 // namespace unique { /* empty body */ } 6343 // using namespace unique; 6344 // namespace unique { namespace-body } 6345 // where all occurrences of 'unique' in a translation unit are 6346 // replaced by the same identifier and this identifier differs 6347 // from all other identifiers in the entire program. 6348 6349 // We just create the namespace with an empty name and then add an 6350 // implicit using declaration, just like the standard suggests. 6351 // 6352 // CodeGen enforces the "universally unique" aspect by giving all 6353 // declarations semantically contained within an anonymous 6354 // namespace internal linkage. 6355 6356 if (!PrevNS) { 6357 UsingDirectiveDecl* UD 6358 = UsingDirectiveDecl::Create(Context, Parent, 6359 /* 'using' */ LBrace, 6360 /* 'namespace' */ SourceLocation(), 6361 /* qualifier */ NestedNameSpecifierLoc(), 6362 /* identifier */ SourceLocation(), 6363 Namespc, 6364 /* Ancestor */ Parent); 6365 UD->setImplicit(); 6366 Parent->addDecl(UD); 6367 } 6368 } 6369 6370 ActOnDocumentableDecl(Namespc); 6371 6372 // Although we could have an invalid decl (i.e. the namespace name is a 6373 // redefinition), push it as current DeclContext and try to continue parsing. 6374 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6375 // for the namespace has the declarations that showed up in that particular 6376 // namespace definition. 6377 PushDeclContext(NamespcScope, Namespc); 6378 return Namespc; 6379} 6380 6381/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6382/// is a namespace alias, returns the namespace it points to. 6383static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6384 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6385 return AD->getNamespace(); 6386 return dyn_cast_or_null<NamespaceDecl>(D); 6387} 6388 6389/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6390/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6391void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6392 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6393 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6394 Namespc->setRBraceLoc(RBrace); 6395 PopDeclContext(); 6396 if (Namespc->hasAttr<VisibilityAttr>()) 6397 PopPragmaVisibility(true, RBrace); 6398} 6399 6400CXXRecordDecl *Sema::getStdBadAlloc() const { 6401 return cast_or_null<CXXRecordDecl>( 6402 StdBadAlloc.get(Context.getExternalSource())); 6403} 6404 6405NamespaceDecl *Sema::getStdNamespace() const { 6406 return cast_or_null<NamespaceDecl>( 6407 StdNamespace.get(Context.getExternalSource())); 6408} 6409 6410/// \brief Retrieve the special "std" namespace, which may require us to 6411/// implicitly define the namespace. 6412NamespaceDecl *Sema::getOrCreateStdNamespace() { 6413 if (!StdNamespace) { 6414 // The "std" namespace has not yet been defined, so build one implicitly. 6415 StdNamespace = NamespaceDecl::Create(Context, 6416 Context.getTranslationUnitDecl(), 6417 /*Inline=*/false, 6418 SourceLocation(), SourceLocation(), 6419 &PP.getIdentifierTable().get("std"), 6420 /*PrevDecl=*/0); 6421 getStdNamespace()->setImplicit(true); 6422 } 6423 6424 return getStdNamespace(); 6425} 6426 6427bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6428 assert(getLangOpts().CPlusPlus && 6429 "Looking for std::initializer_list outside of C++."); 6430 6431 // We're looking for implicit instantiations of 6432 // template <typename E> class std::initializer_list. 6433 6434 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6435 return false; 6436 6437 ClassTemplateDecl *Template = 0; 6438 const TemplateArgument *Arguments = 0; 6439 6440 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6441 6442 ClassTemplateSpecializationDecl *Specialization = 6443 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6444 if (!Specialization) 6445 return false; 6446 6447 Template = Specialization->getSpecializedTemplate(); 6448 Arguments = Specialization->getTemplateArgs().data(); 6449 } else if (const TemplateSpecializationType *TST = 6450 Ty->getAs<TemplateSpecializationType>()) { 6451 Template = dyn_cast_or_null<ClassTemplateDecl>( 6452 TST->getTemplateName().getAsTemplateDecl()); 6453 Arguments = TST->getArgs(); 6454 } 6455 if (!Template) 6456 return false; 6457 6458 if (!StdInitializerList) { 6459 // Haven't recognized std::initializer_list yet, maybe this is it. 6460 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6461 if (TemplateClass->getIdentifier() != 6462 &PP.getIdentifierTable().get("initializer_list") || 6463 !getStdNamespace()->InEnclosingNamespaceSetOf( 6464 TemplateClass->getDeclContext())) 6465 return false; 6466 // This is a template called std::initializer_list, but is it the right 6467 // template? 6468 TemplateParameterList *Params = Template->getTemplateParameters(); 6469 if (Params->getMinRequiredArguments() != 1) 6470 return false; 6471 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6472 return false; 6473 6474 // It's the right template. 6475 StdInitializerList = Template; 6476 } 6477 6478 if (Template != StdInitializerList) 6479 return false; 6480 6481 // This is an instance of std::initializer_list. Find the argument type. 6482 if (Element) 6483 *Element = Arguments[0].getAsType(); 6484 return true; 6485} 6486 6487static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6488 NamespaceDecl *Std = S.getStdNamespace(); 6489 if (!Std) { 6490 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6491 return 0; 6492 } 6493 6494 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6495 Loc, Sema::LookupOrdinaryName); 6496 if (!S.LookupQualifiedName(Result, Std)) { 6497 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6498 return 0; 6499 } 6500 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6501 if (!Template) { 6502 Result.suppressDiagnostics(); 6503 // We found something weird. Complain about the first thing we found. 6504 NamedDecl *Found = *Result.begin(); 6505 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6506 return 0; 6507 } 6508 6509 // We found some template called std::initializer_list. Now verify that it's 6510 // correct. 6511 TemplateParameterList *Params = Template->getTemplateParameters(); 6512 if (Params->getMinRequiredArguments() != 1 || 6513 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6514 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6515 return 0; 6516 } 6517 6518 return Template; 6519} 6520 6521QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6522 if (!StdInitializerList) { 6523 StdInitializerList = LookupStdInitializerList(*this, Loc); 6524 if (!StdInitializerList) 6525 return QualType(); 6526 } 6527 6528 TemplateArgumentListInfo Args(Loc, Loc); 6529 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6530 Context.getTrivialTypeSourceInfo(Element, 6531 Loc))); 6532 return Context.getCanonicalType( 6533 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6534} 6535 6536bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6537 // C++ [dcl.init.list]p2: 6538 // A constructor is an initializer-list constructor if its first parameter 6539 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6540 // std::initializer_list<E> for some type E, and either there are no other 6541 // parameters or else all other parameters have default arguments. 6542 if (Ctor->getNumParams() < 1 || 6543 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6544 return false; 6545 6546 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6547 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6548 ArgType = RT->getPointeeType().getUnqualifiedType(); 6549 6550 return isStdInitializerList(ArgType, 0); 6551} 6552 6553/// \brief Determine whether a using statement is in a context where it will be 6554/// apply in all contexts. 6555static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6556 switch (CurContext->getDeclKind()) { 6557 case Decl::TranslationUnit: 6558 return true; 6559 case Decl::LinkageSpec: 6560 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6561 default: 6562 return false; 6563 } 6564} 6565 6566namespace { 6567 6568// Callback to only accept typo corrections that are namespaces. 6569class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6570 public: 6571 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6572 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6573 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6574 } 6575 return false; 6576 } 6577}; 6578 6579} 6580 6581static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6582 CXXScopeSpec &SS, 6583 SourceLocation IdentLoc, 6584 IdentifierInfo *Ident) { 6585 NamespaceValidatorCCC Validator; 6586 R.clear(); 6587 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6588 R.getLookupKind(), Sc, &SS, 6589 Validator)) { 6590 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6591 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6592 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6593 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6594 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6595 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6596 CorrectedStr); 6597 else 6598 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6599 << Ident << CorrectedQuotedStr 6600 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6601 6602 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6603 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6604 6605 R.addDecl(Corrected.getCorrectionDecl()); 6606 return true; 6607 } 6608 return false; 6609} 6610 6611Decl *Sema::ActOnUsingDirective(Scope *S, 6612 SourceLocation UsingLoc, 6613 SourceLocation NamespcLoc, 6614 CXXScopeSpec &SS, 6615 SourceLocation IdentLoc, 6616 IdentifierInfo *NamespcName, 6617 AttributeList *AttrList) { 6618 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6619 assert(NamespcName && "Invalid NamespcName."); 6620 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6621 6622 // This can only happen along a recovery path. 6623 while (S->getFlags() & Scope::TemplateParamScope) 6624 S = S->getParent(); 6625 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6626 6627 UsingDirectiveDecl *UDir = 0; 6628 NestedNameSpecifier *Qualifier = 0; 6629 if (SS.isSet()) 6630 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6631 6632 // Lookup namespace name. 6633 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6634 LookupParsedName(R, S, &SS); 6635 if (R.isAmbiguous()) 6636 return 0; 6637 6638 if (R.empty()) { 6639 R.clear(); 6640 // Allow "using namespace std;" or "using namespace ::std;" even if 6641 // "std" hasn't been defined yet, for GCC compatibility. 6642 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6643 NamespcName->isStr("std")) { 6644 Diag(IdentLoc, diag::ext_using_undefined_std); 6645 R.addDecl(getOrCreateStdNamespace()); 6646 R.resolveKind(); 6647 } 6648 // Otherwise, attempt typo correction. 6649 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6650 } 6651 6652 if (!R.empty()) { 6653 NamedDecl *Named = R.getFoundDecl(); 6654 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6655 && "expected namespace decl"); 6656 // C++ [namespace.udir]p1: 6657 // A using-directive specifies that the names in the nominated 6658 // namespace can be used in the scope in which the 6659 // using-directive appears after the using-directive. During 6660 // unqualified name lookup (3.4.1), the names appear as if they 6661 // were declared in the nearest enclosing namespace which 6662 // contains both the using-directive and the nominated 6663 // namespace. [Note: in this context, "contains" means "contains 6664 // directly or indirectly". ] 6665 6666 // Find enclosing context containing both using-directive and 6667 // nominated namespace. 6668 NamespaceDecl *NS = getNamespaceDecl(Named); 6669 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6670 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6671 CommonAncestor = CommonAncestor->getParent(); 6672 6673 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6674 SS.getWithLocInContext(Context), 6675 IdentLoc, Named, CommonAncestor); 6676 6677 if (IsUsingDirectiveInToplevelContext(CurContext) && 6678 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6679 Diag(IdentLoc, diag::warn_using_directive_in_header); 6680 } 6681 6682 PushUsingDirective(S, UDir); 6683 } else { 6684 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6685 } 6686 6687 if (UDir) 6688 ProcessDeclAttributeList(S, UDir, AttrList); 6689 6690 return UDir; 6691} 6692 6693void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6694 // If the scope has an associated entity and the using directive is at 6695 // namespace or translation unit scope, add the UsingDirectiveDecl into 6696 // its lookup structure so qualified name lookup can find it. 6697 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6698 if (Ctx && !Ctx->isFunctionOrMethod()) 6699 Ctx->addDecl(UDir); 6700 else 6701 // Otherwise, it is at block sope. The using-directives will affect lookup 6702 // only to the end of the scope. 6703 S->PushUsingDirective(UDir); 6704} 6705 6706 6707Decl *Sema::ActOnUsingDeclaration(Scope *S, 6708 AccessSpecifier AS, 6709 bool HasUsingKeyword, 6710 SourceLocation UsingLoc, 6711 CXXScopeSpec &SS, 6712 UnqualifiedId &Name, 6713 AttributeList *AttrList, 6714 bool IsTypeName, 6715 SourceLocation TypenameLoc) { 6716 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6717 6718 switch (Name.getKind()) { 6719 case UnqualifiedId::IK_ImplicitSelfParam: 6720 case UnqualifiedId::IK_Identifier: 6721 case UnqualifiedId::IK_OperatorFunctionId: 6722 case UnqualifiedId::IK_LiteralOperatorId: 6723 case UnqualifiedId::IK_ConversionFunctionId: 6724 break; 6725 6726 case UnqualifiedId::IK_ConstructorName: 6727 case UnqualifiedId::IK_ConstructorTemplateId: 6728 // C++11 inheriting constructors. 6729 Diag(Name.getLocStart(), 6730 getLangOpts().CPlusPlus11 ? 6731 diag::warn_cxx98_compat_using_decl_constructor : 6732 diag::err_using_decl_constructor) 6733 << SS.getRange(); 6734 6735 if (getLangOpts().CPlusPlus11) break; 6736 6737 return 0; 6738 6739 case UnqualifiedId::IK_DestructorName: 6740 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6741 << SS.getRange(); 6742 return 0; 6743 6744 case UnqualifiedId::IK_TemplateId: 6745 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6746 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6747 return 0; 6748 } 6749 6750 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6751 DeclarationName TargetName = TargetNameInfo.getName(); 6752 if (!TargetName) 6753 return 0; 6754 6755 // Warn about access declarations. 6756 // TODO: store that the declaration was written without 'using' and 6757 // talk about access decls instead of using decls in the 6758 // diagnostics. 6759 if (!HasUsingKeyword) { 6760 UsingLoc = Name.getLocStart(); 6761 6762 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6763 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6764 } 6765 6766 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6767 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6768 return 0; 6769 6770 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6771 TargetNameInfo, AttrList, 6772 /* IsInstantiation */ false, 6773 IsTypeName, TypenameLoc); 6774 if (UD) 6775 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6776 6777 return UD; 6778} 6779 6780/// \brief Determine whether a using declaration considers the given 6781/// declarations as "equivalent", e.g., if they are redeclarations of 6782/// the same entity or are both typedefs of the same type. 6783static bool 6784IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6785 bool &SuppressRedeclaration) { 6786 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6787 SuppressRedeclaration = false; 6788 return true; 6789 } 6790 6791 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6792 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6793 SuppressRedeclaration = true; 6794 return Context.hasSameType(TD1->getUnderlyingType(), 6795 TD2->getUnderlyingType()); 6796 } 6797 6798 return false; 6799} 6800 6801 6802/// Determines whether to create a using shadow decl for a particular 6803/// decl, given the set of decls existing prior to this using lookup. 6804bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6805 const LookupResult &Previous) { 6806 // Diagnose finding a decl which is not from a base class of the 6807 // current class. We do this now because there are cases where this 6808 // function will silently decide not to build a shadow decl, which 6809 // will pre-empt further diagnostics. 6810 // 6811 // We don't need to do this in C++0x because we do the check once on 6812 // the qualifier. 6813 // 6814 // FIXME: diagnose the following if we care enough: 6815 // struct A { int foo; }; 6816 // struct B : A { using A::foo; }; 6817 // template <class T> struct C : A {}; 6818 // template <class T> struct D : C<T> { using B::foo; } // <--- 6819 // This is invalid (during instantiation) in C++03 because B::foo 6820 // resolves to the using decl in B, which is not a base class of D<T>. 6821 // We can't diagnose it immediately because C<T> is an unknown 6822 // specialization. The UsingShadowDecl in D<T> then points directly 6823 // to A::foo, which will look well-formed when we instantiate. 6824 // The right solution is to not collapse the shadow-decl chain. 6825 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6826 DeclContext *OrigDC = Orig->getDeclContext(); 6827 6828 // Handle enums and anonymous structs. 6829 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6830 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6831 while (OrigRec->isAnonymousStructOrUnion()) 6832 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6833 6834 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6835 if (OrigDC == CurContext) { 6836 Diag(Using->getLocation(), 6837 diag::err_using_decl_nested_name_specifier_is_current_class) 6838 << Using->getQualifierLoc().getSourceRange(); 6839 Diag(Orig->getLocation(), diag::note_using_decl_target); 6840 return true; 6841 } 6842 6843 Diag(Using->getQualifierLoc().getBeginLoc(), 6844 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6845 << Using->getQualifier() 6846 << cast<CXXRecordDecl>(CurContext) 6847 << Using->getQualifierLoc().getSourceRange(); 6848 Diag(Orig->getLocation(), diag::note_using_decl_target); 6849 return true; 6850 } 6851 } 6852 6853 if (Previous.empty()) return false; 6854 6855 NamedDecl *Target = Orig; 6856 if (isa<UsingShadowDecl>(Target)) 6857 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6858 6859 // If the target happens to be one of the previous declarations, we 6860 // don't have a conflict. 6861 // 6862 // FIXME: but we might be increasing its access, in which case we 6863 // should redeclare it. 6864 NamedDecl *NonTag = 0, *Tag = 0; 6865 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6866 I != E; ++I) { 6867 NamedDecl *D = (*I)->getUnderlyingDecl(); 6868 bool Result; 6869 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6870 return Result; 6871 6872 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6873 } 6874 6875 if (Target->isFunctionOrFunctionTemplate()) { 6876 FunctionDecl *FD; 6877 if (isa<FunctionTemplateDecl>(Target)) 6878 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6879 else 6880 FD = cast<FunctionDecl>(Target); 6881 6882 NamedDecl *OldDecl = 0; 6883 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6884 case Ovl_Overload: 6885 return false; 6886 6887 case Ovl_NonFunction: 6888 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6889 break; 6890 6891 // We found a decl with the exact signature. 6892 case Ovl_Match: 6893 // If we're in a record, we want to hide the target, so we 6894 // return true (without a diagnostic) to tell the caller not to 6895 // build a shadow decl. 6896 if (CurContext->isRecord()) 6897 return true; 6898 6899 // If we're not in a record, this is an error. 6900 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6901 break; 6902 } 6903 6904 Diag(Target->getLocation(), diag::note_using_decl_target); 6905 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6906 return true; 6907 } 6908 6909 // Target is not a function. 6910 6911 if (isa<TagDecl>(Target)) { 6912 // No conflict between a tag and a non-tag. 6913 if (!Tag) return false; 6914 6915 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6916 Diag(Target->getLocation(), diag::note_using_decl_target); 6917 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6918 return true; 6919 } 6920 6921 // No conflict between a tag and a non-tag. 6922 if (!NonTag) return false; 6923 6924 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6925 Diag(Target->getLocation(), diag::note_using_decl_target); 6926 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6927 return true; 6928} 6929 6930/// Builds a shadow declaration corresponding to a 'using' declaration. 6931UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6932 UsingDecl *UD, 6933 NamedDecl *Orig) { 6934 6935 // If we resolved to another shadow declaration, just coalesce them. 6936 NamedDecl *Target = Orig; 6937 if (isa<UsingShadowDecl>(Target)) { 6938 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6939 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6940 } 6941 6942 UsingShadowDecl *Shadow 6943 = UsingShadowDecl::Create(Context, CurContext, 6944 UD->getLocation(), UD, Target); 6945 UD->addShadowDecl(Shadow); 6946 6947 Shadow->setAccess(UD->getAccess()); 6948 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6949 Shadow->setInvalidDecl(); 6950 6951 if (S) 6952 PushOnScopeChains(Shadow, S); 6953 else 6954 CurContext->addDecl(Shadow); 6955 6956 6957 return Shadow; 6958} 6959 6960/// Hides a using shadow declaration. This is required by the current 6961/// using-decl implementation when a resolvable using declaration in a 6962/// class is followed by a declaration which would hide or override 6963/// one or more of the using decl's targets; for example: 6964/// 6965/// struct Base { void foo(int); }; 6966/// struct Derived : Base { 6967/// using Base::foo; 6968/// void foo(int); 6969/// }; 6970/// 6971/// The governing language is C++03 [namespace.udecl]p12: 6972/// 6973/// When a using-declaration brings names from a base class into a 6974/// derived class scope, member functions in the derived class 6975/// override and/or hide member functions with the same name and 6976/// parameter types in a base class (rather than conflicting). 6977/// 6978/// There are two ways to implement this: 6979/// (1) optimistically create shadow decls when they're not hidden 6980/// by existing declarations, or 6981/// (2) don't create any shadow decls (or at least don't make them 6982/// visible) until we've fully parsed/instantiated the class. 6983/// The problem with (1) is that we might have to retroactively remove 6984/// a shadow decl, which requires several O(n) operations because the 6985/// decl structures are (very reasonably) not designed for removal. 6986/// (2) avoids this but is very fiddly and phase-dependent. 6987void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6988 if (Shadow->getDeclName().getNameKind() == 6989 DeclarationName::CXXConversionFunctionName) 6990 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6991 6992 // Remove it from the DeclContext... 6993 Shadow->getDeclContext()->removeDecl(Shadow); 6994 6995 // ...and the scope, if applicable... 6996 if (S) { 6997 S->RemoveDecl(Shadow); 6998 IdResolver.RemoveDecl(Shadow); 6999 } 7000 7001 // ...and the using decl. 7002 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7003 7004 // TODO: complain somehow if Shadow was used. It shouldn't 7005 // be possible for this to happen, because...? 7006} 7007 7008/// Builds a using declaration. 7009/// 7010/// \param IsInstantiation - Whether this call arises from an 7011/// instantiation of an unresolved using declaration. We treat 7012/// the lookup differently for these declarations. 7013NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7014 SourceLocation UsingLoc, 7015 CXXScopeSpec &SS, 7016 const DeclarationNameInfo &NameInfo, 7017 AttributeList *AttrList, 7018 bool IsInstantiation, 7019 bool IsTypeName, 7020 SourceLocation TypenameLoc) { 7021 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7022 SourceLocation IdentLoc = NameInfo.getLoc(); 7023 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7024 7025 // FIXME: We ignore attributes for now. 7026 7027 if (SS.isEmpty()) { 7028 Diag(IdentLoc, diag::err_using_requires_qualname); 7029 return 0; 7030 } 7031 7032 // Do the redeclaration lookup in the current scope. 7033 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7034 ForRedeclaration); 7035 Previous.setHideTags(false); 7036 if (S) { 7037 LookupName(Previous, S); 7038 7039 // It is really dumb that we have to do this. 7040 LookupResult::Filter F = Previous.makeFilter(); 7041 while (F.hasNext()) { 7042 NamedDecl *D = F.next(); 7043 if (!isDeclInScope(D, CurContext, S)) 7044 F.erase(); 7045 } 7046 F.done(); 7047 } else { 7048 assert(IsInstantiation && "no scope in non-instantiation"); 7049 assert(CurContext->isRecord() && "scope not record in instantiation"); 7050 LookupQualifiedName(Previous, CurContext); 7051 } 7052 7053 // Check for invalid redeclarations. 7054 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 7055 return 0; 7056 7057 // Check for bad qualifiers. 7058 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7059 return 0; 7060 7061 DeclContext *LookupContext = computeDeclContext(SS); 7062 NamedDecl *D; 7063 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7064 if (!LookupContext) { 7065 if (IsTypeName) { 7066 // FIXME: not all declaration name kinds are legal here 7067 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7068 UsingLoc, TypenameLoc, 7069 QualifierLoc, 7070 IdentLoc, NameInfo.getName()); 7071 } else { 7072 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7073 QualifierLoc, NameInfo); 7074 } 7075 } else { 7076 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7077 NameInfo, IsTypeName); 7078 } 7079 D->setAccess(AS); 7080 CurContext->addDecl(D); 7081 7082 if (!LookupContext) return D; 7083 UsingDecl *UD = cast<UsingDecl>(D); 7084 7085 if (RequireCompleteDeclContext(SS, LookupContext)) { 7086 UD->setInvalidDecl(); 7087 return UD; 7088 } 7089 7090 // The normal rules do not apply to inheriting constructor declarations. 7091 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7092 if (CheckInheritingConstructorUsingDecl(UD)) 7093 UD->setInvalidDecl(); 7094 return UD; 7095 } 7096 7097 // Otherwise, look up the target name. 7098 7099 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7100 7101 // Unlike most lookups, we don't always want to hide tag 7102 // declarations: tag names are visible through the using declaration 7103 // even if hidden by ordinary names, *except* in a dependent context 7104 // where it's important for the sanity of two-phase lookup. 7105 if (!IsInstantiation) 7106 R.setHideTags(false); 7107 7108 // For the purposes of this lookup, we have a base object type 7109 // equal to that of the current context. 7110 if (CurContext->isRecord()) { 7111 R.setBaseObjectType( 7112 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7113 } 7114 7115 LookupQualifiedName(R, LookupContext); 7116 7117 if (R.empty()) { 7118 Diag(IdentLoc, diag::err_no_member) 7119 << NameInfo.getName() << LookupContext << SS.getRange(); 7120 UD->setInvalidDecl(); 7121 return UD; 7122 } 7123 7124 if (R.isAmbiguous()) { 7125 UD->setInvalidDecl(); 7126 return UD; 7127 } 7128 7129 if (IsTypeName) { 7130 // If we asked for a typename and got a non-type decl, error out. 7131 if (!R.getAsSingle<TypeDecl>()) { 7132 Diag(IdentLoc, diag::err_using_typename_non_type); 7133 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7134 Diag((*I)->getUnderlyingDecl()->getLocation(), 7135 diag::note_using_decl_target); 7136 UD->setInvalidDecl(); 7137 return UD; 7138 } 7139 } else { 7140 // If we asked for a non-typename and we got a type, error out, 7141 // but only if this is an instantiation of an unresolved using 7142 // decl. Otherwise just silently find the type name. 7143 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7144 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7145 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7146 UD->setInvalidDecl(); 7147 return UD; 7148 } 7149 } 7150 7151 // C++0x N2914 [namespace.udecl]p6: 7152 // A using-declaration shall not name a namespace. 7153 if (R.getAsSingle<NamespaceDecl>()) { 7154 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7155 << SS.getRange(); 7156 UD->setInvalidDecl(); 7157 return UD; 7158 } 7159 7160 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7161 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7162 BuildUsingShadowDecl(S, UD, *I); 7163 } 7164 7165 return UD; 7166} 7167 7168/// Additional checks for a using declaration referring to a constructor name. 7169bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7170 assert(!UD->isTypeName() && "expecting a constructor name"); 7171 7172 const Type *SourceType = UD->getQualifier()->getAsType(); 7173 assert(SourceType && 7174 "Using decl naming constructor doesn't have type in scope spec."); 7175 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7176 7177 // Check whether the named type is a direct base class. 7178 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7179 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7180 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7181 BaseIt != BaseE; ++BaseIt) { 7182 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7183 if (CanonicalSourceType == BaseType) 7184 break; 7185 if (BaseIt->getType()->isDependentType()) 7186 break; 7187 } 7188 7189 if (BaseIt == BaseE) { 7190 // Did not find SourceType in the bases. 7191 Diag(UD->getUsingLocation(), 7192 diag::err_using_decl_constructor_not_in_direct_base) 7193 << UD->getNameInfo().getSourceRange() 7194 << QualType(SourceType, 0) << TargetClass; 7195 return true; 7196 } 7197 7198 if (!CurContext->isDependentContext()) 7199 BaseIt->setInheritConstructors(); 7200 7201 return false; 7202} 7203 7204/// Checks that the given using declaration is not an invalid 7205/// redeclaration. Note that this is checking only for the using decl 7206/// itself, not for any ill-formedness among the UsingShadowDecls. 7207bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7208 bool isTypeName, 7209 const CXXScopeSpec &SS, 7210 SourceLocation NameLoc, 7211 const LookupResult &Prev) { 7212 // C++03 [namespace.udecl]p8: 7213 // C++0x [namespace.udecl]p10: 7214 // A using-declaration is a declaration and can therefore be used 7215 // repeatedly where (and only where) multiple declarations are 7216 // allowed. 7217 // 7218 // That's in non-member contexts. 7219 if (!CurContext->getRedeclContext()->isRecord()) 7220 return false; 7221 7222 NestedNameSpecifier *Qual 7223 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7224 7225 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7226 NamedDecl *D = *I; 7227 7228 bool DTypename; 7229 NestedNameSpecifier *DQual; 7230 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7231 DTypename = UD->isTypeName(); 7232 DQual = UD->getQualifier(); 7233 } else if (UnresolvedUsingValueDecl *UD 7234 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7235 DTypename = false; 7236 DQual = UD->getQualifier(); 7237 } else if (UnresolvedUsingTypenameDecl *UD 7238 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7239 DTypename = true; 7240 DQual = UD->getQualifier(); 7241 } else continue; 7242 7243 // using decls differ if one says 'typename' and the other doesn't. 7244 // FIXME: non-dependent using decls? 7245 if (isTypeName != DTypename) continue; 7246 7247 // using decls differ if they name different scopes (but note that 7248 // template instantiation can cause this check to trigger when it 7249 // didn't before instantiation). 7250 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7251 Context.getCanonicalNestedNameSpecifier(DQual)) 7252 continue; 7253 7254 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7255 Diag(D->getLocation(), diag::note_using_decl) << 1; 7256 return true; 7257 } 7258 7259 return false; 7260} 7261 7262 7263/// Checks that the given nested-name qualifier used in a using decl 7264/// in the current context is appropriately related to the current 7265/// scope. If an error is found, diagnoses it and returns true. 7266bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7267 const CXXScopeSpec &SS, 7268 SourceLocation NameLoc) { 7269 DeclContext *NamedContext = computeDeclContext(SS); 7270 7271 if (!CurContext->isRecord()) { 7272 // C++03 [namespace.udecl]p3: 7273 // C++0x [namespace.udecl]p8: 7274 // A using-declaration for a class member shall be a member-declaration. 7275 7276 // If we weren't able to compute a valid scope, it must be a 7277 // dependent class scope. 7278 if (!NamedContext || NamedContext->isRecord()) { 7279 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7280 << SS.getRange(); 7281 return true; 7282 } 7283 7284 // Otherwise, everything is known to be fine. 7285 return false; 7286 } 7287 7288 // The current scope is a record. 7289 7290 // If the named context is dependent, we can't decide much. 7291 if (!NamedContext) { 7292 // FIXME: in C++0x, we can diagnose if we can prove that the 7293 // nested-name-specifier does not refer to a base class, which is 7294 // still possible in some cases. 7295 7296 // Otherwise we have to conservatively report that things might be 7297 // okay. 7298 return false; 7299 } 7300 7301 if (!NamedContext->isRecord()) { 7302 // Ideally this would point at the last name in the specifier, 7303 // but we don't have that level of source info. 7304 Diag(SS.getRange().getBegin(), 7305 diag::err_using_decl_nested_name_specifier_is_not_class) 7306 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7307 return true; 7308 } 7309 7310 if (!NamedContext->isDependentContext() && 7311 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7312 return true; 7313 7314 if (getLangOpts().CPlusPlus11) { 7315 // C++0x [namespace.udecl]p3: 7316 // In a using-declaration used as a member-declaration, the 7317 // nested-name-specifier shall name a base class of the class 7318 // being defined. 7319 7320 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7321 cast<CXXRecordDecl>(NamedContext))) { 7322 if (CurContext == NamedContext) { 7323 Diag(NameLoc, 7324 diag::err_using_decl_nested_name_specifier_is_current_class) 7325 << SS.getRange(); 7326 return true; 7327 } 7328 7329 Diag(SS.getRange().getBegin(), 7330 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7331 << (NestedNameSpecifier*) SS.getScopeRep() 7332 << cast<CXXRecordDecl>(CurContext) 7333 << SS.getRange(); 7334 return true; 7335 } 7336 7337 return false; 7338 } 7339 7340 // C++03 [namespace.udecl]p4: 7341 // A using-declaration used as a member-declaration shall refer 7342 // to a member of a base class of the class being defined [etc.]. 7343 7344 // Salient point: SS doesn't have to name a base class as long as 7345 // lookup only finds members from base classes. Therefore we can 7346 // diagnose here only if we can prove that that can't happen, 7347 // i.e. if the class hierarchies provably don't intersect. 7348 7349 // TODO: it would be nice if "definitely valid" results were cached 7350 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7351 // need to be repeated. 7352 7353 struct UserData { 7354 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7355 7356 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7357 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7358 Data->Bases.insert(Base); 7359 return true; 7360 } 7361 7362 bool hasDependentBases(const CXXRecordDecl *Class) { 7363 return !Class->forallBases(collect, this); 7364 } 7365 7366 /// Returns true if the base is dependent or is one of the 7367 /// accumulated base classes. 7368 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7369 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7370 return !Data->Bases.count(Base); 7371 } 7372 7373 bool mightShareBases(const CXXRecordDecl *Class) { 7374 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7375 } 7376 }; 7377 7378 UserData Data; 7379 7380 // Returns false if we find a dependent base. 7381 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7382 return false; 7383 7384 // Returns false if the class has a dependent base or if it or one 7385 // of its bases is present in the base set of the current context. 7386 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7387 return false; 7388 7389 Diag(SS.getRange().getBegin(), 7390 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7391 << (NestedNameSpecifier*) SS.getScopeRep() 7392 << cast<CXXRecordDecl>(CurContext) 7393 << SS.getRange(); 7394 7395 return true; 7396} 7397 7398Decl *Sema::ActOnAliasDeclaration(Scope *S, 7399 AccessSpecifier AS, 7400 MultiTemplateParamsArg TemplateParamLists, 7401 SourceLocation UsingLoc, 7402 UnqualifiedId &Name, 7403 AttributeList *AttrList, 7404 TypeResult Type) { 7405 // Skip up to the relevant declaration scope. 7406 while (S->getFlags() & Scope::TemplateParamScope) 7407 S = S->getParent(); 7408 assert((S->getFlags() & Scope::DeclScope) && 7409 "got alias-declaration outside of declaration scope"); 7410 7411 if (Type.isInvalid()) 7412 return 0; 7413 7414 bool Invalid = false; 7415 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7416 TypeSourceInfo *TInfo = 0; 7417 GetTypeFromParser(Type.get(), &TInfo); 7418 7419 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7420 return 0; 7421 7422 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7423 UPPC_DeclarationType)) { 7424 Invalid = true; 7425 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7426 TInfo->getTypeLoc().getBeginLoc()); 7427 } 7428 7429 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7430 LookupName(Previous, S); 7431 7432 // Warn about shadowing the name of a template parameter. 7433 if (Previous.isSingleResult() && 7434 Previous.getFoundDecl()->isTemplateParameter()) { 7435 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7436 Previous.clear(); 7437 } 7438 7439 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7440 "name in alias declaration must be an identifier"); 7441 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7442 Name.StartLocation, 7443 Name.Identifier, TInfo); 7444 7445 NewTD->setAccess(AS); 7446 7447 if (Invalid) 7448 NewTD->setInvalidDecl(); 7449 7450 ProcessDeclAttributeList(S, NewTD, AttrList); 7451 7452 CheckTypedefForVariablyModifiedType(S, NewTD); 7453 Invalid |= NewTD->isInvalidDecl(); 7454 7455 bool Redeclaration = false; 7456 7457 NamedDecl *NewND; 7458 if (TemplateParamLists.size()) { 7459 TypeAliasTemplateDecl *OldDecl = 0; 7460 TemplateParameterList *OldTemplateParams = 0; 7461 7462 if (TemplateParamLists.size() != 1) { 7463 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7464 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7465 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7466 } 7467 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7468 7469 // Only consider previous declarations in the same scope. 7470 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7471 /*ExplicitInstantiationOrSpecialization*/false); 7472 if (!Previous.empty()) { 7473 Redeclaration = true; 7474 7475 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7476 if (!OldDecl && !Invalid) { 7477 Diag(UsingLoc, diag::err_redefinition_different_kind) 7478 << Name.Identifier; 7479 7480 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7481 if (OldD->getLocation().isValid()) 7482 Diag(OldD->getLocation(), diag::note_previous_definition); 7483 7484 Invalid = true; 7485 } 7486 7487 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7488 if (TemplateParameterListsAreEqual(TemplateParams, 7489 OldDecl->getTemplateParameters(), 7490 /*Complain=*/true, 7491 TPL_TemplateMatch)) 7492 OldTemplateParams = OldDecl->getTemplateParameters(); 7493 else 7494 Invalid = true; 7495 7496 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7497 if (!Invalid && 7498 !Context.hasSameType(OldTD->getUnderlyingType(), 7499 NewTD->getUnderlyingType())) { 7500 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7501 // but we can't reasonably accept it. 7502 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7503 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7504 if (OldTD->getLocation().isValid()) 7505 Diag(OldTD->getLocation(), diag::note_previous_definition); 7506 Invalid = true; 7507 } 7508 } 7509 } 7510 7511 // Merge any previous default template arguments into our parameters, 7512 // and check the parameter list. 7513 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7514 TPC_TypeAliasTemplate)) 7515 return 0; 7516 7517 TypeAliasTemplateDecl *NewDecl = 7518 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7519 Name.Identifier, TemplateParams, 7520 NewTD); 7521 7522 NewDecl->setAccess(AS); 7523 7524 if (Invalid) 7525 NewDecl->setInvalidDecl(); 7526 else if (OldDecl) 7527 NewDecl->setPreviousDeclaration(OldDecl); 7528 7529 NewND = NewDecl; 7530 } else { 7531 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7532 NewND = NewTD; 7533 } 7534 7535 if (!Redeclaration) 7536 PushOnScopeChains(NewND, S); 7537 7538 ActOnDocumentableDecl(NewND); 7539 return NewND; 7540} 7541 7542Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7543 SourceLocation NamespaceLoc, 7544 SourceLocation AliasLoc, 7545 IdentifierInfo *Alias, 7546 CXXScopeSpec &SS, 7547 SourceLocation IdentLoc, 7548 IdentifierInfo *Ident) { 7549 7550 // Lookup the namespace name. 7551 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7552 LookupParsedName(R, S, &SS); 7553 7554 // Check if we have a previous declaration with the same name. 7555 NamedDecl *PrevDecl 7556 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7557 ForRedeclaration); 7558 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7559 PrevDecl = 0; 7560 7561 if (PrevDecl) { 7562 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7563 // We already have an alias with the same name that points to the same 7564 // namespace, so don't create a new one. 7565 // FIXME: At some point, we'll want to create the (redundant) 7566 // declaration to maintain better source information. 7567 if (!R.isAmbiguous() && !R.empty() && 7568 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7569 return 0; 7570 } 7571 7572 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7573 diag::err_redefinition_different_kind; 7574 Diag(AliasLoc, DiagID) << Alias; 7575 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7576 return 0; 7577 } 7578 7579 if (R.isAmbiguous()) 7580 return 0; 7581 7582 if (R.empty()) { 7583 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7584 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7585 return 0; 7586 } 7587 } 7588 7589 NamespaceAliasDecl *AliasDecl = 7590 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7591 Alias, SS.getWithLocInContext(Context), 7592 IdentLoc, R.getFoundDecl()); 7593 7594 PushOnScopeChains(AliasDecl, S); 7595 return AliasDecl; 7596} 7597 7598Sema::ImplicitExceptionSpecification 7599Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7600 CXXMethodDecl *MD) { 7601 CXXRecordDecl *ClassDecl = MD->getParent(); 7602 7603 // C++ [except.spec]p14: 7604 // An implicitly declared special member function (Clause 12) shall have an 7605 // exception-specification. [...] 7606 ImplicitExceptionSpecification ExceptSpec(*this); 7607 if (ClassDecl->isInvalidDecl()) 7608 return ExceptSpec; 7609 7610 // Direct base-class constructors. 7611 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7612 BEnd = ClassDecl->bases_end(); 7613 B != BEnd; ++B) { 7614 if (B->isVirtual()) // Handled below. 7615 continue; 7616 7617 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7618 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7619 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7620 // If this is a deleted function, add it anyway. This might be conformant 7621 // with the standard. This might not. I'm not sure. It might not matter. 7622 if (Constructor) 7623 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7624 } 7625 } 7626 7627 // Virtual base-class constructors. 7628 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7629 BEnd = ClassDecl->vbases_end(); 7630 B != BEnd; ++B) { 7631 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7632 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7633 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7634 // If this is a deleted function, add it anyway. This might be conformant 7635 // with the standard. This might not. I'm not sure. It might not matter. 7636 if (Constructor) 7637 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7638 } 7639 } 7640 7641 // Field constructors. 7642 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7643 FEnd = ClassDecl->field_end(); 7644 F != FEnd; ++F) { 7645 if (F->hasInClassInitializer()) { 7646 if (Expr *E = F->getInClassInitializer()) 7647 ExceptSpec.CalledExpr(E); 7648 else if (!F->isInvalidDecl()) 7649 // DR1351: 7650 // If the brace-or-equal-initializer of a non-static data member 7651 // invokes a defaulted default constructor of its class or of an 7652 // enclosing class in a potentially evaluated subexpression, the 7653 // program is ill-formed. 7654 // 7655 // This resolution is unworkable: the exception specification of the 7656 // default constructor can be needed in an unevaluated context, in 7657 // particular, in the operand of a noexcept-expression, and we can be 7658 // unable to compute an exception specification for an enclosed class. 7659 // 7660 // We do not allow an in-class initializer to require the evaluation 7661 // of the exception specification for any in-class initializer whose 7662 // definition is not lexically complete. 7663 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7664 } else if (const RecordType *RecordTy 7665 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7666 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7667 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7668 // If this is a deleted function, add it anyway. This might be conformant 7669 // with the standard. This might not. I'm not sure. It might not matter. 7670 // In particular, the problem is that this function never gets called. It 7671 // might just be ill-formed because this function attempts to refer to 7672 // a deleted function here. 7673 if (Constructor) 7674 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7675 } 7676 } 7677 7678 return ExceptSpec; 7679} 7680 7681Sema::ImplicitExceptionSpecification 7682Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7683 CXXRecordDecl *ClassDecl = CD->getParent(); 7684 7685 // C++ [except.spec]p14: 7686 // An inheriting constructor [...] shall have an exception-specification. [...] 7687 ImplicitExceptionSpecification ExceptSpec(*this); 7688 if (ClassDecl->isInvalidDecl()) 7689 return ExceptSpec; 7690 7691 // Inherited constructor. 7692 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7693 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7694 // FIXME: Copying or moving the parameters could add extra exceptions to the 7695 // set, as could the default arguments for the inherited constructor. This 7696 // will be addressed when we implement the resolution of core issue 1351. 7697 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7698 7699 // Direct base-class constructors. 7700 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7701 BEnd = ClassDecl->bases_end(); 7702 B != BEnd; ++B) { 7703 if (B->isVirtual()) // Handled below. 7704 continue; 7705 7706 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7707 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7708 if (BaseClassDecl == InheritedDecl) 7709 continue; 7710 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7711 if (Constructor) 7712 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7713 } 7714 } 7715 7716 // Virtual base-class constructors. 7717 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7718 BEnd = ClassDecl->vbases_end(); 7719 B != BEnd; ++B) { 7720 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7721 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7722 if (BaseClassDecl == InheritedDecl) 7723 continue; 7724 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7725 if (Constructor) 7726 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7727 } 7728 } 7729 7730 // Field constructors. 7731 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7732 FEnd = ClassDecl->field_end(); 7733 F != FEnd; ++F) { 7734 if (F->hasInClassInitializer()) { 7735 if (Expr *E = F->getInClassInitializer()) 7736 ExceptSpec.CalledExpr(E); 7737 else if (!F->isInvalidDecl()) 7738 Diag(CD->getLocation(), 7739 diag::err_in_class_initializer_references_def_ctor) << CD; 7740 } else if (const RecordType *RecordTy 7741 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7742 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7743 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7744 if (Constructor) 7745 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7746 } 7747 } 7748 7749 return ExceptSpec; 7750} 7751 7752namespace { 7753/// RAII object to register a special member as being currently declared. 7754struct DeclaringSpecialMember { 7755 Sema &S; 7756 Sema::SpecialMemberDecl D; 7757 bool WasAlreadyBeingDeclared; 7758 7759 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7760 : S(S), D(RD, CSM) { 7761 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7762 if (WasAlreadyBeingDeclared) 7763 // This almost never happens, but if it does, ensure that our cache 7764 // doesn't contain a stale result. 7765 S.SpecialMemberCache.clear(); 7766 7767 // FIXME: Register a note to be produced if we encounter an error while 7768 // declaring the special member. 7769 } 7770 ~DeclaringSpecialMember() { 7771 if (!WasAlreadyBeingDeclared) 7772 S.SpecialMembersBeingDeclared.erase(D); 7773 } 7774 7775 /// \brief Are we already trying to declare this special member? 7776 bool isAlreadyBeingDeclared() const { 7777 return WasAlreadyBeingDeclared; 7778 } 7779}; 7780} 7781 7782CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7783 CXXRecordDecl *ClassDecl) { 7784 // C++ [class.ctor]p5: 7785 // A default constructor for a class X is a constructor of class X 7786 // that can be called without an argument. If there is no 7787 // user-declared constructor for class X, a default constructor is 7788 // implicitly declared. An implicitly-declared default constructor 7789 // is an inline public member of its class. 7790 assert(ClassDecl->needsImplicitDefaultConstructor() && 7791 "Should not build implicit default constructor!"); 7792 7793 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7794 if (DSM.isAlreadyBeingDeclared()) 7795 return 0; 7796 7797 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7798 CXXDefaultConstructor, 7799 false); 7800 7801 // Create the actual constructor declaration. 7802 CanQualType ClassType 7803 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7804 SourceLocation ClassLoc = ClassDecl->getLocation(); 7805 DeclarationName Name 7806 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7807 DeclarationNameInfo NameInfo(Name, ClassLoc); 7808 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7809 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7810 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7811 Constexpr); 7812 DefaultCon->setAccess(AS_public); 7813 DefaultCon->setDefaulted(); 7814 DefaultCon->setImplicit(); 7815 7816 // Build an exception specification pointing back at this constructor. 7817 FunctionProtoType::ExtProtoInfo EPI; 7818 EPI.ExceptionSpecType = EST_Unevaluated; 7819 EPI.ExceptionSpecDecl = DefaultCon; 7820 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 7821 7822 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7823 // constructors is easy to compute. 7824 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7825 7826 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7827 SetDeclDeleted(DefaultCon, ClassLoc); 7828 7829 // Note that we have declared this constructor. 7830 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7831 7832 if (Scope *S = getScopeForContext(ClassDecl)) 7833 PushOnScopeChains(DefaultCon, S, false); 7834 ClassDecl->addDecl(DefaultCon); 7835 7836 return DefaultCon; 7837} 7838 7839void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7840 CXXConstructorDecl *Constructor) { 7841 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7842 !Constructor->doesThisDeclarationHaveABody() && 7843 !Constructor->isDeleted()) && 7844 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7845 7846 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7847 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7848 7849 SynthesizedFunctionScope Scope(*this, Constructor); 7850 DiagnosticErrorTrap Trap(Diags); 7851 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7852 Trap.hasErrorOccurred()) { 7853 Diag(CurrentLocation, diag::note_member_synthesized_at) 7854 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7855 Constructor->setInvalidDecl(); 7856 return; 7857 } 7858 7859 SourceLocation Loc = Constructor->getLocation(); 7860 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7861 7862 Constructor->setUsed(); 7863 MarkVTableUsed(CurrentLocation, ClassDecl); 7864 7865 if (ASTMutationListener *L = getASTMutationListener()) { 7866 L->CompletedImplicitDefinition(Constructor); 7867 } 7868} 7869 7870void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7871 // Check that any explicitly-defaulted methods have exception specifications 7872 // compatible with their implicit exception specifications. 7873 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7874} 7875 7876namespace { 7877/// Information on inheriting constructors to declare. 7878class InheritingConstructorInfo { 7879public: 7880 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 7881 : SemaRef(SemaRef), Derived(Derived) { 7882 // Mark the constructors that we already have in the derived class. 7883 // 7884 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7885 // unless there is a user-declared constructor with the same signature in 7886 // the class where the using-declaration appears. 7887 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 7888 } 7889 7890 void inheritAll(CXXRecordDecl *RD) { 7891 visitAll(RD, &InheritingConstructorInfo::inherit); 7892 } 7893 7894private: 7895 /// Information about an inheriting constructor. 7896 struct InheritingConstructor { 7897 InheritingConstructor() 7898 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 7899 7900 /// If \c true, a constructor with this signature is already declared 7901 /// in the derived class. 7902 bool DeclaredInDerived; 7903 7904 /// The constructor which is inherited. 7905 const CXXConstructorDecl *BaseCtor; 7906 7907 /// The derived constructor we declared. 7908 CXXConstructorDecl *DerivedCtor; 7909 }; 7910 7911 /// Inheriting constructors with a given canonical type. There can be at 7912 /// most one such non-template constructor, and any number of templated 7913 /// constructors. 7914 struct InheritingConstructorsForType { 7915 InheritingConstructor NonTemplate; 7916 llvm::SmallVector< 7917 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates; 7918 7919 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 7920 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 7921 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 7922 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 7923 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 7924 false, S.TPL_TemplateMatch)) 7925 return Templates[I].second; 7926 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 7927 return Templates.back().second; 7928 } 7929 7930 return NonTemplate; 7931 } 7932 }; 7933 7934 /// Get or create the inheriting constructor record for a constructor. 7935 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 7936 QualType CtorType) { 7937 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 7938 .getEntry(SemaRef, Ctor); 7939 } 7940 7941 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 7942 7943 /// Process all constructors for a class. 7944 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 7945 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 7946 CtorE = RD->ctor_end(); 7947 CtorIt != CtorE; ++CtorIt) 7948 (this->*Callback)(*CtorIt); 7949 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 7950 I(RD->decls_begin()), E(RD->decls_end()); 7951 I != E; ++I) { 7952 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 7953 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 7954 (this->*Callback)(CD); 7955 } 7956 } 7957 7958 /// Note that a constructor (or constructor template) was declared in Derived. 7959 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 7960 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 7961 } 7962 7963 /// Inherit a single constructor. 7964 void inherit(const CXXConstructorDecl *Ctor) { 7965 const FunctionProtoType *CtorType = 7966 Ctor->getType()->castAs<FunctionProtoType>(); 7967 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 7968 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 7969 7970 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 7971 7972 // Core issue (no number yet): the ellipsis is always discarded. 7973 if (EPI.Variadic) { 7974 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7975 SemaRef.Diag(Ctor->getLocation(), 7976 diag::note_using_decl_constructor_ellipsis); 7977 EPI.Variadic = false; 7978 } 7979 7980 // Declare a constructor for each number of parameters. 7981 // 7982 // C++11 [class.inhctor]p1: 7983 // The candidate set of inherited constructors from the class X named in 7984 // the using-declaration consists of [... modulo defects ...] for each 7985 // constructor or constructor template of X, the set of constructors or 7986 // constructor templates that results from omitting any ellipsis parameter 7987 // specification and successively omitting parameters with a default 7988 // argument from the end of the parameter-type-list 7989 unsigned MinParams = minParamsToInherit(Ctor); 7990 unsigned Params = Ctor->getNumParams(); 7991 if (Params >= MinParams) { 7992 do 7993 declareCtor(UsingLoc, Ctor, 7994 SemaRef.Context.getFunctionType( 7995 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 7996 while (Params > MinParams && 7997 Ctor->getParamDecl(--Params)->hasDefaultArg()); 7998 } 7999 } 8000 8001 /// Find the using-declaration which specified that we should inherit the 8002 /// constructors of \p Base. 8003 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8004 // No fancy lookup required; just look for the base constructor name 8005 // directly within the derived class. 8006 ASTContext &Context = SemaRef.Context; 8007 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8008 Context.getCanonicalType(Context.getRecordType(Base))); 8009 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8010 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8011 } 8012 8013 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8014 // C++11 [class.inhctor]p3: 8015 // [F]or each constructor template in the candidate set of inherited 8016 // constructors, a constructor template is implicitly declared 8017 if (Ctor->getDescribedFunctionTemplate()) 8018 return 0; 8019 8020 // For each non-template constructor in the candidate set of inherited 8021 // constructors other than a constructor having no parameters or a 8022 // copy/move constructor having a single parameter, a constructor is 8023 // implicitly declared [...] 8024 if (Ctor->getNumParams() == 0) 8025 return 1; 8026 if (Ctor->isCopyOrMoveConstructor()) 8027 return 2; 8028 8029 // Per discussion on core reflector, never inherit a constructor which 8030 // would become a default, copy, or move constructor of Derived either. 8031 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8032 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8033 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8034 } 8035 8036 /// Declare a single inheriting constructor, inheriting the specified 8037 /// constructor, with the given type. 8038 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8039 QualType DerivedType) { 8040 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8041 8042 // C++11 [class.inhctor]p3: 8043 // ... a constructor is implicitly declared with the same constructor 8044 // characteristics unless there is a user-declared constructor with 8045 // the same signature in the class where the using-declaration appears 8046 if (Entry.DeclaredInDerived) 8047 return; 8048 8049 // C++11 [class.inhctor]p7: 8050 // If two using-declarations declare inheriting constructors with the 8051 // same signature, the program is ill-formed 8052 if (Entry.DerivedCtor) { 8053 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8054 // Only diagnose this once per constructor. 8055 if (Entry.DerivedCtor->isInvalidDecl()) 8056 return; 8057 Entry.DerivedCtor->setInvalidDecl(); 8058 8059 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8060 SemaRef.Diag(BaseCtor->getLocation(), 8061 diag::note_using_decl_constructor_conflict_current_ctor); 8062 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8063 diag::note_using_decl_constructor_conflict_previous_ctor); 8064 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8065 diag::note_using_decl_constructor_conflict_previous_using); 8066 } else { 8067 // Core issue (no number): if the same inheriting constructor is 8068 // produced by multiple base class constructors from the same base 8069 // class, the inheriting constructor is defined as deleted. 8070 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8071 } 8072 8073 return; 8074 } 8075 8076 ASTContext &Context = SemaRef.Context; 8077 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8078 Context.getCanonicalType(Context.getRecordType(Derived))); 8079 DeclarationNameInfo NameInfo(Name, UsingLoc); 8080 8081 TemplateParameterList *TemplateParams = 0; 8082 if (const FunctionTemplateDecl *FTD = 8083 BaseCtor->getDescribedFunctionTemplate()) { 8084 TemplateParams = FTD->getTemplateParameters(); 8085 // We're reusing template parameters from a different DeclContext. This 8086 // is questionable at best, but works out because the template depth in 8087 // both places is guaranteed to be 0. 8088 // FIXME: Rebuild the template parameters in the new context, and 8089 // transform the function type to refer to them. 8090 } 8091 8092 // Build type source info pointing at the using-declaration. This is 8093 // required by template instantiation. 8094 TypeSourceInfo *TInfo = 8095 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8096 FunctionProtoTypeLoc ProtoLoc = 8097 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8098 8099 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8100 Context, Derived, UsingLoc, NameInfo, DerivedType, 8101 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8102 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8103 8104 // Build an unevaluated exception specification for this constructor. 8105 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8107 EPI.ExceptionSpecType = EST_Unevaluated; 8108 EPI.ExceptionSpecDecl = DerivedCtor; 8109 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8110 FPT->getArgTypes(), EPI)); 8111 8112 // Build the parameter declarations. 8113 SmallVector<ParmVarDecl *, 16> ParamDecls; 8114 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8115 TypeSourceInfo *TInfo = 8116 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8117 ParmVarDecl *PD = ParmVarDecl::Create( 8118 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8119 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8120 PD->setScopeInfo(0, I); 8121 PD->setImplicit(); 8122 ParamDecls.push_back(PD); 8123 ProtoLoc.setArg(I, PD); 8124 } 8125 8126 // Set up the new constructor. 8127 DerivedCtor->setAccess(BaseCtor->getAccess()); 8128 DerivedCtor->setParams(ParamDecls); 8129 DerivedCtor->setInheritedConstructor(BaseCtor); 8130 if (BaseCtor->isDeleted()) 8131 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8132 8133 // If this is a constructor template, build the template declaration. 8134 if (TemplateParams) { 8135 FunctionTemplateDecl *DerivedTemplate = 8136 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8137 TemplateParams, DerivedCtor); 8138 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8139 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8140 Derived->addDecl(DerivedTemplate); 8141 } else { 8142 Derived->addDecl(DerivedCtor); 8143 } 8144 8145 Entry.BaseCtor = BaseCtor; 8146 Entry.DerivedCtor = DerivedCtor; 8147 } 8148 8149 Sema &SemaRef; 8150 CXXRecordDecl *Derived; 8151 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8152 MapType Map; 8153}; 8154} 8155 8156void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8157 // Defer declaring the inheriting constructors until the class is 8158 // instantiated. 8159 if (ClassDecl->isDependentContext()) 8160 return; 8161 8162 // Find base classes from which we might inherit constructors. 8163 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8164 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8165 BaseE = ClassDecl->bases_end(); 8166 BaseIt != BaseE; ++BaseIt) 8167 if (BaseIt->getInheritConstructors()) 8168 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8169 8170 // Go no further if we're not inheriting any constructors. 8171 if (InheritedBases.empty()) 8172 return; 8173 8174 // Declare the inherited constructors. 8175 InheritingConstructorInfo ICI(*this, ClassDecl); 8176 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8177 ICI.inheritAll(InheritedBases[I]); 8178} 8179 8180void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8181 CXXConstructorDecl *Constructor) { 8182 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8183 assert(Constructor->getInheritedConstructor() && 8184 !Constructor->doesThisDeclarationHaveABody() && 8185 !Constructor->isDeleted()); 8186 8187 SynthesizedFunctionScope Scope(*this, Constructor); 8188 DiagnosticErrorTrap Trap(Diags); 8189 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8190 Trap.hasErrorOccurred()) { 8191 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8192 << Context.getTagDeclType(ClassDecl); 8193 Constructor->setInvalidDecl(); 8194 return; 8195 } 8196 8197 SourceLocation Loc = Constructor->getLocation(); 8198 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8199 8200 Constructor->setUsed(); 8201 MarkVTableUsed(CurrentLocation, ClassDecl); 8202 8203 if (ASTMutationListener *L = getASTMutationListener()) { 8204 L->CompletedImplicitDefinition(Constructor); 8205 } 8206} 8207 8208 8209Sema::ImplicitExceptionSpecification 8210Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8211 CXXRecordDecl *ClassDecl = MD->getParent(); 8212 8213 // C++ [except.spec]p14: 8214 // An implicitly declared special member function (Clause 12) shall have 8215 // an exception-specification. 8216 ImplicitExceptionSpecification ExceptSpec(*this); 8217 if (ClassDecl->isInvalidDecl()) 8218 return ExceptSpec; 8219 8220 // Direct base-class destructors. 8221 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8222 BEnd = ClassDecl->bases_end(); 8223 B != BEnd; ++B) { 8224 if (B->isVirtual()) // Handled below. 8225 continue; 8226 8227 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8228 ExceptSpec.CalledDecl(B->getLocStart(), 8229 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8230 } 8231 8232 // Virtual base-class destructors. 8233 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8234 BEnd = ClassDecl->vbases_end(); 8235 B != BEnd; ++B) { 8236 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8237 ExceptSpec.CalledDecl(B->getLocStart(), 8238 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8239 } 8240 8241 // Field destructors. 8242 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8243 FEnd = ClassDecl->field_end(); 8244 F != FEnd; ++F) { 8245 if (const RecordType *RecordTy 8246 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8247 ExceptSpec.CalledDecl(F->getLocation(), 8248 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8249 } 8250 8251 return ExceptSpec; 8252} 8253 8254CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8255 // C++ [class.dtor]p2: 8256 // If a class has no user-declared destructor, a destructor is 8257 // declared implicitly. An implicitly-declared destructor is an 8258 // inline public member of its class. 8259 assert(ClassDecl->needsImplicitDestructor()); 8260 8261 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8262 if (DSM.isAlreadyBeingDeclared()) 8263 return 0; 8264 8265 // Create the actual destructor declaration. 8266 CanQualType ClassType 8267 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8268 SourceLocation ClassLoc = ClassDecl->getLocation(); 8269 DeclarationName Name 8270 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8271 DeclarationNameInfo NameInfo(Name, ClassLoc); 8272 CXXDestructorDecl *Destructor 8273 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8274 QualType(), 0, /*isInline=*/true, 8275 /*isImplicitlyDeclared=*/true); 8276 Destructor->setAccess(AS_public); 8277 Destructor->setDefaulted(); 8278 Destructor->setImplicit(); 8279 8280 // Build an exception specification pointing back at this destructor. 8281 FunctionProtoType::ExtProtoInfo EPI; 8282 EPI.ExceptionSpecType = EST_Unevaluated; 8283 EPI.ExceptionSpecDecl = Destructor; 8284 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8285 8286 AddOverriddenMethods(ClassDecl, Destructor); 8287 8288 // We don't need to use SpecialMemberIsTrivial here; triviality for 8289 // destructors is easy to compute. 8290 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8291 8292 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8293 SetDeclDeleted(Destructor, ClassLoc); 8294 8295 // Note that we have declared this destructor. 8296 ++ASTContext::NumImplicitDestructorsDeclared; 8297 8298 // Introduce this destructor into its scope. 8299 if (Scope *S = getScopeForContext(ClassDecl)) 8300 PushOnScopeChains(Destructor, S, false); 8301 ClassDecl->addDecl(Destructor); 8302 8303 return Destructor; 8304} 8305 8306void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8307 CXXDestructorDecl *Destructor) { 8308 assert((Destructor->isDefaulted() && 8309 !Destructor->doesThisDeclarationHaveABody() && 8310 !Destructor->isDeleted()) && 8311 "DefineImplicitDestructor - call it for implicit default dtor"); 8312 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8313 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8314 8315 if (Destructor->isInvalidDecl()) 8316 return; 8317 8318 SynthesizedFunctionScope Scope(*this, Destructor); 8319 8320 DiagnosticErrorTrap Trap(Diags); 8321 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8322 Destructor->getParent()); 8323 8324 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8325 Diag(CurrentLocation, diag::note_member_synthesized_at) 8326 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8327 8328 Destructor->setInvalidDecl(); 8329 return; 8330 } 8331 8332 SourceLocation Loc = Destructor->getLocation(); 8333 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8334 Destructor->setImplicitlyDefined(true); 8335 Destructor->setUsed(); 8336 MarkVTableUsed(CurrentLocation, ClassDecl); 8337 8338 if (ASTMutationListener *L = getASTMutationListener()) { 8339 L->CompletedImplicitDefinition(Destructor); 8340 } 8341} 8342 8343/// \brief Perform any semantic analysis which needs to be delayed until all 8344/// pending class member declarations have been parsed. 8345void Sema::ActOnFinishCXXMemberDecls() { 8346 // If the context is an invalid C++ class, just suppress these checks. 8347 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8348 if (Record->isInvalidDecl()) { 8349 DelayedDestructorExceptionSpecChecks.clear(); 8350 return; 8351 } 8352 } 8353 8354 // Perform any deferred checking of exception specifications for virtual 8355 // destructors. 8356 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8357 i != e; ++i) { 8358 const CXXDestructorDecl *Dtor = 8359 DelayedDestructorExceptionSpecChecks[i].first; 8360 assert(!Dtor->getParent()->isDependentType() && 8361 "Should not ever add destructors of templates into the list."); 8362 CheckOverridingFunctionExceptionSpec(Dtor, 8363 DelayedDestructorExceptionSpecChecks[i].second); 8364 } 8365 DelayedDestructorExceptionSpecChecks.clear(); 8366} 8367 8368void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8369 CXXDestructorDecl *Destructor) { 8370 assert(getLangOpts().CPlusPlus11 && 8371 "adjusting dtor exception specs was introduced in c++11"); 8372 8373 // C++11 [class.dtor]p3: 8374 // A declaration of a destructor that does not have an exception- 8375 // specification is implicitly considered to have the same exception- 8376 // specification as an implicit declaration. 8377 const FunctionProtoType *DtorType = Destructor->getType()-> 8378 getAs<FunctionProtoType>(); 8379 if (DtorType->hasExceptionSpec()) 8380 return; 8381 8382 // Replace the destructor's type, building off the existing one. Fortunately, 8383 // the only thing of interest in the destructor type is its extended info. 8384 // The return and arguments are fixed. 8385 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8386 EPI.ExceptionSpecType = EST_Unevaluated; 8387 EPI.ExceptionSpecDecl = Destructor; 8388 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8389 8390 // FIXME: If the destructor has a body that could throw, and the newly created 8391 // spec doesn't allow exceptions, we should emit a warning, because this 8392 // change in behavior can break conforming C++03 programs at runtime. 8393 // However, we don't have a body or an exception specification yet, so it 8394 // needs to be done somewhere else. 8395} 8396 8397/// When generating a defaulted copy or move assignment operator, if a field 8398/// should be copied with __builtin_memcpy rather than via explicit assignments, 8399/// do so. This optimization only applies for arrays of scalars, and for arrays 8400/// of class type where the selected copy/move-assignment operator is trivial. 8401static StmtResult 8402buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8403 Expr *To, Expr *From) { 8404 // Compute the size of the memory buffer to be copied. 8405 QualType SizeType = S.Context.getSizeType(); 8406 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8407 S.Context.getTypeSizeInChars(T).getQuantity()); 8408 8409 // Take the address of the field references for "from" and "to". We 8410 // directly construct UnaryOperators here because semantic analysis 8411 // does not permit us to take the address of an xvalue. 8412 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8413 S.Context.getPointerType(From->getType()), 8414 VK_RValue, OK_Ordinary, Loc); 8415 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8416 S.Context.getPointerType(To->getType()), 8417 VK_RValue, OK_Ordinary, Loc); 8418 8419 const Type *E = T->getBaseElementTypeUnsafe(); 8420 bool NeedsCollectableMemCpy = 8421 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8422 8423 // Create a reference to the __builtin_objc_memmove_collectable function 8424 StringRef MemCpyName = NeedsCollectableMemCpy ? 8425 "__builtin_objc_memmove_collectable" : 8426 "__builtin_memcpy"; 8427 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8428 Sema::LookupOrdinaryName); 8429 S.LookupName(R, S.TUScope, true); 8430 8431 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8432 if (!MemCpy) 8433 // Something went horribly wrong earlier, and we will have complained 8434 // about it. 8435 return StmtError(); 8436 8437 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8438 VK_RValue, Loc, 0); 8439 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8440 8441 Expr *CallArgs[] = { 8442 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8443 }; 8444 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8445 Loc, CallArgs, Loc); 8446 8447 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8448 return S.Owned(Call.takeAs<Stmt>()); 8449} 8450 8451/// \brief Builds a statement that copies/moves the given entity from \p From to 8452/// \c To. 8453/// 8454/// This routine is used to copy/move the members of a class with an 8455/// implicitly-declared copy/move assignment operator. When the entities being 8456/// copied are arrays, this routine builds for loops to copy them. 8457/// 8458/// \param S The Sema object used for type-checking. 8459/// 8460/// \param Loc The location where the implicit copy/move is being generated. 8461/// 8462/// \param T The type of the expressions being copied/moved. Both expressions 8463/// must have this type. 8464/// 8465/// \param To The expression we are copying/moving to. 8466/// 8467/// \param From The expression we are copying/moving from. 8468/// 8469/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8470/// Otherwise, it's a non-static member subobject. 8471/// 8472/// \param Copying Whether we're copying or moving. 8473/// 8474/// \param Depth Internal parameter recording the depth of the recursion. 8475/// 8476/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8477/// if a memcpy should be used instead. 8478static StmtResult 8479buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8480 Expr *To, Expr *From, 8481 bool CopyingBaseSubobject, bool Copying, 8482 unsigned Depth = 0) { 8483 // C++11 [class.copy]p28: 8484 // Each subobject is assigned in the manner appropriate to its type: 8485 // 8486 // - if the subobject is of class type, as if by a call to operator= with 8487 // the subobject as the object expression and the corresponding 8488 // subobject of x as a single function argument (as if by explicit 8489 // qualification; that is, ignoring any possible virtual overriding 8490 // functions in more derived classes); 8491 // 8492 // C++03 [class.copy]p13: 8493 // - if the subobject is of class type, the copy assignment operator for 8494 // the class is used (as if by explicit qualification; that is, 8495 // ignoring any possible virtual overriding functions in more derived 8496 // classes); 8497 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8498 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8499 8500 // Look for operator=. 8501 DeclarationName Name 8502 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8503 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8504 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8505 8506 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8507 // operator. 8508 if (!S.getLangOpts().CPlusPlus11) { 8509 LookupResult::Filter F = OpLookup.makeFilter(); 8510 while (F.hasNext()) { 8511 NamedDecl *D = F.next(); 8512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8513 if (Method->isCopyAssignmentOperator() || 8514 (!Copying && Method->isMoveAssignmentOperator())) 8515 continue; 8516 8517 F.erase(); 8518 } 8519 F.done(); 8520 } 8521 8522 // Suppress the protected check (C++ [class.protected]) for each of the 8523 // assignment operators we found. This strange dance is required when 8524 // we're assigning via a base classes's copy-assignment operator. To 8525 // ensure that we're getting the right base class subobject (without 8526 // ambiguities), we need to cast "this" to that subobject type; to 8527 // ensure that we don't go through the virtual call mechanism, we need 8528 // to qualify the operator= name with the base class (see below). However, 8529 // this means that if the base class has a protected copy assignment 8530 // operator, the protected member access check will fail. So, we 8531 // rewrite "protected" access to "public" access in this case, since we 8532 // know by construction that we're calling from a derived class. 8533 if (CopyingBaseSubobject) { 8534 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8535 L != LEnd; ++L) { 8536 if (L.getAccess() == AS_protected) 8537 L.setAccess(AS_public); 8538 } 8539 } 8540 8541 // Create the nested-name-specifier that will be used to qualify the 8542 // reference to operator=; this is required to suppress the virtual 8543 // call mechanism. 8544 CXXScopeSpec SS; 8545 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8546 SS.MakeTrivial(S.Context, 8547 NestedNameSpecifier::Create(S.Context, 0, false, 8548 CanonicalT), 8549 Loc); 8550 8551 // Create the reference to operator=. 8552 ExprResult OpEqualRef 8553 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8554 /*TemplateKWLoc=*/SourceLocation(), 8555 /*FirstQualifierInScope=*/0, 8556 OpLookup, 8557 /*TemplateArgs=*/0, 8558 /*SuppressQualifierCheck=*/true); 8559 if (OpEqualRef.isInvalid()) 8560 return StmtError(); 8561 8562 // Build the call to the assignment operator. 8563 8564 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8565 OpEqualRef.takeAs<Expr>(), 8566 Loc, From, Loc); 8567 if (Call.isInvalid()) 8568 return StmtError(); 8569 8570 // If we built a call to a trivial 'operator=' while copying an array, 8571 // bail out. We'll replace the whole shebang with a memcpy. 8572 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8573 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8574 return StmtResult((Stmt*)0); 8575 8576 // Convert to an expression-statement, and clean up any produced 8577 // temporaries. 8578 return S.ActOnExprStmt(Call); 8579 } 8580 8581 // - if the subobject is of scalar type, the built-in assignment 8582 // operator is used. 8583 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8584 if (!ArrayTy) { 8585 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8586 if (Assignment.isInvalid()) 8587 return StmtError(); 8588 return S.ActOnExprStmt(Assignment); 8589 } 8590 8591 // - if the subobject is an array, each element is assigned, in the 8592 // manner appropriate to the element type; 8593 8594 // Construct a loop over the array bounds, e.g., 8595 // 8596 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8597 // 8598 // that will copy each of the array elements. 8599 QualType SizeType = S.Context.getSizeType(); 8600 8601 // Create the iteration variable. 8602 IdentifierInfo *IterationVarName = 0; 8603 { 8604 SmallString<8> Str; 8605 llvm::raw_svector_ostream OS(Str); 8606 OS << "__i" << Depth; 8607 IterationVarName = &S.Context.Idents.get(OS.str()); 8608 } 8609 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8610 IterationVarName, SizeType, 8611 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8612 SC_None); 8613 8614 // Initialize the iteration variable to zero. 8615 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8616 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8617 8618 // Create a reference to the iteration variable; we'll use this several 8619 // times throughout. 8620 Expr *IterationVarRef 8621 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8622 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8623 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8624 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8625 8626 // Create the DeclStmt that holds the iteration variable. 8627 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8628 8629 // Subscript the "from" and "to" expressions with the iteration variable. 8630 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8631 IterationVarRefRVal, 8632 Loc)); 8633 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8634 IterationVarRefRVal, 8635 Loc)); 8636 if (!Copying) // Cast to rvalue 8637 From = CastForMoving(S, From); 8638 8639 // Build the copy/move for an individual element of the array. 8640 StmtResult Copy = 8641 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8642 To, From, CopyingBaseSubobject, 8643 Copying, Depth + 1); 8644 // Bail out if copying fails or if we determined that we should use memcpy. 8645 if (Copy.isInvalid() || !Copy.get()) 8646 return Copy; 8647 8648 // Create the comparison against the array bound. 8649 llvm::APInt Upper 8650 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8651 Expr *Comparison 8652 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8653 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8654 BO_NE, S.Context.BoolTy, 8655 VK_RValue, OK_Ordinary, Loc, false); 8656 8657 // Create the pre-increment of the iteration variable. 8658 Expr *Increment 8659 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8660 VK_LValue, OK_Ordinary, Loc); 8661 8662 // Construct the loop that copies all elements of this array. 8663 return S.ActOnForStmt(Loc, Loc, InitStmt, 8664 S.MakeFullExpr(Comparison), 8665 0, S.MakeFullDiscardedValueExpr(Increment), 8666 Loc, Copy.take()); 8667} 8668 8669static StmtResult 8670buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8671 Expr *To, Expr *From, 8672 bool CopyingBaseSubobject, bool Copying) { 8673 // Maybe we should use a memcpy? 8674 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8675 T.isTriviallyCopyableType(S.Context)) 8676 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8677 8678 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8679 CopyingBaseSubobject, 8680 Copying, 0)); 8681 8682 // If we ended up picking a trivial assignment operator for an array of a 8683 // non-trivially-copyable class type, just emit a memcpy. 8684 if (!Result.isInvalid() && !Result.get()) 8685 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8686 8687 return Result; 8688} 8689 8690Sema::ImplicitExceptionSpecification 8691Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8692 CXXRecordDecl *ClassDecl = MD->getParent(); 8693 8694 ImplicitExceptionSpecification ExceptSpec(*this); 8695 if (ClassDecl->isInvalidDecl()) 8696 return ExceptSpec; 8697 8698 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8699 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8700 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8701 8702 // C++ [except.spec]p14: 8703 // An implicitly declared special member function (Clause 12) shall have an 8704 // exception-specification. [...] 8705 8706 // It is unspecified whether or not an implicit copy assignment operator 8707 // attempts to deduplicate calls to assignment operators of virtual bases are 8708 // made. As such, this exception specification is effectively unspecified. 8709 // Based on a similar decision made for constness in C++0x, we're erring on 8710 // the side of assuming such calls to be made regardless of whether they 8711 // actually happen. 8712 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8713 BaseEnd = ClassDecl->bases_end(); 8714 Base != BaseEnd; ++Base) { 8715 if (Base->isVirtual()) 8716 continue; 8717 8718 CXXRecordDecl *BaseClassDecl 8719 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8720 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8721 ArgQuals, false, 0)) 8722 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8723 } 8724 8725 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8726 BaseEnd = ClassDecl->vbases_end(); 8727 Base != BaseEnd; ++Base) { 8728 CXXRecordDecl *BaseClassDecl 8729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8730 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8731 ArgQuals, false, 0)) 8732 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8733 } 8734 8735 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8736 FieldEnd = ClassDecl->field_end(); 8737 Field != FieldEnd; 8738 ++Field) { 8739 QualType FieldType = Context.getBaseElementType(Field->getType()); 8740 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8741 if (CXXMethodDecl *CopyAssign = 8742 LookupCopyingAssignment(FieldClassDecl, 8743 ArgQuals | FieldType.getCVRQualifiers(), 8744 false, 0)) 8745 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8746 } 8747 } 8748 8749 return ExceptSpec; 8750} 8751 8752CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8753 // Note: The following rules are largely analoguous to the copy 8754 // constructor rules. Note that virtual bases are not taken into account 8755 // for determining the argument type of the operator. Note also that 8756 // operators taking an object instead of a reference are allowed. 8757 assert(ClassDecl->needsImplicitCopyAssignment()); 8758 8759 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8760 if (DSM.isAlreadyBeingDeclared()) 8761 return 0; 8762 8763 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8764 QualType RetType = Context.getLValueReferenceType(ArgType); 8765 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 8766 if (Const) 8767 ArgType = ArgType.withConst(); 8768 ArgType = Context.getLValueReferenceType(ArgType); 8769 8770 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8771 CXXCopyAssignment, 8772 Const); 8773 8774 // An implicitly-declared copy assignment operator is an inline public 8775 // member of its class. 8776 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8777 SourceLocation ClassLoc = ClassDecl->getLocation(); 8778 DeclarationNameInfo NameInfo(Name, ClassLoc); 8779 CXXMethodDecl *CopyAssignment = 8780 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8781 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 8782 /*isInline=*/ true, Constexpr, SourceLocation()); 8783 CopyAssignment->setAccess(AS_public); 8784 CopyAssignment->setDefaulted(); 8785 CopyAssignment->setImplicit(); 8786 8787 // Build an exception specification pointing back at this member. 8788 FunctionProtoType::ExtProtoInfo EPI; 8789 EPI.ExceptionSpecType = EST_Unevaluated; 8790 EPI.ExceptionSpecDecl = CopyAssignment; 8791 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8792 8793 // Add the parameter to the operator. 8794 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8795 ClassLoc, ClassLoc, /*Id=*/0, 8796 ArgType, /*TInfo=*/0, 8797 SC_None, 0); 8798 CopyAssignment->setParams(FromParam); 8799 8800 AddOverriddenMethods(ClassDecl, CopyAssignment); 8801 8802 CopyAssignment->setTrivial( 8803 ClassDecl->needsOverloadResolutionForCopyAssignment() 8804 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8805 : ClassDecl->hasTrivialCopyAssignment()); 8806 8807 // C++11 [class.copy]p19: 8808 // .... If the class definition does not explicitly declare a copy 8809 // assignment operator, there is no user-declared move constructor, and 8810 // there is no user-declared move assignment operator, a copy assignment 8811 // operator is implicitly declared as defaulted. 8812 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8813 SetDeclDeleted(CopyAssignment, ClassLoc); 8814 8815 // Note that we have added this copy-assignment operator. 8816 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8817 8818 if (Scope *S = getScopeForContext(ClassDecl)) 8819 PushOnScopeChains(CopyAssignment, S, false); 8820 ClassDecl->addDecl(CopyAssignment); 8821 8822 return CopyAssignment; 8823} 8824 8825void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8826 CXXMethodDecl *CopyAssignOperator) { 8827 assert((CopyAssignOperator->isDefaulted() && 8828 CopyAssignOperator->isOverloadedOperator() && 8829 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8830 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8831 !CopyAssignOperator->isDeleted()) && 8832 "DefineImplicitCopyAssignment called for wrong function"); 8833 8834 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8835 8836 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8837 CopyAssignOperator->setInvalidDecl(); 8838 return; 8839 } 8840 8841 CopyAssignOperator->setUsed(); 8842 8843 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8844 DiagnosticErrorTrap Trap(Diags); 8845 8846 // C++0x [class.copy]p30: 8847 // The implicitly-defined or explicitly-defaulted copy assignment operator 8848 // for a non-union class X performs memberwise copy assignment of its 8849 // subobjects. The direct base classes of X are assigned first, in the 8850 // order of their declaration in the base-specifier-list, and then the 8851 // immediate non-static data members of X are assigned, in the order in 8852 // which they were declared in the class definition. 8853 8854 // The statements that form the synthesized function body. 8855 SmallVector<Stmt*, 8> Statements; 8856 8857 // The parameter for the "other" object, which we are copying from. 8858 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8859 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8860 QualType OtherRefType = Other->getType(); 8861 if (const LValueReferenceType *OtherRef 8862 = OtherRefType->getAs<LValueReferenceType>()) { 8863 OtherRefType = OtherRef->getPointeeType(); 8864 OtherQuals = OtherRefType.getQualifiers(); 8865 } 8866 8867 // Our location for everything implicitly-generated. 8868 SourceLocation Loc = CopyAssignOperator->getLocation(); 8869 8870 // Construct a reference to the "other" object. We'll be using this 8871 // throughout the generated ASTs. 8872 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8873 assert(OtherRef && "Reference to parameter cannot fail!"); 8874 8875 // Construct the "this" pointer. We'll be using this throughout the generated 8876 // ASTs. 8877 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8878 assert(This && "Reference to this cannot fail!"); 8879 8880 // Assign base classes. 8881 bool Invalid = false; 8882 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8883 E = ClassDecl->bases_end(); Base != E; ++Base) { 8884 // Form the assignment: 8885 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8886 QualType BaseType = Base->getType().getUnqualifiedType(); 8887 if (!BaseType->isRecordType()) { 8888 Invalid = true; 8889 continue; 8890 } 8891 8892 CXXCastPath BasePath; 8893 BasePath.push_back(Base); 8894 8895 // Construct the "from" expression, which is an implicit cast to the 8896 // appropriately-qualified base type. 8897 Expr *From = OtherRef; 8898 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8899 CK_UncheckedDerivedToBase, 8900 VK_LValue, &BasePath).take(); 8901 8902 // Dereference "this". 8903 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8904 8905 // Implicitly cast "this" to the appropriately-qualified base type. 8906 To = ImpCastExprToType(To.take(), 8907 Context.getCVRQualifiedType(BaseType, 8908 CopyAssignOperator->getTypeQualifiers()), 8909 CK_UncheckedDerivedToBase, 8910 VK_LValue, &BasePath); 8911 8912 // Build the copy. 8913 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8914 To.get(), From, 8915 /*CopyingBaseSubobject=*/true, 8916 /*Copying=*/true); 8917 if (Copy.isInvalid()) { 8918 Diag(CurrentLocation, diag::note_member_synthesized_at) 8919 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8920 CopyAssignOperator->setInvalidDecl(); 8921 return; 8922 } 8923 8924 // Success! Record the copy. 8925 Statements.push_back(Copy.takeAs<Expr>()); 8926 } 8927 8928 // Assign non-static members. 8929 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8930 FieldEnd = ClassDecl->field_end(); 8931 Field != FieldEnd; ++Field) { 8932 if (Field->isUnnamedBitfield()) 8933 continue; 8934 8935 if (Field->isInvalidDecl()) { 8936 Invalid = true; 8937 continue; 8938 } 8939 8940 // Check for members of reference type; we can't copy those. 8941 if (Field->getType()->isReferenceType()) { 8942 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8943 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8944 Diag(Field->getLocation(), diag::note_declared_at); 8945 Diag(CurrentLocation, diag::note_member_synthesized_at) 8946 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8947 Invalid = true; 8948 continue; 8949 } 8950 8951 // Check for members of const-qualified, non-class type. 8952 QualType BaseType = Context.getBaseElementType(Field->getType()); 8953 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8954 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8955 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8956 Diag(Field->getLocation(), diag::note_declared_at); 8957 Diag(CurrentLocation, diag::note_member_synthesized_at) 8958 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8959 Invalid = true; 8960 continue; 8961 } 8962 8963 // Suppress assigning zero-width bitfields. 8964 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8965 continue; 8966 8967 QualType FieldType = Field->getType().getNonReferenceType(); 8968 if (FieldType->isIncompleteArrayType()) { 8969 assert(ClassDecl->hasFlexibleArrayMember() && 8970 "Incomplete array type is not valid"); 8971 continue; 8972 } 8973 8974 // Build references to the field in the object we're copying from and to. 8975 CXXScopeSpec SS; // Intentionally empty 8976 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8977 LookupMemberName); 8978 MemberLookup.addDecl(*Field); 8979 MemberLookup.resolveKind(); 8980 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8981 Loc, /*IsArrow=*/false, 8982 SS, SourceLocation(), 0, 8983 MemberLookup, 0); 8984 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8985 Loc, /*IsArrow=*/true, 8986 SS, SourceLocation(), 0, 8987 MemberLookup, 0); 8988 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8989 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8990 8991 // Build the copy of this field. 8992 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8993 To.get(), From.get(), 8994 /*CopyingBaseSubobject=*/false, 8995 /*Copying=*/true); 8996 if (Copy.isInvalid()) { 8997 Diag(CurrentLocation, diag::note_member_synthesized_at) 8998 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8999 CopyAssignOperator->setInvalidDecl(); 9000 return; 9001 } 9002 9003 // Success! Record the copy. 9004 Statements.push_back(Copy.takeAs<Stmt>()); 9005 } 9006 9007 if (!Invalid) { 9008 // Add a "return *this;" 9009 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9010 9011 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9012 if (Return.isInvalid()) 9013 Invalid = true; 9014 else { 9015 Statements.push_back(Return.takeAs<Stmt>()); 9016 9017 if (Trap.hasErrorOccurred()) { 9018 Diag(CurrentLocation, diag::note_member_synthesized_at) 9019 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9020 Invalid = true; 9021 } 9022 } 9023 } 9024 9025 if (Invalid) { 9026 CopyAssignOperator->setInvalidDecl(); 9027 return; 9028 } 9029 9030 StmtResult Body; 9031 { 9032 CompoundScopeRAII CompoundScope(*this); 9033 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9034 /*isStmtExpr=*/false); 9035 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9036 } 9037 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9038 9039 if (ASTMutationListener *L = getASTMutationListener()) { 9040 L->CompletedImplicitDefinition(CopyAssignOperator); 9041 } 9042} 9043 9044Sema::ImplicitExceptionSpecification 9045Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9046 CXXRecordDecl *ClassDecl = MD->getParent(); 9047 9048 ImplicitExceptionSpecification ExceptSpec(*this); 9049 if (ClassDecl->isInvalidDecl()) 9050 return ExceptSpec; 9051 9052 // C++0x [except.spec]p14: 9053 // An implicitly declared special member function (Clause 12) shall have an 9054 // exception-specification. [...] 9055 9056 // It is unspecified whether or not an implicit move assignment operator 9057 // attempts to deduplicate calls to assignment operators of virtual bases are 9058 // made. As such, this exception specification is effectively unspecified. 9059 // Based on a similar decision made for constness in C++0x, we're erring on 9060 // the side of assuming such calls to be made regardless of whether they 9061 // actually happen. 9062 // Note that a move constructor is not implicitly declared when there are 9063 // virtual bases, but it can still be user-declared and explicitly defaulted. 9064 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9065 BaseEnd = ClassDecl->bases_end(); 9066 Base != BaseEnd; ++Base) { 9067 if (Base->isVirtual()) 9068 continue; 9069 9070 CXXRecordDecl *BaseClassDecl 9071 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9072 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9073 0, false, 0)) 9074 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9075 } 9076 9077 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9078 BaseEnd = ClassDecl->vbases_end(); 9079 Base != BaseEnd; ++Base) { 9080 CXXRecordDecl *BaseClassDecl 9081 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9082 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9083 0, false, 0)) 9084 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9085 } 9086 9087 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9088 FieldEnd = ClassDecl->field_end(); 9089 Field != FieldEnd; 9090 ++Field) { 9091 QualType FieldType = Context.getBaseElementType(Field->getType()); 9092 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9093 if (CXXMethodDecl *MoveAssign = 9094 LookupMovingAssignment(FieldClassDecl, 9095 FieldType.getCVRQualifiers(), 9096 false, 0)) 9097 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9098 } 9099 } 9100 9101 return ExceptSpec; 9102} 9103 9104/// Determine whether the class type has any direct or indirect virtual base 9105/// classes which have a non-trivial move assignment operator. 9106static bool 9107hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9108 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9109 BaseEnd = ClassDecl->vbases_end(); 9110 Base != BaseEnd; ++Base) { 9111 CXXRecordDecl *BaseClass = 9112 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9113 9114 // Try to declare the move assignment. If it would be deleted, then the 9115 // class does not have a non-trivial move assignment. 9116 if (BaseClass->needsImplicitMoveAssignment()) 9117 S.DeclareImplicitMoveAssignment(BaseClass); 9118 9119 if (BaseClass->hasNonTrivialMoveAssignment()) 9120 return true; 9121 } 9122 9123 return false; 9124} 9125 9126/// Determine whether the given type either has a move constructor or is 9127/// trivially copyable. 9128static bool 9129hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9130 Type = S.Context.getBaseElementType(Type); 9131 9132 // FIXME: Technically, non-trivially-copyable non-class types, such as 9133 // reference types, are supposed to return false here, but that appears 9134 // to be a standard defect. 9135 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9136 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9137 return true; 9138 9139 if (Type.isTriviallyCopyableType(S.Context)) 9140 return true; 9141 9142 if (IsConstructor) { 9143 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9144 // give the right answer. 9145 if (ClassDecl->needsImplicitMoveConstructor()) 9146 S.DeclareImplicitMoveConstructor(ClassDecl); 9147 return ClassDecl->hasMoveConstructor(); 9148 } 9149 9150 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9151 // give the right answer. 9152 if (ClassDecl->needsImplicitMoveAssignment()) 9153 S.DeclareImplicitMoveAssignment(ClassDecl); 9154 return ClassDecl->hasMoveAssignment(); 9155} 9156 9157/// Determine whether all non-static data members and direct or virtual bases 9158/// of class \p ClassDecl have either a move operation, or are trivially 9159/// copyable. 9160static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9161 bool IsConstructor) { 9162 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9163 BaseEnd = ClassDecl->bases_end(); 9164 Base != BaseEnd; ++Base) { 9165 if (Base->isVirtual()) 9166 continue; 9167 9168 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9169 return false; 9170 } 9171 9172 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9173 BaseEnd = ClassDecl->vbases_end(); 9174 Base != BaseEnd; ++Base) { 9175 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9176 return false; 9177 } 9178 9179 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9180 FieldEnd = ClassDecl->field_end(); 9181 Field != FieldEnd; ++Field) { 9182 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9183 return false; 9184 } 9185 9186 return true; 9187} 9188 9189CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9190 // C++11 [class.copy]p20: 9191 // If the definition of a class X does not explicitly declare a move 9192 // assignment operator, one will be implicitly declared as defaulted 9193 // if and only if: 9194 // 9195 // - [first 4 bullets] 9196 assert(ClassDecl->needsImplicitMoveAssignment()); 9197 9198 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9199 if (DSM.isAlreadyBeingDeclared()) 9200 return 0; 9201 9202 // [Checked after we build the declaration] 9203 // - the move assignment operator would not be implicitly defined as 9204 // deleted, 9205 9206 // [DR1402]: 9207 // - X has no direct or indirect virtual base class with a non-trivial 9208 // move assignment operator, and 9209 // - each of X's non-static data members and direct or virtual base classes 9210 // has a type that either has a move assignment operator or is trivially 9211 // copyable. 9212 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9213 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9214 ClassDecl->setFailedImplicitMoveAssignment(); 9215 return 0; 9216 } 9217 9218 // Note: The following rules are largely analoguous to the move 9219 // constructor rules. 9220 9221 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9222 QualType RetType = Context.getLValueReferenceType(ArgType); 9223 ArgType = Context.getRValueReferenceType(ArgType); 9224 9225 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9226 CXXMoveAssignment, 9227 false); 9228 9229 // An implicitly-declared move assignment operator is an inline public 9230 // member of its class. 9231 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9232 SourceLocation ClassLoc = ClassDecl->getLocation(); 9233 DeclarationNameInfo NameInfo(Name, ClassLoc); 9234 CXXMethodDecl *MoveAssignment = 9235 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9236 /*TInfo=*/0, /*StorageClass=*/SC_None, 9237 /*isInline=*/true, Constexpr, SourceLocation()); 9238 MoveAssignment->setAccess(AS_public); 9239 MoveAssignment->setDefaulted(); 9240 MoveAssignment->setImplicit(); 9241 9242 // Build an exception specification pointing back at this member. 9243 FunctionProtoType::ExtProtoInfo EPI; 9244 EPI.ExceptionSpecType = EST_Unevaluated; 9245 EPI.ExceptionSpecDecl = MoveAssignment; 9246 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9247 9248 // Add the parameter to the operator. 9249 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9250 ClassLoc, ClassLoc, /*Id=*/0, 9251 ArgType, /*TInfo=*/0, 9252 SC_None, 0); 9253 MoveAssignment->setParams(FromParam); 9254 9255 AddOverriddenMethods(ClassDecl, MoveAssignment); 9256 9257 MoveAssignment->setTrivial( 9258 ClassDecl->needsOverloadResolutionForMoveAssignment() 9259 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9260 : ClassDecl->hasTrivialMoveAssignment()); 9261 9262 // C++0x [class.copy]p9: 9263 // If the definition of a class X does not explicitly declare a move 9264 // assignment operator, one will be implicitly declared as defaulted if and 9265 // only if: 9266 // [...] 9267 // - the move assignment operator would not be implicitly defined as 9268 // deleted. 9269 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9270 // Cache this result so that we don't try to generate this over and over 9271 // on every lookup, leaking memory and wasting time. 9272 ClassDecl->setFailedImplicitMoveAssignment(); 9273 return 0; 9274 } 9275 9276 // Note that we have added this copy-assignment operator. 9277 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9278 9279 if (Scope *S = getScopeForContext(ClassDecl)) 9280 PushOnScopeChains(MoveAssignment, S, false); 9281 ClassDecl->addDecl(MoveAssignment); 9282 9283 return MoveAssignment; 9284} 9285 9286void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9287 CXXMethodDecl *MoveAssignOperator) { 9288 assert((MoveAssignOperator->isDefaulted() && 9289 MoveAssignOperator->isOverloadedOperator() && 9290 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9291 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9292 !MoveAssignOperator->isDeleted()) && 9293 "DefineImplicitMoveAssignment called for wrong function"); 9294 9295 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9296 9297 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9298 MoveAssignOperator->setInvalidDecl(); 9299 return; 9300 } 9301 9302 MoveAssignOperator->setUsed(); 9303 9304 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9305 DiagnosticErrorTrap Trap(Diags); 9306 9307 // C++0x [class.copy]p28: 9308 // The implicitly-defined or move assignment operator for a non-union class 9309 // X performs memberwise move assignment of its subobjects. The direct base 9310 // classes of X are assigned first, in the order of their declaration in the 9311 // base-specifier-list, and then the immediate non-static data members of X 9312 // are assigned, in the order in which they were declared in the class 9313 // definition. 9314 9315 // The statements that form the synthesized function body. 9316 SmallVector<Stmt*, 8> Statements; 9317 9318 // The parameter for the "other" object, which we are move from. 9319 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9320 QualType OtherRefType = Other->getType()-> 9321 getAs<RValueReferenceType>()->getPointeeType(); 9322 assert(!OtherRefType.getQualifiers() && 9323 "Bad argument type of defaulted move assignment"); 9324 9325 // Our location for everything implicitly-generated. 9326 SourceLocation Loc = MoveAssignOperator->getLocation(); 9327 9328 // Construct a reference to the "other" object. We'll be using this 9329 // throughout the generated ASTs. 9330 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9331 assert(OtherRef && "Reference to parameter cannot fail!"); 9332 // Cast to rvalue. 9333 OtherRef = CastForMoving(*this, OtherRef); 9334 9335 // Construct the "this" pointer. We'll be using this throughout the generated 9336 // ASTs. 9337 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9338 assert(This && "Reference to this cannot fail!"); 9339 9340 // Assign base classes. 9341 bool Invalid = false; 9342 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9343 E = ClassDecl->bases_end(); Base != E; ++Base) { 9344 // Form the assignment: 9345 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9346 QualType BaseType = Base->getType().getUnqualifiedType(); 9347 if (!BaseType->isRecordType()) { 9348 Invalid = true; 9349 continue; 9350 } 9351 9352 CXXCastPath BasePath; 9353 BasePath.push_back(Base); 9354 9355 // Construct the "from" expression, which is an implicit cast to the 9356 // appropriately-qualified base type. 9357 Expr *From = OtherRef; 9358 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9359 VK_XValue, &BasePath).take(); 9360 9361 // Dereference "this". 9362 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9363 9364 // Implicitly cast "this" to the appropriately-qualified base type. 9365 To = ImpCastExprToType(To.take(), 9366 Context.getCVRQualifiedType(BaseType, 9367 MoveAssignOperator->getTypeQualifiers()), 9368 CK_UncheckedDerivedToBase, 9369 VK_LValue, &BasePath); 9370 9371 // Build the move. 9372 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9373 To.get(), From, 9374 /*CopyingBaseSubobject=*/true, 9375 /*Copying=*/false); 9376 if (Move.isInvalid()) { 9377 Diag(CurrentLocation, diag::note_member_synthesized_at) 9378 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9379 MoveAssignOperator->setInvalidDecl(); 9380 return; 9381 } 9382 9383 // Success! Record the move. 9384 Statements.push_back(Move.takeAs<Expr>()); 9385 } 9386 9387 // Assign non-static members. 9388 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9389 FieldEnd = ClassDecl->field_end(); 9390 Field != FieldEnd; ++Field) { 9391 if (Field->isUnnamedBitfield()) 9392 continue; 9393 9394 if (Field->isInvalidDecl()) { 9395 Invalid = true; 9396 continue; 9397 } 9398 9399 // Check for members of reference type; we can't move those. 9400 if (Field->getType()->isReferenceType()) { 9401 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9402 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9403 Diag(Field->getLocation(), diag::note_declared_at); 9404 Diag(CurrentLocation, diag::note_member_synthesized_at) 9405 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9406 Invalid = true; 9407 continue; 9408 } 9409 9410 // Check for members of const-qualified, non-class type. 9411 QualType BaseType = Context.getBaseElementType(Field->getType()); 9412 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9413 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9414 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9415 Diag(Field->getLocation(), diag::note_declared_at); 9416 Diag(CurrentLocation, diag::note_member_synthesized_at) 9417 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9418 Invalid = true; 9419 continue; 9420 } 9421 9422 // Suppress assigning zero-width bitfields. 9423 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9424 continue; 9425 9426 QualType FieldType = Field->getType().getNonReferenceType(); 9427 if (FieldType->isIncompleteArrayType()) { 9428 assert(ClassDecl->hasFlexibleArrayMember() && 9429 "Incomplete array type is not valid"); 9430 continue; 9431 } 9432 9433 // Build references to the field in the object we're copying from and to. 9434 CXXScopeSpec SS; // Intentionally empty 9435 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9436 LookupMemberName); 9437 MemberLookup.addDecl(*Field); 9438 MemberLookup.resolveKind(); 9439 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9440 Loc, /*IsArrow=*/false, 9441 SS, SourceLocation(), 0, 9442 MemberLookup, 0); 9443 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9444 Loc, /*IsArrow=*/true, 9445 SS, SourceLocation(), 0, 9446 MemberLookup, 0); 9447 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9448 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9449 9450 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9451 "Member reference with rvalue base must be rvalue except for reference " 9452 "members, which aren't allowed for move assignment."); 9453 9454 // Build the move of this field. 9455 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9456 To.get(), From.get(), 9457 /*CopyingBaseSubobject=*/false, 9458 /*Copying=*/false); 9459 if (Move.isInvalid()) { 9460 Diag(CurrentLocation, diag::note_member_synthesized_at) 9461 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9462 MoveAssignOperator->setInvalidDecl(); 9463 return; 9464 } 9465 9466 // Success! Record the copy. 9467 Statements.push_back(Move.takeAs<Stmt>()); 9468 } 9469 9470 if (!Invalid) { 9471 // Add a "return *this;" 9472 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9473 9474 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9475 if (Return.isInvalid()) 9476 Invalid = true; 9477 else { 9478 Statements.push_back(Return.takeAs<Stmt>()); 9479 9480 if (Trap.hasErrorOccurred()) { 9481 Diag(CurrentLocation, diag::note_member_synthesized_at) 9482 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9483 Invalid = true; 9484 } 9485 } 9486 } 9487 9488 if (Invalid) { 9489 MoveAssignOperator->setInvalidDecl(); 9490 return; 9491 } 9492 9493 StmtResult Body; 9494 { 9495 CompoundScopeRAII CompoundScope(*this); 9496 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9497 /*isStmtExpr=*/false); 9498 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9499 } 9500 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9501 9502 if (ASTMutationListener *L = getASTMutationListener()) { 9503 L->CompletedImplicitDefinition(MoveAssignOperator); 9504 } 9505} 9506 9507Sema::ImplicitExceptionSpecification 9508Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9509 CXXRecordDecl *ClassDecl = MD->getParent(); 9510 9511 ImplicitExceptionSpecification ExceptSpec(*this); 9512 if (ClassDecl->isInvalidDecl()) 9513 return ExceptSpec; 9514 9515 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9516 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9517 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9518 9519 // C++ [except.spec]p14: 9520 // An implicitly declared special member function (Clause 12) shall have an 9521 // exception-specification. [...] 9522 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9523 BaseEnd = ClassDecl->bases_end(); 9524 Base != BaseEnd; 9525 ++Base) { 9526 // Virtual bases are handled below. 9527 if (Base->isVirtual()) 9528 continue; 9529 9530 CXXRecordDecl *BaseClassDecl 9531 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9532 if (CXXConstructorDecl *CopyConstructor = 9533 LookupCopyingConstructor(BaseClassDecl, Quals)) 9534 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9535 } 9536 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9537 BaseEnd = ClassDecl->vbases_end(); 9538 Base != BaseEnd; 9539 ++Base) { 9540 CXXRecordDecl *BaseClassDecl 9541 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9542 if (CXXConstructorDecl *CopyConstructor = 9543 LookupCopyingConstructor(BaseClassDecl, Quals)) 9544 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9545 } 9546 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9547 FieldEnd = ClassDecl->field_end(); 9548 Field != FieldEnd; 9549 ++Field) { 9550 QualType FieldType = Context.getBaseElementType(Field->getType()); 9551 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9552 if (CXXConstructorDecl *CopyConstructor = 9553 LookupCopyingConstructor(FieldClassDecl, 9554 Quals | FieldType.getCVRQualifiers())) 9555 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9556 } 9557 } 9558 9559 return ExceptSpec; 9560} 9561 9562CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9563 CXXRecordDecl *ClassDecl) { 9564 // C++ [class.copy]p4: 9565 // If the class definition does not explicitly declare a copy 9566 // constructor, one is declared implicitly. 9567 assert(ClassDecl->needsImplicitCopyConstructor()); 9568 9569 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9570 if (DSM.isAlreadyBeingDeclared()) 9571 return 0; 9572 9573 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9574 QualType ArgType = ClassType; 9575 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9576 if (Const) 9577 ArgType = ArgType.withConst(); 9578 ArgType = Context.getLValueReferenceType(ArgType); 9579 9580 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9581 CXXCopyConstructor, 9582 Const); 9583 9584 DeclarationName Name 9585 = Context.DeclarationNames.getCXXConstructorName( 9586 Context.getCanonicalType(ClassType)); 9587 SourceLocation ClassLoc = ClassDecl->getLocation(); 9588 DeclarationNameInfo NameInfo(Name, ClassLoc); 9589 9590 // An implicitly-declared copy constructor is an inline public 9591 // member of its class. 9592 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9593 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9594 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9595 Constexpr); 9596 CopyConstructor->setAccess(AS_public); 9597 CopyConstructor->setDefaulted(); 9598 9599 // Build an exception specification pointing back at this member. 9600 FunctionProtoType::ExtProtoInfo EPI; 9601 EPI.ExceptionSpecType = EST_Unevaluated; 9602 EPI.ExceptionSpecDecl = CopyConstructor; 9603 CopyConstructor->setType( 9604 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9605 9606 // Add the parameter to the constructor. 9607 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9608 ClassLoc, ClassLoc, 9609 /*IdentifierInfo=*/0, 9610 ArgType, /*TInfo=*/0, 9611 SC_None, 0); 9612 CopyConstructor->setParams(FromParam); 9613 9614 CopyConstructor->setTrivial( 9615 ClassDecl->needsOverloadResolutionForCopyConstructor() 9616 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9617 : ClassDecl->hasTrivialCopyConstructor()); 9618 9619 // C++11 [class.copy]p8: 9620 // ... If the class definition does not explicitly declare a copy 9621 // constructor, there is no user-declared move constructor, and there is no 9622 // user-declared move assignment operator, a copy constructor is implicitly 9623 // declared as defaulted. 9624 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9625 SetDeclDeleted(CopyConstructor, ClassLoc); 9626 9627 // Note that we have declared this constructor. 9628 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9629 9630 if (Scope *S = getScopeForContext(ClassDecl)) 9631 PushOnScopeChains(CopyConstructor, S, false); 9632 ClassDecl->addDecl(CopyConstructor); 9633 9634 return CopyConstructor; 9635} 9636 9637void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9638 CXXConstructorDecl *CopyConstructor) { 9639 assert((CopyConstructor->isDefaulted() && 9640 CopyConstructor->isCopyConstructor() && 9641 !CopyConstructor->doesThisDeclarationHaveABody() && 9642 !CopyConstructor->isDeleted()) && 9643 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9644 9645 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9646 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9647 9648 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9649 DiagnosticErrorTrap Trap(Diags); 9650 9651 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9652 Trap.hasErrorOccurred()) { 9653 Diag(CurrentLocation, diag::note_member_synthesized_at) 9654 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9655 CopyConstructor->setInvalidDecl(); 9656 } else { 9657 Sema::CompoundScopeRAII CompoundScope(*this); 9658 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9659 CopyConstructor->getLocation(), 9660 MultiStmtArg(), 9661 /*isStmtExpr=*/false) 9662 .takeAs<Stmt>()); 9663 CopyConstructor->setImplicitlyDefined(true); 9664 } 9665 9666 CopyConstructor->setUsed(); 9667 if (ASTMutationListener *L = getASTMutationListener()) { 9668 L->CompletedImplicitDefinition(CopyConstructor); 9669 } 9670} 9671 9672Sema::ImplicitExceptionSpecification 9673Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9674 CXXRecordDecl *ClassDecl = MD->getParent(); 9675 9676 // C++ [except.spec]p14: 9677 // An implicitly declared special member function (Clause 12) shall have an 9678 // exception-specification. [...] 9679 ImplicitExceptionSpecification ExceptSpec(*this); 9680 if (ClassDecl->isInvalidDecl()) 9681 return ExceptSpec; 9682 9683 // Direct base-class constructors. 9684 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9685 BEnd = ClassDecl->bases_end(); 9686 B != BEnd; ++B) { 9687 if (B->isVirtual()) // Handled below. 9688 continue; 9689 9690 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9691 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9692 CXXConstructorDecl *Constructor = 9693 LookupMovingConstructor(BaseClassDecl, 0); 9694 // If this is a deleted function, add it anyway. This might be conformant 9695 // with the standard. This might not. I'm not sure. It might not matter. 9696 if (Constructor) 9697 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9698 } 9699 } 9700 9701 // Virtual base-class constructors. 9702 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9703 BEnd = ClassDecl->vbases_end(); 9704 B != BEnd; ++B) { 9705 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9706 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9707 CXXConstructorDecl *Constructor = 9708 LookupMovingConstructor(BaseClassDecl, 0); 9709 // If this is a deleted function, add it anyway. This might be conformant 9710 // with the standard. This might not. I'm not sure. It might not matter. 9711 if (Constructor) 9712 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9713 } 9714 } 9715 9716 // Field constructors. 9717 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9718 FEnd = ClassDecl->field_end(); 9719 F != FEnd; ++F) { 9720 QualType FieldType = Context.getBaseElementType(F->getType()); 9721 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9722 CXXConstructorDecl *Constructor = 9723 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9724 // If this is a deleted function, add it anyway. This might be conformant 9725 // with the standard. This might not. I'm not sure. It might not matter. 9726 // In particular, the problem is that this function never gets called. It 9727 // might just be ill-formed because this function attempts to refer to 9728 // a deleted function here. 9729 if (Constructor) 9730 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9731 } 9732 } 9733 9734 return ExceptSpec; 9735} 9736 9737CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9738 CXXRecordDecl *ClassDecl) { 9739 // C++11 [class.copy]p9: 9740 // If the definition of a class X does not explicitly declare a move 9741 // constructor, one will be implicitly declared as defaulted if and only if: 9742 // 9743 // - [first 4 bullets] 9744 assert(ClassDecl->needsImplicitMoveConstructor()); 9745 9746 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9747 if (DSM.isAlreadyBeingDeclared()) 9748 return 0; 9749 9750 // [Checked after we build the declaration] 9751 // - the move assignment operator would not be implicitly defined as 9752 // deleted, 9753 9754 // [DR1402]: 9755 // - each of X's non-static data members and direct or virtual base classes 9756 // has a type that either has a move constructor or is trivially copyable. 9757 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9758 ClassDecl->setFailedImplicitMoveConstructor(); 9759 return 0; 9760 } 9761 9762 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9763 QualType ArgType = Context.getRValueReferenceType(ClassType); 9764 9765 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9766 CXXMoveConstructor, 9767 false); 9768 9769 DeclarationName Name 9770 = Context.DeclarationNames.getCXXConstructorName( 9771 Context.getCanonicalType(ClassType)); 9772 SourceLocation ClassLoc = ClassDecl->getLocation(); 9773 DeclarationNameInfo NameInfo(Name, ClassLoc); 9774 9775 // C++11 [class.copy]p11: 9776 // An implicitly-declared copy/move constructor is an inline public 9777 // member of its class. 9778 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9779 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9780 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9781 Constexpr); 9782 MoveConstructor->setAccess(AS_public); 9783 MoveConstructor->setDefaulted(); 9784 9785 // Build an exception specification pointing back at this member. 9786 FunctionProtoType::ExtProtoInfo EPI; 9787 EPI.ExceptionSpecType = EST_Unevaluated; 9788 EPI.ExceptionSpecDecl = MoveConstructor; 9789 MoveConstructor->setType( 9790 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9791 9792 // Add the parameter to the constructor. 9793 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9794 ClassLoc, ClassLoc, 9795 /*IdentifierInfo=*/0, 9796 ArgType, /*TInfo=*/0, 9797 SC_None, 0); 9798 MoveConstructor->setParams(FromParam); 9799 9800 MoveConstructor->setTrivial( 9801 ClassDecl->needsOverloadResolutionForMoveConstructor() 9802 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9803 : ClassDecl->hasTrivialMoveConstructor()); 9804 9805 // C++0x [class.copy]p9: 9806 // If the definition of a class X does not explicitly declare a move 9807 // constructor, one will be implicitly declared as defaulted if and only if: 9808 // [...] 9809 // - the move constructor would not be implicitly defined as deleted. 9810 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9811 // Cache this result so that we don't try to generate this over and over 9812 // on every lookup, leaking memory and wasting time. 9813 ClassDecl->setFailedImplicitMoveConstructor(); 9814 return 0; 9815 } 9816 9817 // Note that we have declared this constructor. 9818 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9819 9820 if (Scope *S = getScopeForContext(ClassDecl)) 9821 PushOnScopeChains(MoveConstructor, S, false); 9822 ClassDecl->addDecl(MoveConstructor); 9823 9824 return MoveConstructor; 9825} 9826 9827void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9828 CXXConstructorDecl *MoveConstructor) { 9829 assert((MoveConstructor->isDefaulted() && 9830 MoveConstructor->isMoveConstructor() && 9831 !MoveConstructor->doesThisDeclarationHaveABody() && 9832 !MoveConstructor->isDeleted()) && 9833 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9834 9835 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9836 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9837 9838 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9839 DiagnosticErrorTrap Trap(Diags); 9840 9841 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9842 Trap.hasErrorOccurred()) { 9843 Diag(CurrentLocation, diag::note_member_synthesized_at) 9844 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9845 MoveConstructor->setInvalidDecl(); 9846 } else { 9847 Sema::CompoundScopeRAII CompoundScope(*this); 9848 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9849 MoveConstructor->getLocation(), 9850 MultiStmtArg(), 9851 /*isStmtExpr=*/false) 9852 .takeAs<Stmt>()); 9853 MoveConstructor->setImplicitlyDefined(true); 9854 } 9855 9856 MoveConstructor->setUsed(); 9857 9858 if (ASTMutationListener *L = getASTMutationListener()) { 9859 L->CompletedImplicitDefinition(MoveConstructor); 9860 } 9861} 9862 9863bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9864 return FD->isDeleted() && 9865 (FD->isDefaulted() || FD->isImplicit()) && 9866 isa<CXXMethodDecl>(FD); 9867} 9868 9869/// \brief Mark the call operator of the given lambda closure type as "used". 9870static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9871 CXXMethodDecl *CallOperator 9872 = cast<CXXMethodDecl>( 9873 Lambda->lookup( 9874 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9875 CallOperator->setReferenced(); 9876 CallOperator->setUsed(); 9877} 9878 9879void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9880 SourceLocation CurrentLocation, 9881 CXXConversionDecl *Conv) 9882{ 9883 CXXRecordDecl *Lambda = Conv->getParent(); 9884 9885 // Make sure that the lambda call operator is marked used. 9886 markLambdaCallOperatorUsed(*this, Lambda); 9887 9888 Conv->setUsed(); 9889 9890 SynthesizedFunctionScope Scope(*this, Conv); 9891 DiagnosticErrorTrap Trap(Diags); 9892 9893 // Return the address of the __invoke function. 9894 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9895 CXXMethodDecl *Invoke 9896 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9897 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9898 VK_LValue, Conv->getLocation()).take(); 9899 assert(FunctionRef && "Can't refer to __invoke function?"); 9900 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9901 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9902 Conv->getLocation(), 9903 Conv->getLocation())); 9904 9905 // Fill in the __invoke function with a dummy implementation. IR generation 9906 // will fill in the actual details. 9907 Invoke->setUsed(); 9908 Invoke->setReferenced(); 9909 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9910 9911 if (ASTMutationListener *L = getASTMutationListener()) { 9912 L->CompletedImplicitDefinition(Conv); 9913 L->CompletedImplicitDefinition(Invoke); 9914 } 9915} 9916 9917void Sema::DefineImplicitLambdaToBlockPointerConversion( 9918 SourceLocation CurrentLocation, 9919 CXXConversionDecl *Conv) 9920{ 9921 Conv->setUsed(); 9922 9923 SynthesizedFunctionScope Scope(*this, Conv); 9924 DiagnosticErrorTrap Trap(Diags); 9925 9926 // Copy-initialize the lambda object as needed to capture it. 9927 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9928 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9929 9930 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9931 Conv->getLocation(), 9932 Conv, DerefThis); 9933 9934 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9935 // behavior. Note that only the general conversion function does this 9936 // (since it's unusable otherwise); in the case where we inline the 9937 // block literal, it has block literal lifetime semantics. 9938 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9939 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9940 CK_CopyAndAutoreleaseBlockObject, 9941 BuildBlock.get(), 0, VK_RValue); 9942 9943 if (BuildBlock.isInvalid()) { 9944 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9945 Conv->setInvalidDecl(); 9946 return; 9947 } 9948 9949 // Create the return statement that returns the block from the conversion 9950 // function. 9951 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9952 if (Return.isInvalid()) { 9953 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9954 Conv->setInvalidDecl(); 9955 return; 9956 } 9957 9958 // Set the body of the conversion function. 9959 Stmt *ReturnS = Return.take(); 9960 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9961 Conv->getLocation(), 9962 Conv->getLocation())); 9963 9964 // We're done; notify the mutation listener, if any. 9965 if (ASTMutationListener *L = getASTMutationListener()) { 9966 L->CompletedImplicitDefinition(Conv); 9967 } 9968} 9969 9970/// \brief Determine whether the given list arguments contains exactly one 9971/// "real" (non-default) argument. 9972static bool hasOneRealArgument(MultiExprArg Args) { 9973 switch (Args.size()) { 9974 case 0: 9975 return false; 9976 9977 default: 9978 if (!Args[1]->isDefaultArgument()) 9979 return false; 9980 9981 // fall through 9982 case 1: 9983 return !Args[0]->isDefaultArgument(); 9984 } 9985 9986 return false; 9987} 9988 9989ExprResult 9990Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9991 CXXConstructorDecl *Constructor, 9992 MultiExprArg ExprArgs, 9993 bool HadMultipleCandidates, 9994 bool IsListInitialization, 9995 bool RequiresZeroInit, 9996 unsigned ConstructKind, 9997 SourceRange ParenRange) { 9998 bool Elidable = false; 9999 10000 // C++0x [class.copy]p34: 10001 // When certain criteria are met, an implementation is allowed to 10002 // omit the copy/move construction of a class object, even if the 10003 // copy/move constructor and/or destructor for the object have 10004 // side effects. [...] 10005 // - when a temporary class object that has not been bound to a 10006 // reference (12.2) would be copied/moved to a class object 10007 // with the same cv-unqualified type, the copy/move operation 10008 // can be omitted by constructing the temporary object 10009 // directly into the target of the omitted copy/move 10010 if (ConstructKind == CXXConstructExpr::CK_Complete && 10011 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10012 Expr *SubExpr = ExprArgs[0]; 10013 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10014 } 10015 10016 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10017 Elidable, ExprArgs, HadMultipleCandidates, 10018 IsListInitialization, RequiresZeroInit, 10019 ConstructKind, ParenRange); 10020} 10021 10022/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10023/// including handling of its default argument expressions. 10024ExprResult 10025Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10026 CXXConstructorDecl *Constructor, bool Elidable, 10027 MultiExprArg ExprArgs, 10028 bool HadMultipleCandidates, 10029 bool IsListInitialization, 10030 bool RequiresZeroInit, 10031 unsigned ConstructKind, 10032 SourceRange ParenRange) { 10033 MarkFunctionReferenced(ConstructLoc, Constructor); 10034 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10035 Constructor, Elidable, ExprArgs, 10036 HadMultipleCandidates, 10037 IsListInitialization, RequiresZeroInit, 10038 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10039 ParenRange)); 10040} 10041 10042void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10043 if (VD->isInvalidDecl()) return; 10044 10045 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10046 if (ClassDecl->isInvalidDecl()) return; 10047 if (ClassDecl->hasIrrelevantDestructor()) return; 10048 if (ClassDecl->isDependentContext()) return; 10049 10050 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10051 MarkFunctionReferenced(VD->getLocation(), Destructor); 10052 CheckDestructorAccess(VD->getLocation(), Destructor, 10053 PDiag(diag::err_access_dtor_var) 10054 << VD->getDeclName() 10055 << VD->getType()); 10056 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10057 10058 if (!VD->hasGlobalStorage()) return; 10059 10060 // Emit warning for non-trivial dtor in global scope (a real global, 10061 // class-static, function-static). 10062 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10063 10064 // TODO: this should be re-enabled for static locals by !CXAAtExit 10065 if (!VD->isStaticLocal()) 10066 Diag(VD->getLocation(), diag::warn_global_destructor); 10067} 10068 10069/// \brief Given a constructor and the set of arguments provided for the 10070/// constructor, convert the arguments and add any required default arguments 10071/// to form a proper call to this constructor. 10072/// 10073/// \returns true if an error occurred, false otherwise. 10074bool 10075Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10076 MultiExprArg ArgsPtr, 10077 SourceLocation Loc, 10078 SmallVectorImpl<Expr*> &ConvertedArgs, 10079 bool AllowExplicit, 10080 bool IsListInitialization) { 10081 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10082 unsigned NumArgs = ArgsPtr.size(); 10083 Expr **Args = ArgsPtr.data(); 10084 10085 const FunctionProtoType *Proto 10086 = Constructor->getType()->getAs<FunctionProtoType>(); 10087 assert(Proto && "Constructor without a prototype?"); 10088 unsigned NumArgsInProto = Proto->getNumArgs(); 10089 10090 // If too few arguments are available, we'll fill in the rest with defaults. 10091 if (NumArgs < NumArgsInProto) 10092 ConvertedArgs.reserve(NumArgsInProto); 10093 else 10094 ConvertedArgs.reserve(NumArgs); 10095 10096 VariadicCallType CallType = 10097 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10098 SmallVector<Expr *, 8> AllArgs; 10099 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10100 Proto, 0, 10101 llvm::makeArrayRef(Args, NumArgs), 10102 AllArgs, 10103 CallType, AllowExplicit, 10104 IsListInitialization); 10105 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10106 10107 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10108 10109 CheckConstructorCall(Constructor, 10110 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10111 AllArgs.size()), 10112 Proto, Loc); 10113 10114 return Invalid; 10115} 10116 10117static inline bool 10118CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10119 const FunctionDecl *FnDecl) { 10120 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10121 if (isa<NamespaceDecl>(DC)) { 10122 return SemaRef.Diag(FnDecl->getLocation(), 10123 diag::err_operator_new_delete_declared_in_namespace) 10124 << FnDecl->getDeclName(); 10125 } 10126 10127 if (isa<TranslationUnitDecl>(DC) && 10128 FnDecl->getStorageClass() == SC_Static) { 10129 return SemaRef.Diag(FnDecl->getLocation(), 10130 diag::err_operator_new_delete_declared_static) 10131 << FnDecl->getDeclName(); 10132 } 10133 10134 return false; 10135} 10136 10137static inline bool 10138CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10139 CanQualType ExpectedResultType, 10140 CanQualType ExpectedFirstParamType, 10141 unsigned DependentParamTypeDiag, 10142 unsigned InvalidParamTypeDiag) { 10143 QualType ResultType = 10144 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10145 10146 // Check that the result type is not dependent. 10147 if (ResultType->isDependentType()) 10148 return SemaRef.Diag(FnDecl->getLocation(), 10149 diag::err_operator_new_delete_dependent_result_type) 10150 << FnDecl->getDeclName() << ExpectedResultType; 10151 10152 // Check that the result type is what we expect. 10153 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10154 return SemaRef.Diag(FnDecl->getLocation(), 10155 diag::err_operator_new_delete_invalid_result_type) 10156 << FnDecl->getDeclName() << ExpectedResultType; 10157 10158 // A function template must have at least 2 parameters. 10159 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10160 return SemaRef.Diag(FnDecl->getLocation(), 10161 diag::err_operator_new_delete_template_too_few_parameters) 10162 << FnDecl->getDeclName(); 10163 10164 // The function decl must have at least 1 parameter. 10165 if (FnDecl->getNumParams() == 0) 10166 return SemaRef.Diag(FnDecl->getLocation(), 10167 diag::err_operator_new_delete_too_few_parameters) 10168 << FnDecl->getDeclName(); 10169 10170 // Check the first parameter type is not dependent. 10171 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10172 if (FirstParamType->isDependentType()) 10173 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10174 << FnDecl->getDeclName() << ExpectedFirstParamType; 10175 10176 // Check that the first parameter type is what we expect. 10177 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10178 ExpectedFirstParamType) 10179 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10180 << FnDecl->getDeclName() << ExpectedFirstParamType; 10181 10182 return false; 10183} 10184 10185static bool 10186CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10187 // C++ [basic.stc.dynamic.allocation]p1: 10188 // A program is ill-formed if an allocation function is declared in a 10189 // namespace scope other than global scope or declared static in global 10190 // scope. 10191 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10192 return true; 10193 10194 CanQualType SizeTy = 10195 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10196 10197 // C++ [basic.stc.dynamic.allocation]p1: 10198 // The return type shall be void*. The first parameter shall have type 10199 // std::size_t. 10200 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10201 SizeTy, 10202 diag::err_operator_new_dependent_param_type, 10203 diag::err_operator_new_param_type)) 10204 return true; 10205 10206 // C++ [basic.stc.dynamic.allocation]p1: 10207 // The first parameter shall not have an associated default argument. 10208 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10209 return SemaRef.Diag(FnDecl->getLocation(), 10210 diag::err_operator_new_default_arg) 10211 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10212 10213 return false; 10214} 10215 10216static bool 10217CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10218 // C++ [basic.stc.dynamic.deallocation]p1: 10219 // A program is ill-formed if deallocation functions are declared in a 10220 // namespace scope other than global scope or declared static in global 10221 // scope. 10222 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10223 return true; 10224 10225 // C++ [basic.stc.dynamic.deallocation]p2: 10226 // Each deallocation function shall return void and its first parameter 10227 // shall be void*. 10228 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10229 SemaRef.Context.VoidPtrTy, 10230 diag::err_operator_delete_dependent_param_type, 10231 diag::err_operator_delete_param_type)) 10232 return true; 10233 10234 return false; 10235} 10236 10237/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10238/// of this overloaded operator is well-formed. If so, returns false; 10239/// otherwise, emits appropriate diagnostics and returns true. 10240bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10241 assert(FnDecl && FnDecl->isOverloadedOperator() && 10242 "Expected an overloaded operator declaration"); 10243 10244 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10245 10246 // C++ [over.oper]p5: 10247 // The allocation and deallocation functions, operator new, 10248 // operator new[], operator delete and operator delete[], are 10249 // described completely in 3.7.3. The attributes and restrictions 10250 // found in the rest of this subclause do not apply to them unless 10251 // explicitly stated in 3.7.3. 10252 if (Op == OO_Delete || Op == OO_Array_Delete) 10253 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10254 10255 if (Op == OO_New || Op == OO_Array_New) 10256 return CheckOperatorNewDeclaration(*this, FnDecl); 10257 10258 // C++ [over.oper]p6: 10259 // An operator function shall either be a non-static member 10260 // function or be a non-member function and have at least one 10261 // parameter whose type is a class, a reference to a class, an 10262 // enumeration, or a reference to an enumeration. 10263 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10264 if (MethodDecl->isStatic()) 10265 return Diag(FnDecl->getLocation(), 10266 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10267 } else { 10268 bool ClassOrEnumParam = false; 10269 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10270 ParamEnd = FnDecl->param_end(); 10271 Param != ParamEnd; ++Param) { 10272 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10273 if (ParamType->isDependentType() || ParamType->isRecordType() || 10274 ParamType->isEnumeralType()) { 10275 ClassOrEnumParam = true; 10276 break; 10277 } 10278 } 10279 10280 if (!ClassOrEnumParam) 10281 return Diag(FnDecl->getLocation(), 10282 diag::err_operator_overload_needs_class_or_enum) 10283 << FnDecl->getDeclName(); 10284 } 10285 10286 // C++ [over.oper]p8: 10287 // An operator function cannot have default arguments (8.3.6), 10288 // except where explicitly stated below. 10289 // 10290 // Only the function-call operator allows default arguments 10291 // (C++ [over.call]p1). 10292 if (Op != OO_Call) { 10293 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10294 Param != FnDecl->param_end(); ++Param) { 10295 if ((*Param)->hasDefaultArg()) 10296 return Diag((*Param)->getLocation(), 10297 diag::err_operator_overload_default_arg) 10298 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10299 } 10300 } 10301 10302 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10303 { false, false, false } 10304#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10305 , { Unary, Binary, MemberOnly } 10306#include "clang/Basic/OperatorKinds.def" 10307 }; 10308 10309 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10310 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10311 bool MustBeMemberOperator = OperatorUses[Op][2]; 10312 10313 // C++ [over.oper]p8: 10314 // [...] Operator functions cannot have more or fewer parameters 10315 // than the number required for the corresponding operator, as 10316 // described in the rest of this subclause. 10317 unsigned NumParams = FnDecl->getNumParams() 10318 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10319 if (Op != OO_Call && 10320 ((NumParams == 1 && !CanBeUnaryOperator) || 10321 (NumParams == 2 && !CanBeBinaryOperator) || 10322 (NumParams < 1) || (NumParams > 2))) { 10323 // We have the wrong number of parameters. 10324 unsigned ErrorKind; 10325 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10326 ErrorKind = 2; // 2 -> unary or binary. 10327 } else if (CanBeUnaryOperator) { 10328 ErrorKind = 0; // 0 -> unary 10329 } else { 10330 assert(CanBeBinaryOperator && 10331 "All non-call overloaded operators are unary or binary!"); 10332 ErrorKind = 1; // 1 -> binary 10333 } 10334 10335 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10336 << FnDecl->getDeclName() << NumParams << ErrorKind; 10337 } 10338 10339 // Overloaded operators other than operator() cannot be variadic. 10340 if (Op != OO_Call && 10341 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10342 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10343 << FnDecl->getDeclName(); 10344 } 10345 10346 // Some operators must be non-static member functions. 10347 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10348 return Diag(FnDecl->getLocation(), 10349 diag::err_operator_overload_must_be_member) 10350 << FnDecl->getDeclName(); 10351 } 10352 10353 // C++ [over.inc]p1: 10354 // The user-defined function called operator++ implements the 10355 // prefix and postfix ++ operator. If this function is a member 10356 // function with no parameters, or a non-member function with one 10357 // parameter of class or enumeration type, it defines the prefix 10358 // increment operator ++ for objects of that type. If the function 10359 // is a member function with one parameter (which shall be of type 10360 // int) or a non-member function with two parameters (the second 10361 // of which shall be of type int), it defines the postfix 10362 // increment operator ++ for objects of that type. 10363 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10364 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10365 bool ParamIsInt = false; 10366 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10367 ParamIsInt = BT->getKind() == BuiltinType::Int; 10368 10369 if (!ParamIsInt) 10370 return Diag(LastParam->getLocation(), 10371 diag::err_operator_overload_post_incdec_must_be_int) 10372 << LastParam->getType() << (Op == OO_MinusMinus); 10373 } 10374 10375 return false; 10376} 10377 10378/// CheckLiteralOperatorDeclaration - Check whether the declaration 10379/// of this literal operator function is well-formed. If so, returns 10380/// false; otherwise, emits appropriate diagnostics and returns true. 10381bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10382 if (isa<CXXMethodDecl>(FnDecl)) { 10383 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10384 << FnDecl->getDeclName(); 10385 return true; 10386 } 10387 10388 if (FnDecl->isExternC()) { 10389 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10390 return true; 10391 } 10392 10393 bool Valid = false; 10394 10395 // This might be the definition of a literal operator template. 10396 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10397 // This might be a specialization of a literal operator template. 10398 if (!TpDecl) 10399 TpDecl = FnDecl->getPrimaryTemplate(); 10400 10401 // template <char...> type operator "" name() is the only valid template 10402 // signature, and the only valid signature with no parameters. 10403 if (TpDecl) { 10404 if (FnDecl->param_size() == 0) { 10405 // Must have only one template parameter 10406 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10407 if (Params->size() == 1) { 10408 NonTypeTemplateParmDecl *PmDecl = 10409 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10410 10411 // The template parameter must be a char parameter pack. 10412 if (PmDecl && PmDecl->isTemplateParameterPack() && 10413 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10414 Valid = true; 10415 } 10416 } 10417 } else if (FnDecl->param_size()) { 10418 // Check the first parameter 10419 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10420 10421 QualType T = (*Param)->getType().getUnqualifiedType(); 10422 10423 // unsigned long long int, long double, and any character type are allowed 10424 // as the only parameters. 10425 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10426 Context.hasSameType(T, Context.LongDoubleTy) || 10427 Context.hasSameType(T, Context.CharTy) || 10428 Context.hasSameType(T, Context.WideCharTy) || 10429 Context.hasSameType(T, Context.Char16Ty) || 10430 Context.hasSameType(T, Context.Char32Ty)) { 10431 if (++Param == FnDecl->param_end()) 10432 Valid = true; 10433 goto FinishedParams; 10434 } 10435 10436 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10437 const PointerType *PT = T->getAs<PointerType>(); 10438 if (!PT) 10439 goto FinishedParams; 10440 T = PT->getPointeeType(); 10441 if (!T.isConstQualified() || T.isVolatileQualified()) 10442 goto FinishedParams; 10443 T = T.getUnqualifiedType(); 10444 10445 // Move on to the second parameter; 10446 ++Param; 10447 10448 // If there is no second parameter, the first must be a const char * 10449 if (Param == FnDecl->param_end()) { 10450 if (Context.hasSameType(T, Context.CharTy)) 10451 Valid = true; 10452 goto FinishedParams; 10453 } 10454 10455 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10456 // are allowed as the first parameter to a two-parameter function 10457 if (!(Context.hasSameType(T, Context.CharTy) || 10458 Context.hasSameType(T, Context.WideCharTy) || 10459 Context.hasSameType(T, Context.Char16Ty) || 10460 Context.hasSameType(T, Context.Char32Ty))) 10461 goto FinishedParams; 10462 10463 // The second and final parameter must be an std::size_t 10464 T = (*Param)->getType().getUnqualifiedType(); 10465 if (Context.hasSameType(T, Context.getSizeType()) && 10466 ++Param == FnDecl->param_end()) 10467 Valid = true; 10468 } 10469 10470 // FIXME: This diagnostic is absolutely terrible. 10471FinishedParams: 10472 if (!Valid) { 10473 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10474 << FnDecl->getDeclName(); 10475 return true; 10476 } 10477 10478 // A parameter-declaration-clause containing a default argument is not 10479 // equivalent to any of the permitted forms. 10480 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10481 ParamEnd = FnDecl->param_end(); 10482 Param != ParamEnd; ++Param) { 10483 if ((*Param)->hasDefaultArg()) { 10484 Diag((*Param)->getDefaultArgRange().getBegin(), 10485 diag::err_literal_operator_default_argument) 10486 << (*Param)->getDefaultArgRange(); 10487 break; 10488 } 10489 } 10490 10491 StringRef LiteralName 10492 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10493 if (LiteralName[0] != '_') { 10494 // C++11 [usrlit.suffix]p1: 10495 // Literal suffix identifiers that do not start with an underscore 10496 // are reserved for future standardization. 10497 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10498 } 10499 10500 return false; 10501} 10502 10503/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10504/// linkage specification, including the language and (if present) 10505/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10506/// the location of the language string literal, which is provided 10507/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10508/// the '{' brace. Otherwise, this linkage specification does not 10509/// have any braces. 10510Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10511 SourceLocation LangLoc, 10512 StringRef Lang, 10513 SourceLocation LBraceLoc) { 10514 LinkageSpecDecl::LanguageIDs Language; 10515 if (Lang == "\"C\"") 10516 Language = LinkageSpecDecl::lang_c; 10517 else if (Lang == "\"C++\"") 10518 Language = LinkageSpecDecl::lang_cxx; 10519 else { 10520 Diag(LangLoc, diag::err_bad_language); 10521 return 0; 10522 } 10523 10524 // FIXME: Add all the various semantics of linkage specifications 10525 10526 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10527 ExternLoc, LangLoc, Language, 10528 LBraceLoc.isValid()); 10529 CurContext->addDecl(D); 10530 PushDeclContext(S, D); 10531 return D; 10532} 10533 10534/// ActOnFinishLinkageSpecification - Complete the definition of 10535/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10536/// valid, it's the position of the closing '}' brace in a linkage 10537/// specification that uses braces. 10538Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10539 Decl *LinkageSpec, 10540 SourceLocation RBraceLoc) { 10541 if (LinkageSpec) { 10542 if (RBraceLoc.isValid()) { 10543 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10544 LSDecl->setRBraceLoc(RBraceLoc); 10545 } 10546 PopDeclContext(); 10547 } 10548 return LinkageSpec; 10549} 10550 10551Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10552 AttributeList *AttrList, 10553 SourceLocation SemiLoc) { 10554 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10555 // Attribute declarations appertain to empty declaration so we handle 10556 // them here. 10557 if (AttrList) 10558 ProcessDeclAttributeList(S, ED, AttrList); 10559 10560 CurContext->addDecl(ED); 10561 return ED; 10562} 10563 10564/// \brief Perform semantic analysis for the variable declaration that 10565/// occurs within a C++ catch clause, returning the newly-created 10566/// variable. 10567VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10568 TypeSourceInfo *TInfo, 10569 SourceLocation StartLoc, 10570 SourceLocation Loc, 10571 IdentifierInfo *Name) { 10572 bool Invalid = false; 10573 QualType ExDeclType = TInfo->getType(); 10574 10575 // Arrays and functions decay. 10576 if (ExDeclType->isArrayType()) 10577 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10578 else if (ExDeclType->isFunctionType()) 10579 ExDeclType = Context.getPointerType(ExDeclType); 10580 10581 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10582 // The exception-declaration shall not denote a pointer or reference to an 10583 // incomplete type, other than [cv] void*. 10584 // N2844 forbids rvalue references. 10585 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10586 Diag(Loc, diag::err_catch_rvalue_ref); 10587 Invalid = true; 10588 } 10589 10590 QualType BaseType = ExDeclType; 10591 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10592 unsigned DK = diag::err_catch_incomplete; 10593 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10594 BaseType = Ptr->getPointeeType(); 10595 Mode = 1; 10596 DK = diag::err_catch_incomplete_ptr; 10597 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10598 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10599 BaseType = Ref->getPointeeType(); 10600 Mode = 2; 10601 DK = diag::err_catch_incomplete_ref; 10602 } 10603 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10604 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10605 Invalid = true; 10606 10607 if (!Invalid && !ExDeclType->isDependentType() && 10608 RequireNonAbstractType(Loc, ExDeclType, 10609 diag::err_abstract_type_in_decl, 10610 AbstractVariableType)) 10611 Invalid = true; 10612 10613 // Only the non-fragile NeXT runtime currently supports C++ catches 10614 // of ObjC types, and no runtime supports catching ObjC types by value. 10615 if (!Invalid && getLangOpts().ObjC1) { 10616 QualType T = ExDeclType; 10617 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10618 T = RT->getPointeeType(); 10619 10620 if (T->isObjCObjectType()) { 10621 Diag(Loc, diag::err_objc_object_catch); 10622 Invalid = true; 10623 } else if (T->isObjCObjectPointerType()) { 10624 // FIXME: should this be a test for macosx-fragile specifically? 10625 if (getLangOpts().ObjCRuntime.isFragile()) 10626 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10627 } 10628 } 10629 10630 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10631 ExDeclType, TInfo, SC_None); 10632 ExDecl->setExceptionVariable(true); 10633 10634 // In ARC, infer 'retaining' for variables of retainable type. 10635 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10636 Invalid = true; 10637 10638 if (!Invalid && !ExDeclType->isDependentType()) { 10639 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10640 // Insulate this from anything else we might currently be parsing. 10641 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10642 10643 // C++ [except.handle]p16: 10644 // The object declared in an exception-declaration or, if the 10645 // exception-declaration does not specify a name, a temporary (12.2) is 10646 // copy-initialized (8.5) from the exception object. [...] 10647 // The object is destroyed when the handler exits, after the destruction 10648 // of any automatic objects initialized within the handler. 10649 // 10650 // We just pretend to initialize the object with itself, then make sure 10651 // it can be destroyed later. 10652 QualType initType = ExDeclType; 10653 10654 InitializedEntity entity = 10655 InitializedEntity::InitializeVariable(ExDecl); 10656 InitializationKind initKind = 10657 InitializationKind::CreateCopy(Loc, SourceLocation()); 10658 10659 Expr *opaqueValue = 10660 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10661 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 10662 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 10663 if (result.isInvalid()) 10664 Invalid = true; 10665 else { 10666 // If the constructor used was non-trivial, set this as the 10667 // "initializer". 10668 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10669 if (!construct->getConstructor()->isTrivial()) { 10670 Expr *init = MaybeCreateExprWithCleanups(construct); 10671 ExDecl->setInit(init); 10672 } 10673 10674 // And make sure it's destructable. 10675 FinalizeVarWithDestructor(ExDecl, recordType); 10676 } 10677 } 10678 } 10679 10680 if (Invalid) 10681 ExDecl->setInvalidDecl(); 10682 10683 return ExDecl; 10684} 10685 10686/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10687/// handler. 10688Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10689 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10690 bool Invalid = D.isInvalidType(); 10691 10692 // Check for unexpanded parameter packs. 10693 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10694 UPPC_ExceptionType)) { 10695 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10696 D.getIdentifierLoc()); 10697 Invalid = true; 10698 } 10699 10700 IdentifierInfo *II = D.getIdentifier(); 10701 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10702 LookupOrdinaryName, 10703 ForRedeclaration)) { 10704 // The scope should be freshly made just for us. There is just no way 10705 // it contains any previous declaration. 10706 assert(!S->isDeclScope(PrevDecl)); 10707 if (PrevDecl->isTemplateParameter()) { 10708 // Maybe we will complain about the shadowed template parameter. 10709 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10710 PrevDecl = 0; 10711 } 10712 } 10713 10714 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10715 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10716 << D.getCXXScopeSpec().getRange(); 10717 Invalid = true; 10718 } 10719 10720 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10721 D.getLocStart(), 10722 D.getIdentifierLoc(), 10723 D.getIdentifier()); 10724 if (Invalid) 10725 ExDecl->setInvalidDecl(); 10726 10727 // Add the exception declaration into this scope. 10728 if (II) 10729 PushOnScopeChains(ExDecl, S); 10730 else 10731 CurContext->addDecl(ExDecl); 10732 10733 ProcessDeclAttributes(S, ExDecl, D); 10734 return ExDecl; 10735} 10736 10737Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10738 Expr *AssertExpr, 10739 Expr *AssertMessageExpr, 10740 SourceLocation RParenLoc) { 10741 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10742 10743 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10744 return 0; 10745 10746 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10747 AssertMessage, RParenLoc, false); 10748} 10749 10750Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10751 Expr *AssertExpr, 10752 StringLiteral *AssertMessage, 10753 SourceLocation RParenLoc, 10754 bool Failed) { 10755 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10756 !Failed) { 10757 // In a static_assert-declaration, the constant-expression shall be a 10758 // constant expression that can be contextually converted to bool. 10759 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10760 if (Converted.isInvalid()) 10761 Failed = true; 10762 10763 llvm::APSInt Cond; 10764 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10765 diag::err_static_assert_expression_is_not_constant, 10766 /*AllowFold=*/false).isInvalid()) 10767 Failed = true; 10768 10769 if (!Failed && !Cond) { 10770 SmallString<256> MsgBuffer; 10771 llvm::raw_svector_ostream Msg(MsgBuffer); 10772 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10773 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10774 << Msg.str() << AssertExpr->getSourceRange(); 10775 Failed = true; 10776 } 10777 } 10778 10779 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10780 AssertExpr, AssertMessage, RParenLoc, 10781 Failed); 10782 10783 CurContext->addDecl(Decl); 10784 return Decl; 10785} 10786 10787/// \brief Perform semantic analysis of the given friend type declaration. 10788/// 10789/// \returns A friend declaration that. 10790FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10791 SourceLocation FriendLoc, 10792 TypeSourceInfo *TSInfo) { 10793 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10794 10795 QualType T = TSInfo->getType(); 10796 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10797 10798 // C++03 [class.friend]p2: 10799 // An elaborated-type-specifier shall be used in a friend declaration 10800 // for a class.* 10801 // 10802 // * The class-key of the elaborated-type-specifier is required. 10803 if (!ActiveTemplateInstantiations.empty()) { 10804 // Do not complain about the form of friend template types during 10805 // template instantiation; we will already have complained when the 10806 // template was declared. 10807 } else { 10808 if (!T->isElaboratedTypeSpecifier()) { 10809 // If we evaluated the type to a record type, suggest putting 10810 // a tag in front. 10811 if (const RecordType *RT = T->getAs<RecordType>()) { 10812 RecordDecl *RD = RT->getDecl(); 10813 10814 std::string InsertionText = std::string(" ") + RD->getKindName(); 10815 10816 Diag(TypeRange.getBegin(), 10817 getLangOpts().CPlusPlus11 ? 10818 diag::warn_cxx98_compat_unelaborated_friend_type : 10819 diag::ext_unelaborated_friend_type) 10820 << (unsigned) RD->getTagKind() 10821 << T 10822 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10823 InsertionText); 10824 } else { 10825 Diag(FriendLoc, 10826 getLangOpts().CPlusPlus11 ? 10827 diag::warn_cxx98_compat_nonclass_type_friend : 10828 diag::ext_nonclass_type_friend) 10829 << T 10830 << TypeRange; 10831 } 10832 } else if (T->getAs<EnumType>()) { 10833 Diag(FriendLoc, 10834 getLangOpts().CPlusPlus11 ? 10835 diag::warn_cxx98_compat_enum_friend : 10836 diag::ext_enum_friend) 10837 << T 10838 << TypeRange; 10839 } 10840 10841 // C++11 [class.friend]p3: 10842 // A friend declaration that does not declare a function shall have one 10843 // of the following forms: 10844 // friend elaborated-type-specifier ; 10845 // friend simple-type-specifier ; 10846 // friend typename-specifier ; 10847 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10848 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10849 } 10850 10851 // If the type specifier in a friend declaration designates a (possibly 10852 // cv-qualified) class type, that class is declared as a friend; otherwise, 10853 // the friend declaration is ignored. 10854 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10855} 10856 10857/// Handle a friend tag declaration where the scope specifier was 10858/// templated. 10859Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10860 unsigned TagSpec, SourceLocation TagLoc, 10861 CXXScopeSpec &SS, 10862 IdentifierInfo *Name, 10863 SourceLocation NameLoc, 10864 AttributeList *Attr, 10865 MultiTemplateParamsArg TempParamLists) { 10866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10867 10868 bool isExplicitSpecialization = false; 10869 bool Invalid = false; 10870 10871 if (TemplateParameterList *TemplateParams 10872 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10873 TempParamLists.data(), 10874 TempParamLists.size(), 10875 /*friend*/ true, 10876 isExplicitSpecialization, 10877 Invalid)) { 10878 if (TemplateParams->size() > 0) { 10879 // This is a declaration of a class template. 10880 if (Invalid) 10881 return 0; 10882 10883 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10884 SS, Name, NameLoc, Attr, 10885 TemplateParams, AS_public, 10886 /*ModulePrivateLoc=*/SourceLocation(), 10887 TempParamLists.size() - 1, 10888 TempParamLists.data()).take(); 10889 } else { 10890 // The "template<>" header is extraneous. 10891 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10892 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10893 isExplicitSpecialization = true; 10894 } 10895 } 10896 10897 if (Invalid) return 0; 10898 10899 bool isAllExplicitSpecializations = true; 10900 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10901 if (TempParamLists[I]->size()) { 10902 isAllExplicitSpecializations = false; 10903 break; 10904 } 10905 } 10906 10907 // FIXME: don't ignore attributes. 10908 10909 // If it's explicit specializations all the way down, just forget 10910 // about the template header and build an appropriate non-templated 10911 // friend. TODO: for source fidelity, remember the headers. 10912 if (isAllExplicitSpecializations) { 10913 if (SS.isEmpty()) { 10914 bool Owned = false; 10915 bool IsDependent = false; 10916 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10917 Attr, AS_public, 10918 /*ModulePrivateLoc=*/SourceLocation(), 10919 MultiTemplateParamsArg(), Owned, IsDependent, 10920 /*ScopedEnumKWLoc=*/SourceLocation(), 10921 /*ScopedEnumUsesClassTag=*/false, 10922 /*UnderlyingType=*/TypeResult()); 10923 } 10924 10925 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10926 ElaboratedTypeKeyword Keyword 10927 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10928 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10929 *Name, NameLoc); 10930 if (T.isNull()) 10931 return 0; 10932 10933 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10934 if (isa<DependentNameType>(T)) { 10935 DependentNameTypeLoc TL = 10936 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10937 TL.setElaboratedKeywordLoc(TagLoc); 10938 TL.setQualifierLoc(QualifierLoc); 10939 TL.setNameLoc(NameLoc); 10940 } else { 10941 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 10942 TL.setElaboratedKeywordLoc(TagLoc); 10943 TL.setQualifierLoc(QualifierLoc); 10944 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 10945 } 10946 10947 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10948 TSI, FriendLoc, TempParamLists); 10949 Friend->setAccess(AS_public); 10950 CurContext->addDecl(Friend); 10951 return Friend; 10952 } 10953 10954 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10955 10956 10957 10958 // Handle the case of a templated-scope friend class. e.g. 10959 // template <class T> class A<T>::B; 10960 // FIXME: we don't support these right now. 10961 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10962 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10963 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10964 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10965 TL.setElaboratedKeywordLoc(TagLoc); 10966 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10967 TL.setNameLoc(NameLoc); 10968 10969 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10970 TSI, FriendLoc, TempParamLists); 10971 Friend->setAccess(AS_public); 10972 Friend->setUnsupportedFriend(true); 10973 CurContext->addDecl(Friend); 10974 return Friend; 10975} 10976 10977 10978/// Handle a friend type declaration. This works in tandem with 10979/// ActOnTag. 10980/// 10981/// Notes on friend class templates: 10982/// 10983/// We generally treat friend class declarations as if they were 10984/// declaring a class. So, for example, the elaborated type specifier 10985/// in a friend declaration is required to obey the restrictions of a 10986/// class-head (i.e. no typedefs in the scope chain), template 10987/// parameters are required to match up with simple template-ids, &c. 10988/// However, unlike when declaring a template specialization, it's 10989/// okay to refer to a template specialization without an empty 10990/// template parameter declaration, e.g. 10991/// friend class A<T>::B<unsigned>; 10992/// We permit this as a special case; if there are any template 10993/// parameters present at all, require proper matching, i.e. 10994/// template <> template \<class T> friend class A<int>::B; 10995Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10996 MultiTemplateParamsArg TempParams) { 10997 SourceLocation Loc = DS.getLocStart(); 10998 10999 assert(DS.isFriendSpecified()); 11000 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11001 11002 // Try to convert the decl specifier to a type. This works for 11003 // friend templates because ActOnTag never produces a ClassTemplateDecl 11004 // for a TUK_Friend. 11005 Declarator TheDeclarator(DS, Declarator::MemberContext); 11006 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11007 QualType T = TSI->getType(); 11008 if (TheDeclarator.isInvalidType()) 11009 return 0; 11010 11011 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11012 return 0; 11013 11014 // This is definitely an error in C++98. It's probably meant to 11015 // be forbidden in C++0x, too, but the specification is just 11016 // poorly written. 11017 // 11018 // The problem is with declarations like the following: 11019 // template <T> friend A<T>::foo; 11020 // where deciding whether a class C is a friend or not now hinges 11021 // on whether there exists an instantiation of A that causes 11022 // 'foo' to equal C. There are restrictions on class-heads 11023 // (which we declare (by fiat) elaborated friend declarations to 11024 // be) that makes this tractable. 11025 // 11026 // FIXME: handle "template <> friend class A<T>;", which 11027 // is possibly well-formed? Who even knows? 11028 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11029 Diag(Loc, diag::err_tagless_friend_type_template) 11030 << DS.getSourceRange(); 11031 return 0; 11032 } 11033 11034 // C++98 [class.friend]p1: A friend of a class is a function 11035 // or class that is not a member of the class . . . 11036 // This is fixed in DR77, which just barely didn't make the C++03 11037 // deadline. It's also a very silly restriction that seriously 11038 // affects inner classes and which nobody else seems to implement; 11039 // thus we never diagnose it, not even in -pedantic. 11040 // 11041 // But note that we could warn about it: it's always useless to 11042 // friend one of your own members (it's not, however, worthless to 11043 // friend a member of an arbitrary specialization of your template). 11044 11045 Decl *D; 11046 if (unsigned NumTempParamLists = TempParams.size()) 11047 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11048 NumTempParamLists, 11049 TempParams.data(), 11050 TSI, 11051 DS.getFriendSpecLoc()); 11052 else 11053 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11054 11055 if (!D) 11056 return 0; 11057 11058 D->setAccess(AS_public); 11059 CurContext->addDecl(D); 11060 11061 return D; 11062} 11063 11064NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11065 MultiTemplateParamsArg TemplateParams) { 11066 const DeclSpec &DS = D.getDeclSpec(); 11067 11068 assert(DS.isFriendSpecified()); 11069 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11070 11071 SourceLocation Loc = D.getIdentifierLoc(); 11072 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11073 11074 // C++ [class.friend]p1 11075 // A friend of a class is a function or class.... 11076 // Note that this sees through typedefs, which is intended. 11077 // It *doesn't* see through dependent types, which is correct 11078 // according to [temp.arg.type]p3: 11079 // If a declaration acquires a function type through a 11080 // type dependent on a template-parameter and this causes 11081 // a declaration that does not use the syntactic form of a 11082 // function declarator to have a function type, the program 11083 // is ill-formed. 11084 if (!TInfo->getType()->isFunctionType()) { 11085 Diag(Loc, diag::err_unexpected_friend); 11086 11087 // It might be worthwhile to try to recover by creating an 11088 // appropriate declaration. 11089 return 0; 11090 } 11091 11092 // C++ [namespace.memdef]p3 11093 // - If a friend declaration in a non-local class first declares a 11094 // class or function, the friend class or function is a member 11095 // of the innermost enclosing namespace. 11096 // - The name of the friend is not found by simple name lookup 11097 // until a matching declaration is provided in that namespace 11098 // scope (either before or after the class declaration granting 11099 // friendship). 11100 // - If a friend function is called, its name may be found by the 11101 // name lookup that considers functions from namespaces and 11102 // classes associated with the types of the function arguments. 11103 // - When looking for a prior declaration of a class or a function 11104 // declared as a friend, scopes outside the innermost enclosing 11105 // namespace scope are not considered. 11106 11107 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11108 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11109 DeclarationName Name = NameInfo.getName(); 11110 assert(Name); 11111 11112 // Check for unexpanded parameter packs. 11113 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11114 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11115 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11116 return 0; 11117 11118 // The context we found the declaration in, or in which we should 11119 // create the declaration. 11120 DeclContext *DC; 11121 Scope *DCScope = S; 11122 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11123 ForRedeclaration); 11124 11125 // FIXME: there are different rules in local classes 11126 11127 // There are four cases here. 11128 // - There's no scope specifier, in which case we just go to the 11129 // appropriate scope and look for a function or function template 11130 // there as appropriate. 11131 // Recover from invalid scope qualifiers as if they just weren't there. 11132 if (SS.isInvalid() || !SS.isSet()) { 11133 // C++0x [namespace.memdef]p3: 11134 // If the name in a friend declaration is neither qualified nor 11135 // a template-id and the declaration is a function or an 11136 // elaborated-type-specifier, the lookup to determine whether 11137 // the entity has been previously declared shall not consider 11138 // any scopes outside the innermost enclosing namespace. 11139 // C++0x [class.friend]p11: 11140 // If a friend declaration appears in a local class and the name 11141 // specified is an unqualified name, a prior declaration is 11142 // looked up without considering scopes that are outside the 11143 // innermost enclosing non-class scope. For a friend function 11144 // declaration, if there is no prior declaration, the program is 11145 // ill-formed. 11146 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 11147 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11148 11149 // Find the appropriate context according to the above. 11150 DC = CurContext; 11151 11152 // Skip class contexts. If someone can cite chapter and verse 11153 // for this behavior, that would be nice --- it's what GCC and 11154 // EDG do, and it seems like a reasonable intent, but the spec 11155 // really only says that checks for unqualified existing 11156 // declarations should stop at the nearest enclosing namespace, 11157 // not that they should only consider the nearest enclosing 11158 // namespace. 11159 while (DC->isRecord()) 11160 DC = DC->getParent(); 11161 11162 DeclContext *LookupDC = DC; 11163 while (LookupDC->isTransparentContext()) 11164 LookupDC = LookupDC->getParent(); 11165 11166 while (true) { 11167 LookupQualifiedName(Previous, LookupDC); 11168 11169 // TODO: decide what we think about using declarations. 11170 if (isLocal) 11171 break; 11172 11173 if (!Previous.empty()) { 11174 DC = LookupDC; 11175 break; 11176 } 11177 11178 if (isTemplateId) { 11179 if (isa<TranslationUnitDecl>(LookupDC)) break; 11180 } else { 11181 if (LookupDC->isFileContext()) break; 11182 } 11183 LookupDC = LookupDC->getParent(); 11184 } 11185 11186 DCScope = getScopeForDeclContext(S, DC); 11187 11188 // C++ [class.friend]p6: 11189 // A function can be defined in a friend declaration of a class if and 11190 // only if the class is a non-local class (9.8), the function name is 11191 // unqualified, and the function has namespace scope. 11192 if (isLocal && D.isFunctionDefinition()) { 11193 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11194 } 11195 11196 // - There's a non-dependent scope specifier, in which case we 11197 // compute it and do a previous lookup there for a function 11198 // or function template. 11199 } else if (!SS.getScopeRep()->isDependent()) { 11200 DC = computeDeclContext(SS); 11201 if (!DC) return 0; 11202 11203 if (RequireCompleteDeclContext(SS, DC)) return 0; 11204 11205 LookupQualifiedName(Previous, DC); 11206 11207 // Ignore things found implicitly in the wrong scope. 11208 // TODO: better diagnostics for this case. Suggesting the right 11209 // qualified scope would be nice... 11210 LookupResult::Filter F = Previous.makeFilter(); 11211 while (F.hasNext()) { 11212 NamedDecl *D = F.next(); 11213 if (!DC->InEnclosingNamespaceSetOf( 11214 D->getDeclContext()->getRedeclContext())) 11215 F.erase(); 11216 } 11217 F.done(); 11218 11219 if (Previous.empty()) { 11220 D.setInvalidType(); 11221 Diag(Loc, diag::err_qualified_friend_not_found) 11222 << Name << TInfo->getType(); 11223 return 0; 11224 } 11225 11226 // C++ [class.friend]p1: A friend of a class is a function or 11227 // class that is not a member of the class . . . 11228 if (DC->Equals(CurContext)) 11229 Diag(DS.getFriendSpecLoc(), 11230 getLangOpts().CPlusPlus11 ? 11231 diag::warn_cxx98_compat_friend_is_member : 11232 diag::err_friend_is_member); 11233 11234 if (D.isFunctionDefinition()) { 11235 // C++ [class.friend]p6: 11236 // A function can be defined in a friend declaration of a class if and 11237 // only if the class is a non-local class (9.8), the function name is 11238 // unqualified, and the function has namespace scope. 11239 SemaDiagnosticBuilder DB 11240 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11241 11242 DB << SS.getScopeRep(); 11243 if (DC->isFileContext()) 11244 DB << FixItHint::CreateRemoval(SS.getRange()); 11245 SS.clear(); 11246 } 11247 11248 // - There's a scope specifier that does not match any template 11249 // parameter lists, in which case we use some arbitrary context, 11250 // create a method or method template, and wait for instantiation. 11251 // - There's a scope specifier that does match some template 11252 // parameter lists, which we don't handle right now. 11253 } else { 11254 if (D.isFunctionDefinition()) { 11255 // C++ [class.friend]p6: 11256 // A function can be defined in a friend declaration of a class if and 11257 // only if the class is a non-local class (9.8), the function name is 11258 // unqualified, and the function has namespace scope. 11259 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11260 << SS.getScopeRep(); 11261 } 11262 11263 DC = CurContext; 11264 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11265 } 11266 11267 if (!DC->isRecord()) { 11268 // This implies that it has to be an operator or function. 11269 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11270 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11271 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11272 Diag(Loc, diag::err_introducing_special_friend) << 11273 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11274 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11275 return 0; 11276 } 11277 } 11278 11279 // FIXME: This is an egregious hack to cope with cases where the scope stack 11280 // does not contain the declaration context, i.e., in an out-of-line 11281 // definition of a class. 11282 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11283 if (!DCScope) { 11284 FakeDCScope.setEntity(DC); 11285 DCScope = &FakeDCScope; 11286 } 11287 11288 bool AddToScope = true; 11289 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11290 TemplateParams, AddToScope); 11291 if (!ND) return 0; 11292 11293 assert(ND->getDeclContext() == DC); 11294 assert(ND->getLexicalDeclContext() == CurContext); 11295 11296 // Add the function declaration to the appropriate lookup tables, 11297 // adjusting the redeclarations list as necessary. We don't 11298 // want to do this yet if the friending class is dependent. 11299 // 11300 // Also update the scope-based lookup if the target context's 11301 // lookup context is in lexical scope. 11302 if (!CurContext->isDependentContext()) { 11303 DC = DC->getRedeclContext(); 11304 DC->makeDeclVisibleInContext(ND); 11305 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11306 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11307 } 11308 11309 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11310 D.getIdentifierLoc(), ND, 11311 DS.getFriendSpecLoc()); 11312 FrD->setAccess(AS_public); 11313 CurContext->addDecl(FrD); 11314 11315 if (ND->isInvalidDecl()) { 11316 FrD->setInvalidDecl(); 11317 } else { 11318 if (DC->isRecord()) CheckFriendAccess(ND); 11319 11320 FunctionDecl *FD; 11321 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11322 FD = FTD->getTemplatedDecl(); 11323 else 11324 FD = cast<FunctionDecl>(ND); 11325 11326 // Mark templated-scope function declarations as unsupported. 11327 if (FD->getNumTemplateParameterLists()) 11328 FrD->setUnsupportedFriend(true); 11329 } 11330 11331 return ND; 11332} 11333 11334void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11335 AdjustDeclIfTemplate(Dcl); 11336 11337 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11338 if (!Fn) { 11339 Diag(DelLoc, diag::err_deleted_non_function); 11340 return; 11341 } 11342 11343 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11344 // Don't consider the implicit declaration we generate for explicit 11345 // specializations. FIXME: Do not generate these implicit declarations. 11346 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11347 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11348 Diag(DelLoc, diag::err_deleted_decl_not_first); 11349 Diag(Prev->getLocation(), diag::note_previous_declaration); 11350 } 11351 // If the declaration wasn't the first, we delete the function anyway for 11352 // recovery. 11353 Fn = Fn->getCanonicalDecl(); 11354 } 11355 11356 if (Fn->isDeleted()) 11357 return; 11358 11359 // See if we're deleting a function which is already known to override a 11360 // non-deleted virtual function. 11361 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11362 bool IssuedDiagnostic = false; 11363 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11364 E = MD->end_overridden_methods(); 11365 I != E; ++I) { 11366 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11367 if (!IssuedDiagnostic) { 11368 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11369 IssuedDiagnostic = true; 11370 } 11371 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11372 } 11373 } 11374 } 11375 11376 Fn->setDeletedAsWritten(); 11377} 11378 11379void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11380 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11381 11382 if (MD) { 11383 if (MD->getParent()->isDependentType()) { 11384 MD->setDefaulted(); 11385 MD->setExplicitlyDefaulted(); 11386 return; 11387 } 11388 11389 CXXSpecialMember Member = getSpecialMember(MD); 11390 if (Member == CXXInvalid) { 11391 Diag(DefaultLoc, diag::err_default_special_members); 11392 return; 11393 } 11394 11395 MD->setDefaulted(); 11396 MD->setExplicitlyDefaulted(); 11397 11398 // If this definition appears within the record, do the checking when 11399 // the record is complete. 11400 const FunctionDecl *Primary = MD; 11401 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11402 // Find the uninstantiated declaration that actually had the '= default' 11403 // on it. 11404 Pattern->isDefined(Primary); 11405 11406 // If the method was defaulted on its first declaration, we will have 11407 // already performed the checking in CheckCompletedCXXClass. Such a 11408 // declaration doesn't trigger an implicit definition. 11409 if (Primary == Primary->getCanonicalDecl()) 11410 return; 11411 11412 CheckExplicitlyDefaultedSpecialMember(MD); 11413 11414 // The exception specification is needed because we are defining the 11415 // function. 11416 ResolveExceptionSpec(DefaultLoc, 11417 MD->getType()->castAs<FunctionProtoType>()); 11418 11419 switch (Member) { 11420 case CXXDefaultConstructor: { 11421 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11422 if (!CD->isInvalidDecl()) 11423 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11424 break; 11425 } 11426 11427 case CXXCopyConstructor: { 11428 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11429 if (!CD->isInvalidDecl()) 11430 DefineImplicitCopyConstructor(DefaultLoc, CD); 11431 break; 11432 } 11433 11434 case CXXCopyAssignment: { 11435 if (!MD->isInvalidDecl()) 11436 DefineImplicitCopyAssignment(DefaultLoc, MD); 11437 break; 11438 } 11439 11440 case CXXDestructor: { 11441 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11442 if (!DD->isInvalidDecl()) 11443 DefineImplicitDestructor(DefaultLoc, DD); 11444 break; 11445 } 11446 11447 case CXXMoveConstructor: { 11448 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11449 if (!CD->isInvalidDecl()) 11450 DefineImplicitMoveConstructor(DefaultLoc, CD); 11451 break; 11452 } 11453 11454 case CXXMoveAssignment: { 11455 if (!MD->isInvalidDecl()) 11456 DefineImplicitMoveAssignment(DefaultLoc, MD); 11457 break; 11458 } 11459 11460 case CXXInvalid: 11461 llvm_unreachable("Invalid special member."); 11462 } 11463 } else { 11464 Diag(DefaultLoc, diag::err_default_special_members); 11465 } 11466} 11467 11468static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11469 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11470 Stmt *SubStmt = *CI; 11471 if (!SubStmt) 11472 continue; 11473 if (isa<ReturnStmt>(SubStmt)) 11474 Self.Diag(SubStmt->getLocStart(), 11475 diag::err_return_in_constructor_handler); 11476 if (!isa<Expr>(SubStmt)) 11477 SearchForReturnInStmt(Self, SubStmt); 11478 } 11479} 11480 11481void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11482 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11483 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11484 SearchForReturnInStmt(*this, Handler); 11485 } 11486} 11487 11488bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11489 const CXXMethodDecl *Old) { 11490 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11491 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11492 11493 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11494 11495 // If the calling conventions match, everything is fine 11496 if (NewCC == OldCC) 11497 return false; 11498 11499 // If either of the calling conventions are set to "default", we need to pick 11500 // something more sensible based on the target. This supports code where the 11501 // one method explicitly sets thiscall, and another has no explicit calling 11502 // convention. 11503 CallingConv Default = 11504 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11505 if (NewCC == CC_Default) 11506 NewCC = Default; 11507 if (OldCC == CC_Default) 11508 OldCC = Default; 11509 11510 // If the calling conventions still don't match, then report the error 11511 if (NewCC != OldCC) { 11512 Diag(New->getLocation(), 11513 diag::err_conflicting_overriding_cc_attributes) 11514 << New->getDeclName() << New->getType() << Old->getType(); 11515 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11516 return true; 11517 } 11518 11519 return false; 11520} 11521 11522bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11523 const CXXMethodDecl *Old) { 11524 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11525 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11526 11527 if (Context.hasSameType(NewTy, OldTy) || 11528 NewTy->isDependentType() || OldTy->isDependentType()) 11529 return false; 11530 11531 // Check if the return types are covariant 11532 QualType NewClassTy, OldClassTy; 11533 11534 /// Both types must be pointers or references to classes. 11535 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11536 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11537 NewClassTy = NewPT->getPointeeType(); 11538 OldClassTy = OldPT->getPointeeType(); 11539 } 11540 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11541 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11542 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11543 NewClassTy = NewRT->getPointeeType(); 11544 OldClassTy = OldRT->getPointeeType(); 11545 } 11546 } 11547 } 11548 11549 // The return types aren't either both pointers or references to a class type. 11550 if (NewClassTy.isNull()) { 11551 Diag(New->getLocation(), 11552 diag::err_different_return_type_for_overriding_virtual_function) 11553 << New->getDeclName() << NewTy << OldTy; 11554 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11555 11556 return true; 11557 } 11558 11559 // C++ [class.virtual]p6: 11560 // If the return type of D::f differs from the return type of B::f, the 11561 // class type in the return type of D::f shall be complete at the point of 11562 // declaration of D::f or shall be the class type D. 11563 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11564 if (!RT->isBeingDefined() && 11565 RequireCompleteType(New->getLocation(), NewClassTy, 11566 diag::err_covariant_return_incomplete, 11567 New->getDeclName())) 11568 return true; 11569 } 11570 11571 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11572 // Check if the new class derives from the old class. 11573 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11574 Diag(New->getLocation(), 11575 diag::err_covariant_return_not_derived) 11576 << New->getDeclName() << NewTy << OldTy; 11577 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11578 return true; 11579 } 11580 11581 // Check if we the conversion from derived to base is valid. 11582 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11583 diag::err_covariant_return_inaccessible_base, 11584 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11585 // FIXME: Should this point to the return type? 11586 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11587 // FIXME: this note won't trigger for delayed access control 11588 // diagnostics, and it's impossible to get an undelayed error 11589 // here from access control during the original parse because 11590 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11591 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11592 return true; 11593 } 11594 } 11595 11596 // The qualifiers of the return types must be the same. 11597 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11598 Diag(New->getLocation(), 11599 diag::err_covariant_return_type_different_qualifications) 11600 << New->getDeclName() << NewTy << OldTy; 11601 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11602 return true; 11603 }; 11604 11605 11606 // The new class type must have the same or less qualifiers as the old type. 11607 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11608 Diag(New->getLocation(), 11609 diag::err_covariant_return_type_class_type_more_qualified) 11610 << New->getDeclName() << NewTy << OldTy; 11611 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11612 return true; 11613 }; 11614 11615 return false; 11616} 11617 11618/// \brief Mark the given method pure. 11619/// 11620/// \param Method the method to be marked pure. 11621/// 11622/// \param InitRange the source range that covers the "0" initializer. 11623bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11624 SourceLocation EndLoc = InitRange.getEnd(); 11625 if (EndLoc.isValid()) 11626 Method->setRangeEnd(EndLoc); 11627 11628 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11629 Method->setPure(); 11630 return false; 11631 } 11632 11633 if (!Method->isInvalidDecl()) 11634 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11635 << Method->getDeclName() << InitRange; 11636 return true; 11637} 11638 11639/// \brief Determine whether the given declaration is a static data member. 11640static bool isStaticDataMember(Decl *D) { 11641 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11642 if (!Var) 11643 return false; 11644 11645 return Var->isStaticDataMember(); 11646} 11647/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11648/// an initializer for the out-of-line declaration 'Dcl'. The scope 11649/// is a fresh scope pushed for just this purpose. 11650/// 11651/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11652/// static data member of class X, names should be looked up in the scope of 11653/// class X. 11654void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11655 // If there is no declaration, there was an error parsing it. 11656 if (D == 0 || D->isInvalidDecl()) return; 11657 11658 // We should only get called for declarations with scope specifiers, like: 11659 // int foo::bar; 11660 assert(D->isOutOfLine()); 11661 EnterDeclaratorContext(S, D->getDeclContext()); 11662 11663 // If we are parsing the initializer for a static data member, push a 11664 // new expression evaluation context that is associated with this static 11665 // data member. 11666 if (isStaticDataMember(D)) 11667 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11668} 11669 11670/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11671/// initializer for the out-of-line declaration 'D'. 11672void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11673 // If there is no declaration, there was an error parsing it. 11674 if (D == 0 || D->isInvalidDecl()) return; 11675 11676 if (isStaticDataMember(D)) 11677 PopExpressionEvaluationContext(); 11678 11679 assert(D->isOutOfLine()); 11680 ExitDeclaratorContext(S); 11681} 11682 11683/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11684/// C++ if/switch/while/for statement. 11685/// e.g: "if (int x = f()) {...}" 11686DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11687 // C++ 6.4p2: 11688 // The declarator shall not specify a function or an array. 11689 // The type-specifier-seq shall not contain typedef and shall not declare a 11690 // new class or enumeration. 11691 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11692 "Parser allowed 'typedef' as storage class of condition decl."); 11693 11694 Decl *Dcl = ActOnDeclarator(S, D); 11695 if (!Dcl) 11696 return true; 11697 11698 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11699 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11700 << D.getSourceRange(); 11701 return true; 11702 } 11703 11704 return Dcl; 11705} 11706 11707void Sema::LoadExternalVTableUses() { 11708 if (!ExternalSource) 11709 return; 11710 11711 SmallVector<ExternalVTableUse, 4> VTables; 11712 ExternalSource->ReadUsedVTables(VTables); 11713 SmallVector<VTableUse, 4> NewUses; 11714 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11715 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11716 = VTablesUsed.find(VTables[I].Record); 11717 // Even if a definition wasn't required before, it may be required now. 11718 if (Pos != VTablesUsed.end()) { 11719 if (!Pos->second && VTables[I].DefinitionRequired) 11720 Pos->second = true; 11721 continue; 11722 } 11723 11724 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11725 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11726 } 11727 11728 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11729} 11730 11731void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11732 bool DefinitionRequired) { 11733 // Ignore any vtable uses in unevaluated operands or for classes that do 11734 // not have a vtable. 11735 if (!Class->isDynamicClass() || Class->isDependentContext() || 11736 CurContext->isDependentContext() || isUnevaluatedContext()) 11737 return; 11738 11739 // Try to insert this class into the map. 11740 LoadExternalVTableUses(); 11741 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11742 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11743 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11744 if (!Pos.second) { 11745 // If we already had an entry, check to see if we are promoting this vtable 11746 // to required a definition. If so, we need to reappend to the VTableUses 11747 // list, since we may have already processed the first entry. 11748 if (DefinitionRequired && !Pos.first->second) { 11749 Pos.first->second = true; 11750 } else { 11751 // Otherwise, we can early exit. 11752 return; 11753 } 11754 } 11755 11756 // Local classes need to have their virtual members marked 11757 // immediately. For all other classes, we mark their virtual members 11758 // at the end of the translation unit. 11759 if (Class->isLocalClass()) 11760 MarkVirtualMembersReferenced(Loc, Class); 11761 else 11762 VTableUses.push_back(std::make_pair(Class, Loc)); 11763} 11764 11765bool Sema::DefineUsedVTables() { 11766 LoadExternalVTableUses(); 11767 if (VTableUses.empty()) 11768 return false; 11769 11770 // Note: The VTableUses vector could grow as a result of marking 11771 // the members of a class as "used", so we check the size each 11772 // time through the loop and prefer indices (which are stable) to 11773 // iterators (which are not). 11774 bool DefinedAnything = false; 11775 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11776 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11777 if (!Class) 11778 continue; 11779 11780 SourceLocation Loc = VTableUses[I].second; 11781 11782 bool DefineVTable = true; 11783 11784 // If this class has a key function, but that key function is 11785 // defined in another translation unit, we don't need to emit the 11786 // vtable even though we're using it. 11787 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11788 if (KeyFunction && !KeyFunction->hasBody()) { 11789 switch (KeyFunction->getTemplateSpecializationKind()) { 11790 case TSK_Undeclared: 11791 case TSK_ExplicitSpecialization: 11792 case TSK_ExplicitInstantiationDeclaration: 11793 // The key function is in another translation unit. 11794 DefineVTable = false; 11795 break; 11796 11797 case TSK_ExplicitInstantiationDefinition: 11798 case TSK_ImplicitInstantiation: 11799 // We will be instantiating the key function. 11800 break; 11801 } 11802 } else if (!KeyFunction) { 11803 // If we have a class with no key function that is the subject 11804 // of an explicit instantiation declaration, suppress the 11805 // vtable; it will live with the explicit instantiation 11806 // definition. 11807 bool IsExplicitInstantiationDeclaration 11808 = Class->getTemplateSpecializationKind() 11809 == TSK_ExplicitInstantiationDeclaration; 11810 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11811 REnd = Class->redecls_end(); 11812 R != REnd; ++R) { 11813 TemplateSpecializationKind TSK 11814 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11815 if (TSK == TSK_ExplicitInstantiationDeclaration) 11816 IsExplicitInstantiationDeclaration = true; 11817 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11818 IsExplicitInstantiationDeclaration = false; 11819 break; 11820 } 11821 } 11822 11823 if (IsExplicitInstantiationDeclaration) 11824 DefineVTable = false; 11825 } 11826 11827 // The exception specifications for all virtual members may be needed even 11828 // if we are not providing an authoritative form of the vtable in this TU. 11829 // We may choose to emit it available_externally anyway. 11830 if (!DefineVTable) { 11831 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11832 continue; 11833 } 11834 11835 // Mark all of the virtual members of this class as referenced, so 11836 // that we can build a vtable. Then, tell the AST consumer that a 11837 // vtable for this class is required. 11838 DefinedAnything = true; 11839 MarkVirtualMembersReferenced(Loc, Class); 11840 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11841 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11842 11843 // Optionally warn if we're emitting a weak vtable. 11844 if (Class->isExternallyVisible() && 11845 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11846 const FunctionDecl *KeyFunctionDef = 0; 11847 if (!KeyFunction || 11848 (KeyFunction->hasBody(KeyFunctionDef) && 11849 KeyFunctionDef->isInlined())) 11850 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11851 TSK_ExplicitInstantiationDefinition 11852 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11853 << Class; 11854 } 11855 } 11856 VTableUses.clear(); 11857 11858 return DefinedAnything; 11859} 11860 11861void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11862 const CXXRecordDecl *RD) { 11863 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11864 E = RD->method_end(); I != E; ++I) 11865 if ((*I)->isVirtual() && !(*I)->isPure()) 11866 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11867} 11868 11869void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11870 const CXXRecordDecl *RD) { 11871 // Mark all functions which will appear in RD's vtable as used. 11872 CXXFinalOverriderMap FinalOverriders; 11873 RD->getFinalOverriders(FinalOverriders); 11874 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11875 E = FinalOverriders.end(); 11876 I != E; ++I) { 11877 for (OverridingMethods::const_iterator OI = I->second.begin(), 11878 OE = I->second.end(); 11879 OI != OE; ++OI) { 11880 assert(OI->second.size() > 0 && "no final overrider"); 11881 CXXMethodDecl *Overrider = OI->second.front().Method; 11882 11883 // C++ [basic.def.odr]p2: 11884 // [...] A virtual member function is used if it is not pure. [...] 11885 if (!Overrider->isPure()) 11886 MarkFunctionReferenced(Loc, Overrider); 11887 } 11888 } 11889 11890 // Only classes that have virtual bases need a VTT. 11891 if (RD->getNumVBases() == 0) 11892 return; 11893 11894 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11895 e = RD->bases_end(); i != e; ++i) { 11896 const CXXRecordDecl *Base = 11897 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11898 if (Base->getNumVBases() == 0) 11899 continue; 11900 MarkVirtualMembersReferenced(Loc, Base); 11901 } 11902} 11903 11904/// SetIvarInitializers - This routine builds initialization ASTs for the 11905/// Objective-C implementation whose ivars need be initialized. 11906void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11907 if (!getLangOpts().CPlusPlus) 11908 return; 11909 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11910 SmallVector<ObjCIvarDecl*, 8> ivars; 11911 CollectIvarsToConstructOrDestruct(OID, ivars); 11912 if (ivars.empty()) 11913 return; 11914 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11915 for (unsigned i = 0; i < ivars.size(); i++) { 11916 FieldDecl *Field = ivars[i]; 11917 if (Field->isInvalidDecl()) 11918 continue; 11919 11920 CXXCtorInitializer *Member; 11921 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11922 InitializationKind InitKind = 11923 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11924 11925 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 11926 ExprResult MemberInit = 11927 InitSeq.Perform(*this, InitEntity, InitKind, None); 11928 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11929 // Note, MemberInit could actually come back empty if no initialization 11930 // is required (e.g., because it would call a trivial default constructor) 11931 if (!MemberInit.get() || MemberInit.isInvalid()) 11932 continue; 11933 11934 Member = 11935 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11936 SourceLocation(), 11937 MemberInit.takeAs<Expr>(), 11938 SourceLocation()); 11939 AllToInit.push_back(Member); 11940 11941 // Be sure that the destructor is accessible and is marked as referenced. 11942 if (const RecordType *RecordTy 11943 = Context.getBaseElementType(Field->getType()) 11944 ->getAs<RecordType>()) { 11945 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11946 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11947 MarkFunctionReferenced(Field->getLocation(), Destructor); 11948 CheckDestructorAccess(Field->getLocation(), Destructor, 11949 PDiag(diag::err_access_dtor_ivar) 11950 << Context.getBaseElementType(Field->getType())); 11951 } 11952 } 11953 } 11954 ObjCImplementation->setIvarInitializers(Context, 11955 AllToInit.data(), AllToInit.size()); 11956 } 11957} 11958 11959static 11960void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11961 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11962 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11963 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11964 Sema &S) { 11965 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11966 CE = Current.end(); 11967 if (Ctor->isInvalidDecl()) 11968 return; 11969 11970 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11971 11972 // Target may not be determinable yet, for instance if this is a dependent 11973 // call in an uninstantiated template. 11974 if (Target) { 11975 const FunctionDecl *FNTarget = 0; 11976 (void)Target->hasBody(FNTarget); 11977 Target = const_cast<CXXConstructorDecl*>( 11978 cast_or_null<CXXConstructorDecl>(FNTarget)); 11979 } 11980 11981 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11982 // Avoid dereferencing a null pointer here. 11983 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11984 11985 if (!Current.insert(Canonical)) 11986 return; 11987 11988 // We know that beyond here, we aren't chaining into a cycle. 11989 if (!Target || !Target->isDelegatingConstructor() || 11990 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11991 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11992 Valid.insert(*CI); 11993 Current.clear(); 11994 // We've hit a cycle. 11995 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11996 Current.count(TCanonical)) { 11997 // If we haven't diagnosed this cycle yet, do so now. 11998 if (!Invalid.count(TCanonical)) { 11999 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12000 diag::warn_delegating_ctor_cycle) 12001 << Ctor; 12002 12003 // Don't add a note for a function delegating directly to itself. 12004 if (TCanonical != Canonical) 12005 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12006 12007 CXXConstructorDecl *C = Target; 12008 while (C->getCanonicalDecl() != Canonical) { 12009 const FunctionDecl *FNTarget = 0; 12010 (void)C->getTargetConstructor()->hasBody(FNTarget); 12011 assert(FNTarget && "Ctor cycle through bodiless function"); 12012 12013 C = const_cast<CXXConstructorDecl*>( 12014 cast<CXXConstructorDecl>(FNTarget)); 12015 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12016 } 12017 } 12018 12019 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12020 Invalid.insert(*CI); 12021 Current.clear(); 12022 } else { 12023 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12024 } 12025} 12026 12027 12028void Sema::CheckDelegatingCtorCycles() { 12029 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12030 12031 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12032 CE = Current.end(); 12033 12034 for (DelegatingCtorDeclsType::iterator 12035 I = DelegatingCtorDecls.begin(ExternalSource), 12036 E = DelegatingCtorDecls.end(); 12037 I != E; ++I) 12038 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12039 12040 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 12041 (*CI)->setInvalidDecl(); 12042} 12043 12044namespace { 12045 /// \brief AST visitor that finds references to the 'this' expression. 12046 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12047 Sema &S; 12048 12049 public: 12050 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12051 12052 bool VisitCXXThisExpr(CXXThisExpr *E) { 12053 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12054 << E->isImplicit(); 12055 return false; 12056 } 12057 }; 12058} 12059 12060bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12061 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12062 if (!TSInfo) 12063 return false; 12064 12065 TypeLoc TL = TSInfo->getTypeLoc(); 12066 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12067 if (!ProtoTL) 12068 return false; 12069 12070 // C++11 [expr.prim.general]p3: 12071 // [The expression this] shall not appear before the optional 12072 // cv-qualifier-seq and it shall not appear within the declaration of a 12073 // static member function (although its type and value category are defined 12074 // within a static member function as they are within a non-static member 12075 // function). [ Note: this is because declaration matching does not occur 12076 // until the complete declarator is known. - end note ] 12077 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12078 FindCXXThisExpr Finder(*this); 12079 12080 // If the return type came after the cv-qualifier-seq, check it now. 12081 if (Proto->hasTrailingReturn() && 12082 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12083 return true; 12084 12085 // Check the exception specification. 12086 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12087 return true; 12088 12089 return checkThisInStaticMemberFunctionAttributes(Method); 12090} 12091 12092bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12093 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12094 if (!TSInfo) 12095 return false; 12096 12097 TypeLoc TL = TSInfo->getTypeLoc(); 12098 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12099 if (!ProtoTL) 12100 return false; 12101 12102 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12103 FindCXXThisExpr Finder(*this); 12104 12105 switch (Proto->getExceptionSpecType()) { 12106 case EST_Uninstantiated: 12107 case EST_Unevaluated: 12108 case EST_BasicNoexcept: 12109 case EST_DynamicNone: 12110 case EST_MSAny: 12111 case EST_None: 12112 break; 12113 12114 case EST_ComputedNoexcept: 12115 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12116 return true; 12117 12118 case EST_Dynamic: 12119 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12120 EEnd = Proto->exception_end(); 12121 E != EEnd; ++E) { 12122 if (!Finder.TraverseType(*E)) 12123 return true; 12124 } 12125 break; 12126 } 12127 12128 return false; 12129} 12130 12131bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12132 FindCXXThisExpr Finder(*this); 12133 12134 // Check attributes. 12135 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12136 A != AEnd; ++A) { 12137 // FIXME: This should be emitted by tblgen. 12138 Expr *Arg = 0; 12139 ArrayRef<Expr *> Args; 12140 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12141 Arg = G->getArg(); 12142 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12143 Arg = G->getArg(); 12144 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12145 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12146 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12147 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12148 else if (ExclusiveLockFunctionAttr *ELF 12149 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12150 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12151 else if (SharedLockFunctionAttr *SLF 12152 = dyn_cast<SharedLockFunctionAttr>(*A)) 12153 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12154 else if (ExclusiveTrylockFunctionAttr *ETLF 12155 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12156 Arg = ETLF->getSuccessValue(); 12157 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12158 } else if (SharedTrylockFunctionAttr *STLF 12159 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12160 Arg = STLF->getSuccessValue(); 12161 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12162 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12163 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12164 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12165 Arg = LR->getArg(); 12166 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12167 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12168 else if (ExclusiveLocksRequiredAttr *ELR 12169 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12170 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12171 else if (SharedLocksRequiredAttr *SLR 12172 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12173 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12174 12175 if (Arg && !Finder.TraverseStmt(Arg)) 12176 return true; 12177 12178 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12179 if (!Finder.TraverseStmt(Args[I])) 12180 return true; 12181 } 12182 } 12183 12184 return false; 12185} 12186 12187void 12188Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12189 ArrayRef<ParsedType> DynamicExceptions, 12190 ArrayRef<SourceRange> DynamicExceptionRanges, 12191 Expr *NoexceptExpr, 12192 SmallVectorImpl<QualType> &Exceptions, 12193 FunctionProtoType::ExtProtoInfo &EPI) { 12194 Exceptions.clear(); 12195 EPI.ExceptionSpecType = EST; 12196 if (EST == EST_Dynamic) { 12197 Exceptions.reserve(DynamicExceptions.size()); 12198 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12199 // FIXME: Preserve type source info. 12200 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12201 12202 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12203 collectUnexpandedParameterPacks(ET, Unexpanded); 12204 if (!Unexpanded.empty()) { 12205 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12206 UPPC_ExceptionType, 12207 Unexpanded); 12208 continue; 12209 } 12210 12211 // Check that the type is valid for an exception spec, and 12212 // drop it if not. 12213 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12214 Exceptions.push_back(ET); 12215 } 12216 EPI.NumExceptions = Exceptions.size(); 12217 EPI.Exceptions = Exceptions.data(); 12218 return; 12219 } 12220 12221 if (EST == EST_ComputedNoexcept) { 12222 // If an error occurred, there's no expression here. 12223 if (NoexceptExpr) { 12224 assert((NoexceptExpr->isTypeDependent() || 12225 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12226 Context.BoolTy) && 12227 "Parser should have made sure that the expression is boolean"); 12228 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12229 EPI.ExceptionSpecType = EST_BasicNoexcept; 12230 return; 12231 } 12232 12233 if (!NoexceptExpr->isValueDependent()) 12234 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12235 diag::err_noexcept_needs_constant_expression, 12236 /*AllowFold*/ false).take(); 12237 EPI.NoexceptExpr = NoexceptExpr; 12238 } 12239 return; 12240 } 12241} 12242 12243/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12244Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12245 // Implicitly declared functions (e.g. copy constructors) are 12246 // __host__ __device__ 12247 if (D->isImplicit()) 12248 return CFT_HostDevice; 12249 12250 if (D->hasAttr<CUDAGlobalAttr>()) 12251 return CFT_Global; 12252 12253 if (D->hasAttr<CUDADeviceAttr>()) { 12254 if (D->hasAttr<CUDAHostAttr>()) 12255 return CFT_HostDevice; 12256 else 12257 return CFT_Device; 12258 } 12259 12260 return CFT_Host; 12261} 12262 12263bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12264 CUDAFunctionTarget CalleeTarget) { 12265 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12266 // Callable from the device only." 12267 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12268 return true; 12269 12270 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12271 // Callable from the host only." 12272 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12273 // Callable from the host only." 12274 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12275 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12276 return true; 12277 12278 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12279 return true; 12280 12281 return false; 12282} 12283 12284/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12285/// 12286MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12287 SourceLocation DeclStart, 12288 Declarator &D, Expr *BitWidth, 12289 InClassInitStyle InitStyle, 12290 AccessSpecifier AS, 12291 AttributeList *MSPropertyAttr) { 12292 IdentifierInfo *II = D.getIdentifier(); 12293 if (!II) { 12294 Diag(DeclStart, diag::err_anonymous_property); 12295 return NULL; 12296 } 12297 SourceLocation Loc = D.getIdentifierLoc(); 12298 12299 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12300 QualType T = TInfo->getType(); 12301 if (getLangOpts().CPlusPlus) { 12302 CheckExtraCXXDefaultArguments(D); 12303 12304 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12305 UPPC_DataMemberType)) { 12306 D.setInvalidType(); 12307 T = Context.IntTy; 12308 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12309 } 12310 } 12311 12312 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12313 12314 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12315 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12316 diag::err_invalid_thread) 12317 << DeclSpec::getSpecifierName(TSCS); 12318 12319 // Check to see if this name was declared as a member previously 12320 NamedDecl *PrevDecl = 0; 12321 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12322 LookupName(Previous, S); 12323 switch (Previous.getResultKind()) { 12324 case LookupResult::Found: 12325 case LookupResult::FoundUnresolvedValue: 12326 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12327 break; 12328 12329 case LookupResult::FoundOverloaded: 12330 PrevDecl = Previous.getRepresentativeDecl(); 12331 break; 12332 12333 case LookupResult::NotFound: 12334 case LookupResult::NotFoundInCurrentInstantiation: 12335 case LookupResult::Ambiguous: 12336 break; 12337 } 12338 12339 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12340 // Maybe we will complain about the shadowed template parameter. 12341 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12342 // Just pretend that we didn't see the previous declaration. 12343 PrevDecl = 0; 12344 } 12345 12346 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12347 PrevDecl = 0; 12348 12349 SourceLocation TSSL = D.getLocStart(); 12350 MSPropertyDecl *NewPD; 12351 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12352 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12353 II, T, TInfo, TSSL, 12354 Data.GetterId, Data.SetterId); 12355 ProcessDeclAttributes(TUScope, NewPD, D); 12356 NewPD->setAccess(AS); 12357 12358 if (NewPD->isInvalidDecl()) 12359 Record->setInvalidDecl(); 12360 12361 if (D.getDeclSpec().isModulePrivateSpecified()) 12362 NewPD->setModulePrivate(); 12363 12364 if (NewPD->isInvalidDecl() && PrevDecl) { 12365 // Don't introduce NewFD into scope; there's already something 12366 // with the same name in the same scope. 12367 } else if (II) { 12368 PushOnScopeChains(NewPD, S); 12369 } else 12370 Record->addDecl(NewPD); 12371 12372 return NewPD; 12373} 12374