SemaDeclCXX.cpp revision bebf5b1bcfbf591dd3cd80c4aebd6486bb34f41c
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, 1); 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 Expr **Inits = &InitExpr; 2161 unsigned NumInits = 1; 2162 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2163 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2164 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2165 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2166 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 2167 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 2168 if (Init.isInvalid()) { 2169 FD->setInvalidDecl(); 2170 return; 2171 } 2172 } 2173 2174 // C++11 [class.base.init]p7: 2175 // The initialization of each base and member constitutes a 2176 // full-expression. 2177 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2178 if (Init.isInvalid()) { 2179 FD->setInvalidDecl(); 2180 return; 2181 } 2182 2183 InitExpr = Init.release(); 2184 2185 FD->setInClassInitializer(InitExpr); 2186} 2187 2188/// \brief Find the direct and/or virtual base specifiers that 2189/// correspond to the given base type, for use in base initialization 2190/// within a constructor. 2191static bool FindBaseInitializer(Sema &SemaRef, 2192 CXXRecordDecl *ClassDecl, 2193 QualType BaseType, 2194 const CXXBaseSpecifier *&DirectBaseSpec, 2195 const CXXBaseSpecifier *&VirtualBaseSpec) { 2196 // First, check for a direct base class. 2197 DirectBaseSpec = 0; 2198 for (CXXRecordDecl::base_class_const_iterator Base 2199 = ClassDecl->bases_begin(); 2200 Base != ClassDecl->bases_end(); ++Base) { 2201 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2202 // We found a direct base of this type. That's what we're 2203 // initializing. 2204 DirectBaseSpec = &*Base; 2205 break; 2206 } 2207 } 2208 2209 // Check for a virtual base class. 2210 // FIXME: We might be able to short-circuit this if we know in advance that 2211 // there are no virtual bases. 2212 VirtualBaseSpec = 0; 2213 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2214 // We haven't found a base yet; search the class hierarchy for a 2215 // virtual base class. 2216 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2217 /*DetectVirtual=*/false); 2218 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2219 BaseType, Paths)) { 2220 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2221 Path != Paths.end(); ++Path) { 2222 if (Path->back().Base->isVirtual()) { 2223 VirtualBaseSpec = Path->back().Base; 2224 break; 2225 } 2226 } 2227 } 2228 } 2229 2230 return DirectBaseSpec || VirtualBaseSpec; 2231} 2232 2233/// \brief Handle a C++ member initializer using braced-init-list syntax. 2234MemInitResult 2235Sema::ActOnMemInitializer(Decl *ConstructorD, 2236 Scope *S, 2237 CXXScopeSpec &SS, 2238 IdentifierInfo *MemberOrBase, 2239 ParsedType TemplateTypeTy, 2240 const DeclSpec &DS, 2241 SourceLocation IdLoc, 2242 Expr *InitList, 2243 SourceLocation EllipsisLoc) { 2244 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2245 DS, IdLoc, InitList, 2246 EllipsisLoc); 2247} 2248 2249/// \brief Handle a C++ member initializer using parentheses syntax. 2250MemInitResult 2251Sema::ActOnMemInitializer(Decl *ConstructorD, 2252 Scope *S, 2253 CXXScopeSpec &SS, 2254 IdentifierInfo *MemberOrBase, 2255 ParsedType TemplateTypeTy, 2256 const DeclSpec &DS, 2257 SourceLocation IdLoc, 2258 SourceLocation LParenLoc, 2259 Expr **Args, unsigned NumArgs, 2260 SourceLocation RParenLoc, 2261 SourceLocation EllipsisLoc) { 2262 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2263 llvm::makeArrayRef(Args, NumArgs), 2264 RParenLoc); 2265 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2266 DS, IdLoc, List, EllipsisLoc); 2267} 2268 2269namespace { 2270 2271// Callback to only accept typo corrections that can be a valid C++ member 2272// intializer: either a non-static field member or a base class. 2273class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2274 public: 2275 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2276 : ClassDecl(ClassDecl) {} 2277 2278 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2279 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2280 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2281 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2282 else 2283 return isa<TypeDecl>(ND); 2284 } 2285 return false; 2286 } 2287 2288 private: 2289 CXXRecordDecl *ClassDecl; 2290}; 2291 2292} 2293 2294/// \brief Handle a C++ member initializer. 2295MemInitResult 2296Sema::BuildMemInitializer(Decl *ConstructorD, 2297 Scope *S, 2298 CXXScopeSpec &SS, 2299 IdentifierInfo *MemberOrBase, 2300 ParsedType TemplateTypeTy, 2301 const DeclSpec &DS, 2302 SourceLocation IdLoc, 2303 Expr *Init, 2304 SourceLocation EllipsisLoc) { 2305 if (!ConstructorD) 2306 return true; 2307 2308 AdjustDeclIfTemplate(ConstructorD); 2309 2310 CXXConstructorDecl *Constructor 2311 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2312 if (!Constructor) { 2313 // The user wrote a constructor initializer on a function that is 2314 // not a C++ constructor. Ignore the error for now, because we may 2315 // have more member initializers coming; we'll diagnose it just 2316 // once in ActOnMemInitializers. 2317 return true; 2318 } 2319 2320 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2321 2322 // C++ [class.base.init]p2: 2323 // Names in a mem-initializer-id are looked up in the scope of the 2324 // constructor's class and, if not found in that scope, are looked 2325 // up in the scope containing the constructor's definition. 2326 // [Note: if the constructor's class contains a member with the 2327 // same name as a direct or virtual base class of the class, a 2328 // mem-initializer-id naming the member or base class and composed 2329 // of a single identifier refers to the class member. A 2330 // mem-initializer-id for the hidden base class may be specified 2331 // using a qualified name. ] 2332 if (!SS.getScopeRep() && !TemplateTypeTy) { 2333 // Look for a member, first. 2334 DeclContext::lookup_result Result 2335 = ClassDecl->lookup(MemberOrBase); 2336 if (!Result.empty()) { 2337 ValueDecl *Member; 2338 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2339 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2340 if (EllipsisLoc.isValid()) 2341 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2342 << MemberOrBase 2343 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2344 2345 return BuildMemberInitializer(Member, Init, IdLoc); 2346 } 2347 } 2348 } 2349 // It didn't name a member, so see if it names a class. 2350 QualType BaseType; 2351 TypeSourceInfo *TInfo = 0; 2352 2353 if (TemplateTypeTy) { 2354 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2355 } else if (DS.getTypeSpecType() == TST_decltype) { 2356 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2357 } else { 2358 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2359 LookupParsedName(R, S, &SS); 2360 2361 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2362 if (!TyD) { 2363 if (R.isAmbiguous()) return true; 2364 2365 // We don't want access-control diagnostics here. 2366 R.suppressDiagnostics(); 2367 2368 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2369 bool NotUnknownSpecialization = false; 2370 DeclContext *DC = computeDeclContext(SS, false); 2371 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2372 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2373 2374 if (!NotUnknownSpecialization) { 2375 // When the scope specifier can refer to a member of an unknown 2376 // specialization, we take it as a type name. 2377 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2378 SS.getWithLocInContext(Context), 2379 *MemberOrBase, IdLoc); 2380 if (BaseType.isNull()) 2381 return true; 2382 2383 R.clear(); 2384 R.setLookupName(MemberOrBase); 2385 } 2386 } 2387 2388 // If no results were found, try to correct typos. 2389 TypoCorrection Corr; 2390 MemInitializerValidatorCCC Validator(ClassDecl); 2391 if (R.empty() && BaseType.isNull() && 2392 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2393 Validator, ClassDecl))) { 2394 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2395 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2396 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2397 // We have found a non-static data member with a similar 2398 // name to what was typed; complain and initialize that 2399 // member. 2400 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2401 << MemberOrBase << true << CorrectedQuotedStr 2402 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2403 Diag(Member->getLocation(), diag::note_previous_decl) 2404 << CorrectedQuotedStr; 2405 2406 return BuildMemberInitializer(Member, Init, IdLoc); 2407 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2408 const CXXBaseSpecifier *DirectBaseSpec; 2409 const CXXBaseSpecifier *VirtualBaseSpec; 2410 if (FindBaseInitializer(*this, ClassDecl, 2411 Context.getTypeDeclType(Type), 2412 DirectBaseSpec, VirtualBaseSpec)) { 2413 // We have found a direct or virtual base class with a 2414 // similar name to what was typed; complain and initialize 2415 // that base class. 2416 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2417 << MemberOrBase << false << CorrectedQuotedStr 2418 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2419 2420 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2421 : VirtualBaseSpec; 2422 Diag(BaseSpec->getLocStart(), 2423 diag::note_base_class_specified_here) 2424 << BaseSpec->getType() 2425 << BaseSpec->getSourceRange(); 2426 2427 TyD = Type; 2428 } 2429 } 2430 } 2431 2432 if (!TyD && BaseType.isNull()) { 2433 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2434 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2435 return true; 2436 } 2437 } 2438 2439 if (BaseType.isNull()) { 2440 BaseType = Context.getTypeDeclType(TyD); 2441 if (SS.isSet()) { 2442 NestedNameSpecifier *Qualifier = 2443 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2444 2445 // FIXME: preserve source range information 2446 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2447 } 2448 } 2449 } 2450 2451 if (!TInfo) 2452 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2453 2454 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2455} 2456 2457/// Checks a member initializer expression for cases where reference (or 2458/// pointer) members are bound to by-value parameters (or their addresses). 2459static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2460 Expr *Init, 2461 SourceLocation IdLoc) { 2462 QualType MemberTy = Member->getType(); 2463 2464 // We only handle pointers and references currently. 2465 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2466 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2467 return; 2468 2469 const bool IsPointer = MemberTy->isPointerType(); 2470 if (IsPointer) { 2471 if (const UnaryOperator *Op 2472 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2473 // The only case we're worried about with pointers requires taking the 2474 // address. 2475 if (Op->getOpcode() != UO_AddrOf) 2476 return; 2477 2478 Init = Op->getSubExpr(); 2479 } else { 2480 // We only handle address-of expression initializers for pointers. 2481 return; 2482 } 2483 } 2484 2485 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2486 // Taking the address of a temporary will be diagnosed as a hard error. 2487 if (IsPointer) 2488 return; 2489 2490 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2491 << Member << Init->getSourceRange(); 2492 } else if (const DeclRefExpr *DRE 2493 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2494 // We only warn when referring to a non-reference parameter declaration. 2495 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2496 if (!Parameter || Parameter->getType()->isReferenceType()) 2497 return; 2498 2499 S.Diag(Init->getExprLoc(), 2500 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2501 : diag::warn_bind_ref_member_to_parameter) 2502 << Member << Parameter << Init->getSourceRange(); 2503 } else { 2504 // Other initializers are fine. 2505 return; 2506 } 2507 2508 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2509 << (unsigned)IsPointer; 2510} 2511 2512MemInitResult 2513Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2514 SourceLocation IdLoc) { 2515 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2516 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2517 assert((DirectMember || IndirectMember) && 2518 "Member must be a FieldDecl or IndirectFieldDecl"); 2519 2520 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2521 return true; 2522 2523 if (Member->isInvalidDecl()) 2524 return true; 2525 2526 // Diagnose value-uses of fields to initialize themselves, e.g. 2527 // foo(foo) 2528 // where foo is not also a parameter to the constructor. 2529 // TODO: implement -Wuninitialized and fold this into that framework. 2530 Expr **Args; 2531 unsigned NumArgs; 2532 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2533 Args = ParenList->getExprs(); 2534 NumArgs = ParenList->getNumExprs(); 2535 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2536 Args = InitList->getInits(); 2537 NumArgs = InitList->getNumInits(); 2538 } else { 2539 // Template instantiation doesn't reconstruct ParenListExprs for us. 2540 Args = &Init; 2541 NumArgs = 1; 2542 } 2543 2544 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2545 != DiagnosticsEngine::Ignored) 2546 for (unsigned i = 0; i < NumArgs; ++i) 2547 // FIXME: Warn about the case when other fields are used before being 2548 // initialized. For example, let this field be the i'th field. When 2549 // initializing the i'th field, throw a warning if any of the >= i'th 2550 // fields are used, as they are not yet initialized. 2551 // Right now we are only handling the case where the i'th field uses 2552 // itself in its initializer. 2553 // Also need to take into account that some fields may be initialized by 2554 // in-class initializers, see C++11 [class.base.init]p9. 2555 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2556 2557 SourceRange InitRange = Init->getSourceRange(); 2558 2559 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2560 // Can't check initialization for a member of dependent type or when 2561 // any of the arguments are type-dependent expressions. 2562 DiscardCleanupsInEvaluationContext(); 2563 } else { 2564 bool InitList = false; 2565 if (isa<InitListExpr>(Init)) { 2566 InitList = true; 2567 Args = &Init; 2568 NumArgs = 1; 2569 2570 if (isStdInitializerList(Member->getType(), 0)) { 2571 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2572 << /*at end of ctor*/1 << InitRange; 2573 } 2574 } 2575 2576 // Initialize the member. 2577 InitializedEntity MemberEntity = 2578 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2579 : InitializedEntity::InitializeMember(IndirectMember, 0); 2580 InitializationKind Kind = 2581 InitList ? InitializationKind::CreateDirectList(IdLoc) 2582 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2583 InitRange.getEnd()); 2584 2585 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2586 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2587 MultiExprArg(Args, NumArgs), 2588 0); 2589 if (MemberInit.isInvalid()) 2590 return true; 2591 2592 // C++11 [class.base.init]p7: 2593 // The initialization of each base and member constitutes a 2594 // full-expression. 2595 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2596 if (MemberInit.isInvalid()) 2597 return true; 2598 2599 Init = MemberInit.get(); 2600 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2601 } 2602 2603 if (DirectMember) { 2604 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2605 InitRange.getBegin(), Init, 2606 InitRange.getEnd()); 2607 } else { 2608 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2609 InitRange.getBegin(), Init, 2610 InitRange.getEnd()); 2611 } 2612} 2613 2614MemInitResult 2615Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2616 CXXRecordDecl *ClassDecl) { 2617 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2618 if (!LangOpts.CPlusPlus11) 2619 return Diag(NameLoc, diag::err_delegating_ctor) 2620 << TInfo->getTypeLoc().getLocalSourceRange(); 2621 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2622 2623 bool InitList = true; 2624 Expr **Args = &Init; 2625 unsigned NumArgs = 1; 2626 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2627 InitList = false; 2628 Args = ParenList->getExprs(); 2629 NumArgs = ParenList->getNumExprs(); 2630 } 2631 2632 SourceRange InitRange = Init->getSourceRange(); 2633 // Initialize the object. 2634 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2635 QualType(ClassDecl->getTypeForDecl(), 0)); 2636 InitializationKind Kind = 2637 InitList ? InitializationKind::CreateDirectList(NameLoc) 2638 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2639 InitRange.getEnd()); 2640 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2641 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2642 MultiExprArg(Args, NumArgs), 2643 0); 2644 if (DelegationInit.isInvalid()) 2645 return true; 2646 2647 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2648 "Delegating constructor with no target?"); 2649 2650 // C++11 [class.base.init]p7: 2651 // The initialization of each base and member constitutes a 2652 // full-expression. 2653 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2654 InitRange.getBegin()); 2655 if (DelegationInit.isInvalid()) 2656 return true; 2657 2658 // If we are in a dependent context, template instantiation will 2659 // perform this type-checking again. Just save the arguments that we 2660 // received in a ParenListExpr. 2661 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2662 // of the information that we have about the base 2663 // initializer. However, deconstructing the ASTs is a dicey process, 2664 // and this approach is far more likely to get the corner cases right. 2665 if (CurContext->isDependentContext()) 2666 DelegationInit = Owned(Init); 2667 2668 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2669 DelegationInit.takeAs<Expr>(), 2670 InitRange.getEnd()); 2671} 2672 2673MemInitResult 2674Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2675 Expr *Init, CXXRecordDecl *ClassDecl, 2676 SourceLocation EllipsisLoc) { 2677 SourceLocation BaseLoc 2678 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2679 2680 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2681 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2682 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2683 2684 // C++ [class.base.init]p2: 2685 // [...] Unless the mem-initializer-id names a nonstatic data 2686 // member of the constructor's class or a direct or virtual base 2687 // of that class, the mem-initializer is ill-formed. A 2688 // mem-initializer-list can initialize a base class using any 2689 // name that denotes that base class type. 2690 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2691 2692 SourceRange InitRange = Init->getSourceRange(); 2693 if (EllipsisLoc.isValid()) { 2694 // This is a pack expansion. 2695 if (!BaseType->containsUnexpandedParameterPack()) { 2696 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2697 << SourceRange(BaseLoc, InitRange.getEnd()); 2698 2699 EllipsisLoc = SourceLocation(); 2700 } 2701 } else { 2702 // Check for any unexpanded parameter packs. 2703 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2704 return true; 2705 2706 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2707 return true; 2708 } 2709 2710 // Check for direct and virtual base classes. 2711 const CXXBaseSpecifier *DirectBaseSpec = 0; 2712 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2713 if (!Dependent) { 2714 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2715 BaseType)) 2716 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2717 2718 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2719 VirtualBaseSpec); 2720 2721 // C++ [base.class.init]p2: 2722 // Unless the mem-initializer-id names a nonstatic data member of the 2723 // constructor's class or a direct or virtual base of that class, the 2724 // mem-initializer is ill-formed. 2725 if (!DirectBaseSpec && !VirtualBaseSpec) { 2726 // If the class has any dependent bases, then it's possible that 2727 // one of those types will resolve to the same type as 2728 // BaseType. Therefore, just treat this as a dependent base 2729 // class initialization. FIXME: Should we try to check the 2730 // initialization anyway? It seems odd. 2731 if (ClassDecl->hasAnyDependentBases()) 2732 Dependent = true; 2733 else 2734 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2735 << BaseType << Context.getTypeDeclType(ClassDecl) 2736 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2737 } 2738 } 2739 2740 if (Dependent) { 2741 DiscardCleanupsInEvaluationContext(); 2742 2743 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2744 /*IsVirtual=*/false, 2745 InitRange.getBegin(), Init, 2746 InitRange.getEnd(), EllipsisLoc); 2747 } 2748 2749 // C++ [base.class.init]p2: 2750 // If a mem-initializer-id is ambiguous because it designates both 2751 // a direct non-virtual base class and an inherited virtual base 2752 // class, the mem-initializer is ill-formed. 2753 if (DirectBaseSpec && VirtualBaseSpec) 2754 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2755 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2756 2757 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2758 if (!BaseSpec) 2759 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2760 2761 // Initialize the base. 2762 bool InitList = true; 2763 Expr **Args = &Init; 2764 unsigned NumArgs = 1; 2765 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2766 InitList = false; 2767 Args = ParenList->getExprs(); 2768 NumArgs = ParenList->getNumExprs(); 2769 } 2770 2771 InitializedEntity BaseEntity = 2772 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2773 InitializationKind Kind = 2774 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2775 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2776 InitRange.getEnd()); 2777 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2778 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2779 MultiExprArg(Args, NumArgs), 0); 2780 if (BaseInit.isInvalid()) 2781 return true; 2782 2783 // C++11 [class.base.init]p7: 2784 // The initialization of each base and member constitutes a 2785 // full-expression. 2786 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2787 if (BaseInit.isInvalid()) 2788 return true; 2789 2790 // If we are in a dependent context, template instantiation will 2791 // perform this type-checking again. Just save the arguments that we 2792 // received in a ParenListExpr. 2793 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2794 // of the information that we have about the base 2795 // initializer. However, deconstructing the ASTs is a dicey process, 2796 // and this approach is far more likely to get the corner cases right. 2797 if (CurContext->isDependentContext()) 2798 BaseInit = Owned(Init); 2799 2800 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2801 BaseSpec->isVirtual(), 2802 InitRange.getBegin(), 2803 BaseInit.takeAs<Expr>(), 2804 InitRange.getEnd(), EllipsisLoc); 2805} 2806 2807// Create a static_cast\<T&&>(expr). 2808static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2809 if (T.isNull()) T = E->getType(); 2810 QualType TargetType = SemaRef.BuildReferenceType( 2811 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2812 SourceLocation ExprLoc = E->getLocStart(); 2813 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2814 TargetType, ExprLoc); 2815 2816 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2817 SourceRange(ExprLoc, ExprLoc), 2818 E->getSourceRange()).take(); 2819} 2820 2821/// ImplicitInitializerKind - How an implicit base or member initializer should 2822/// initialize its base or member. 2823enum ImplicitInitializerKind { 2824 IIK_Default, 2825 IIK_Copy, 2826 IIK_Move, 2827 IIK_Inherit 2828}; 2829 2830static bool 2831BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2832 ImplicitInitializerKind ImplicitInitKind, 2833 CXXBaseSpecifier *BaseSpec, 2834 bool IsInheritedVirtualBase, 2835 CXXCtorInitializer *&CXXBaseInit) { 2836 InitializedEntity InitEntity 2837 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2838 IsInheritedVirtualBase); 2839 2840 ExprResult BaseInit; 2841 2842 switch (ImplicitInitKind) { 2843 case IIK_Inherit: { 2844 const CXXRecordDecl *Inherited = 2845 Constructor->getInheritedConstructor()->getParent(); 2846 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2847 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2848 // C++11 [class.inhctor]p8: 2849 // Each expression in the expression-list is of the form 2850 // static_cast<T&&>(p), where p is the name of the corresponding 2851 // constructor parameter and T is the declared type of p. 2852 SmallVector<Expr*, 16> Args; 2853 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2854 ParmVarDecl *PD = Constructor->getParamDecl(I); 2855 ExprResult ArgExpr = 2856 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2857 VK_LValue, SourceLocation()); 2858 if (ArgExpr.isInvalid()) 2859 return true; 2860 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2861 } 2862 2863 InitializationKind InitKind = InitializationKind::CreateDirect( 2864 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2865 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2866 Args.data(), Args.size()); 2867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2868 break; 2869 } 2870 } 2871 // Fall through. 2872 case IIK_Default: { 2873 InitializationKind InitKind 2874 = InitializationKind::CreateDefault(Constructor->getLocation()); 2875 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2876 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2877 break; 2878 } 2879 2880 case IIK_Move: 2881 case IIK_Copy: { 2882 bool Moving = ImplicitInitKind == IIK_Move; 2883 ParmVarDecl *Param = Constructor->getParamDecl(0); 2884 QualType ParamType = Param->getType().getNonReferenceType(); 2885 2886 Expr *CopyCtorArg = 2887 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2888 SourceLocation(), Param, false, 2889 Constructor->getLocation(), ParamType, 2890 VK_LValue, 0); 2891 2892 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2893 2894 // Cast to the base class to avoid ambiguities. 2895 QualType ArgTy = 2896 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2897 ParamType.getQualifiers()); 2898 2899 if (Moving) { 2900 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2901 } 2902 2903 CXXCastPath BasePath; 2904 BasePath.push_back(BaseSpec); 2905 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2906 CK_UncheckedDerivedToBase, 2907 Moving ? VK_XValue : VK_LValue, 2908 &BasePath).take(); 2909 2910 InitializationKind InitKind 2911 = InitializationKind::CreateDirect(Constructor->getLocation(), 2912 SourceLocation(), SourceLocation()); 2913 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2914 &CopyCtorArg, 1); 2915 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2916 MultiExprArg(&CopyCtorArg, 1)); 2917 break; 2918 } 2919 } 2920 2921 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2922 if (BaseInit.isInvalid()) 2923 return true; 2924 2925 CXXBaseInit = 2926 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2927 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2928 SourceLocation()), 2929 BaseSpec->isVirtual(), 2930 SourceLocation(), 2931 BaseInit.takeAs<Expr>(), 2932 SourceLocation(), 2933 SourceLocation()); 2934 2935 return false; 2936} 2937 2938static bool RefersToRValueRef(Expr *MemRef) { 2939 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2940 return Referenced->getType()->isRValueReferenceType(); 2941} 2942 2943static bool 2944BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2945 ImplicitInitializerKind ImplicitInitKind, 2946 FieldDecl *Field, IndirectFieldDecl *Indirect, 2947 CXXCtorInitializer *&CXXMemberInit) { 2948 if (Field->isInvalidDecl()) 2949 return true; 2950 2951 SourceLocation Loc = Constructor->getLocation(); 2952 2953 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2954 bool Moving = ImplicitInitKind == IIK_Move; 2955 ParmVarDecl *Param = Constructor->getParamDecl(0); 2956 QualType ParamType = Param->getType().getNonReferenceType(); 2957 2958 // Suppress copying zero-width bitfields. 2959 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2960 return false; 2961 2962 Expr *MemberExprBase = 2963 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2964 SourceLocation(), Param, false, 2965 Loc, ParamType, VK_LValue, 0); 2966 2967 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2968 2969 if (Moving) { 2970 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2971 } 2972 2973 // Build a reference to this field within the parameter. 2974 CXXScopeSpec SS; 2975 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2976 Sema::LookupMemberName); 2977 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2978 : cast<ValueDecl>(Field), AS_public); 2979 MemberLookup.resolveKind(); 2980 ExprResult CtorArg 2981 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2982 ParamType, Loc, 2983 /*IsArrow=*/false, 2984 SS, 2985 /*TemplateKWLoc=*/SourceLocation(), 2986 /*FirstQualifierInScope=*/0, 2987 MemberLookup, 2988 /*TemplateArgs=*/0); 2989 if (CtorArg.isInvalid()) 2990 return true; 2991 2992 // C++11 [class.copy]p15: 2993 // - if a member m has rvalue reference type T&&, it is direct-initialized 2994 // with static_cast<T&&>(x.m); 2995 if (RefersToRValueRef(CtorArg.get())) { 2996 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2997 } 2998 2999 // When the field we are copying is an array, create index variables for 3000 // each dimension of the array. We use these index variables to subscript 3001 // the source array, and other clients (e.g., CodeGen) will perform the 3002 // necessary iteration with these index variables. 3003 SmallVector<VarDecl *, 4> IndexVariables; 3004 QualType BaseType = Field->getType(); 3005 QualType SizeType = SemaRef.Context.getSizeType(); 3006 bool InitializingArray = false; 3007 while (const ConstantArrayType *Array 3008 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3009 InitializingArray = true; 3010 // Create the iteration variable for this array index. 3011 IdentifierInfo *IterationVarName = 0; 3012 { 3013 SmallString<8> Str; 3014 llvm::raw_svector_ostream OS(Str); 3015 OS << "__i" << IndexVariables.size(); 3016 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3017 } 3018 VarDecl *IterationVar 3019 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3020 IterationVarName, SizeType, 3021 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3022 SC_None); 3023 IndexVariables.push_back(IterationVar); 3024 3025 // Create a reference to the iteration variable. 3026 ExprResult IterationVarRef 3027 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3028 assert(!IterationVarRef.isInvalid() && 3029 "Reference to invented variable cannot fail!"); 3030 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3031 assert(!IterationVarRef.isInvalid() && 3032 "Conversion of invented variable cannot fail!"); 3033 3034 // Subscript the array with this iteration variable. 3035 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3036 IterationVarRef.take(), 3037 Loc); 3038 if (CtorArg.isInvalid()) 3039 return true; 3040 3041 BaseType = Array->getElementType(); 3042 } 3043 3044 // The array subscript expression is an lvalue, which is wrong for moving. 3045 if (Moving && InitializingArray) 3046 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3047 3048 // Construct the entity that we will be initializing. For an array, this 3049 // will be first element in the array, which may require several levels 3050 // of array-subscript entities. 3051 SmallVector<InitializedEntity, 4> Entities; 3052 Entities.reserve(1 + IndexVariables.size()); 3053 if (Indirect) 3054 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3055 else 3056 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3057 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3058 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3059 0, 3060 Entities.back())); 3061 3062 // Direct-initialize to use the copy constructor. 3063 InitializationKind InitKind = 3064 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3065 3066 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3067 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 3068 &CtorArgE, 1); 3069 3070 ExprResult MemberInit 3071 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3072 MultiExprArg(&CtorArgE, 1)); 3073 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3074 if (MemberInit.isInvalid()) 3075 return true; 3076 3077 if (Indirect) { 3078 assert(IndexVariables.size() == 0 && 3079 "Indirect field improperly initialized"); 3080 CXXMemberInit 3081 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3082 Loc, Loc, 3083 MemberInit.takeAs<Expr>(), 3084 Loc); 3085 } else 3086 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3087 Loc, MemberInit.takeAs<Expr>(), 3088 Loc, 3089 IndexVariables.data(), 3090 IndexVariables.size()); 3091 return false; 3092 } 3093 3094 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3095 "Unhandled implicit init kind!"); 3096 3097 QualType FieldBaseElementType = 3098 SemaRef.Context.getBaseElementType(Field->getType()); 3099 3100 if (FieldBaseElementType->isRecordType()) { 3101 InitializedEntity InitEntity 3102 = Indirect? InitializedEntity::InitializeMember(Indirect) 3103 : InitializedEntity::InitializeMember(Field); 3104 InitializationKind InitKind = 3105 InitializationKind::CreateDefault(Loc); 3106 3107 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 3108 ExprResult MemberInit = 3109 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 3110 3111 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3112 if (MemberInit.isInvalid()) 3113 return true; 3114 3115 if (Indirect) 3116 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3117 Indirect, Loc, 3118 Loc, 3119 MemberInit.get(), 3120 Loc); 3121 else 3122 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3123 Field, Loc, Loc, 3124 MemberInit.get(), 3125 Loc); 3126 return false; 3127 } 3128 3129 if (!Field->getParent()->isUnion()) { 3130 if (FieldBaseElementType->isReferenceType()) { 3131 SemaRef.Diag(Constructor->getLocation(), 3132 diag::err_uninitialized_member_in_ctor) 3133 << (int)Constructor->isImplicit() 3134 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3135 << 0 << Field->getDeclName(); 3136 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3137 return true; 3138 } 3139 3140 if (FieldBaseElementType.isConstQualified()) { 3141 SemaRef.Diag(Constructor->getLocation(), 3142 diag::err_uninitialized_member_in_ctor) 3143 << (int)Constructor->isImplicit() 3144 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3145 << 1 << Field->getDeclName(); 3146 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3147 return true; 3148 } 3149 } 3150 3151 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3152 FieldBaseElementType->isObjCRetainableType() && 3153 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3154 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3155 // ARC: 3156 // Default-initialize Objective-C pointers to NULL. 3157 CXXMemberInit 3158 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3159 Loc, Loc, 3160 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3161 Loc); 3162 return false; 3163 } 3164 3165 // Nothing to initialize. 3166 CXXMemberInit = 0; 3167 return false; 3168} 3169 3170namespace { 3171struct BaseAndFieldInfo { 3172 Sema &S; 3173 CXXConstructorDecl *Ctor; 3174 bool AnyErrorsInInits; 3175 ImplicitInitializerKind IIK; 3176 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3177 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3178 3179 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3180 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3181 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3182 if (Generated && Ctor->isCopyConstructor()) 3183 IIK = IIK_Copy; 3184 else if (Generated && Ctor->isMoveConstructor()) 3185 IIK = IIK_Move; 3186 else if (Ctor->getInheritedConstructor()) 3187 IIK = IIK_Inherit; 3188 else 3189 IIK = IIK_Default; 3190 } 3191 3192 bool isImplicitCopyOrMove() const { 3193 switch (IIK) { 3194 case IIK_Copy: 3195 case IIK_Move: 3196 return true; 3197 3198 case IIK_Default: 3199 case IIK_Inherit: 3200 return false; 3201 } 3202 3203 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3204 } 3205 3206 bool addFieldInitializer(CXXCtorInitializer *Init) { 3207 AllToInit.push_back(Init); 3208 3209 // Check whether this initializer makes the field "used". 3210 if (Init->getInit()->HasSideEffects(S.Context)) 3211 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3212 3213 return false; 3214 } 3215}; 3216} 3217 3218/// \brief Determine whether the given indirect field declaration is somewhere 3219/// within an anonymous union. 3220static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3221 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3222 CEnd = F->chain_end(); 3223 C != CEnd; ++C) 3224 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3225 if (Record->isUnion()) 3226 return true; 3227 3228 return false; 3229} 3230 3231/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3232/// array type. 3233static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3234 if (T->isIncompleteArrayType()) 3235 return true; 3236 3237 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3238 if (!ArrayT->getSize()) 3239 return true; 3240 3241 T = ArrayT->getElementType(); 3242 } 3243 3244 return false; 3245} 3246 3247static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3248 FieldDecl *Field, 3249 IndirectFieldDecl *Indirect = 0) { 3250 3251 // Overwhelmingly common case: we have a direct initializer for this field. 3252 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3253 return Info.addFieldInitializer(Init); 3254 3255 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3256 // has a brace-or-equal-initializer, the entity is initialized as specified 3257 // in [dcl.init]. 3258 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3259 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3260 Info.Ctor->getLocation(), Field); 3261 CXXCtorInitializer *Init; 3262 if (Indirect) 3263 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3264 SourceLocation(), 3265 SourceLocation(), DIE, 3266 SourceLocation()); 3267 else 3268 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3269 SourceLocation(), 3270 SourceLocation(), DIE, 3271 SourceLocation()); 3272 return Info.addFieldInitializer(Init); 3273 } 3274 3275 // Don't build an implicit initializer for union members if none was 3276 // explicitly specified. 3277 if (Field->getParent()->isUnion() || 3278 (Indirect && isWithinAnonymousUnion(Indirect))) 3279 return false; 3280 3281 // Don't initialize incomplete or zero-length arrays. 3282 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3283 return false; 3284 3285 // Don't try to build an implicit initializer if there were semantic 3286 // errors in any of the initializers (and therefore we might be 3287 // missing some that the user actually wrote). 3288 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3289 return false; 3290 3291 CXXCtorInitializer *Init = 0; 3292 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3293 Indirect, Init)) 3294 return true; 3295 3296 if (!Init) 3297 return false; 3298 3299 return Info.addFieldInitializer(Init); 3300} 3301 3302bool 3303Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3304 CXXCtorInitializer *Initializer) { 3305 assert(Initializer->isDelegatingInitializer()); 3306 Constructor->setNumCtorInitializers(1); 3307 CXXCtorInitializer **initializer = 3308 new (Context) CXXCtorInitializer*[1]; 3309 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3310 Constructor->setCtorInitializers(initializer); 3311 3312 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3313 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3314 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3315 } 3316 3317 DelegatingCtorDecls.push_back(Constructor); 3318 3319 return false; 3320} 3321 3322bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3323 ArrayRef<CXXCtorInitializer *> Initializers) { 3324 if (Constructor->isDependentContext()) { 3325 // Just store the initializers as written, they will be checked during 3326 // instantiation. 3327 if (!Initializers.empty()) { 3328 Constructor->setNumCtorInitializers(Initializers.size()); 3329 CXXCtorInitializer **baseOrMemberInitializers = 3330 new (Context) CXXCtorInitializer*[Initializers.size()]; 3331 memcpy(baseOrMemberInitializers, Initializers.data(), 3332 Initializers.size() * sizeof(CXXCtorInitializer*)); 3333 Constructor->setCtorInitializers(baseOrMemberInitializers); 3334 } 3335 3336 // Let template instantiation know whether we had errors. 3337 if (AnyErrors) 3338 Constructor->setInvalidDecl(); 3339 3340 return false; 3341 } 3342 3343 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3344 3345 // We need to build the initializer AST according to order of construction 3346 // and not what user specified in the Initializers list. 3347 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3348 if (!ClassDecl) 3349 return true; 3350 3351 bool HadError = false; 3352 3353 for (unsigned i = 0; i < Initializers.size(); i++) { 3354 CXXCtorInitializer *Member = Initializers[i]; 3355 3356 if (Member->isBaseInitializer()) 3357 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3358 else 3359 Info.AllBaseFields[Member->getAnyMember()] = Member; 3360 } 3361 3362 // Keep track of the direct virtual bases. 3363 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3364 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3365 E = ClassDecl->bases_end(); I != E; ++I) { 3366 if (I->isVirtual()) 3367 DirectVBases.insert(I); 3368 } 3369 3370 // Push virtual bases before others. 3371 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3372 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3373 3374 if (CXXCtorInitializer *Value 3375 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3376 Info.AllToInit.push_back(Value); 3377 } else if (!AnyErrors) { 3378 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3379 CXXCtorInitializer *CXXBaseInit; 3380 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3381 VBase, IsInheritedVirtualBase, 3382 CXXBaseInit)) { 3383 HadError = true; 3384 continue; 3385 } 3386 3387 Info.AllToInit.push_back(CXXBaseInit); 3388 } 3389 } 3390 3391 // Non-virtual bases. 3392 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3393 E = ClassDecl->bases_end(); Base != E; ++Base) { 3394 // Virtuals are in the virtual base list and already constructed. 3395 if (Base->isVirtual()) 3396 continue; 3397 3398 if (CXXCtorInitializer *Value 3399 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3400 Info.AllToInit.push_back(Value); 3401 } else if (!AnyErrors) { 3402 CXXCtorInitializer *CXXBaseInit; 3403 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3404 Base, /*IsInheritedVirtualBase=*/false, 3405 CXXBaseInit)) { 3406 HadError = true; 3407 continue; 3408 } 3409 3410 Info.AllToInit.push_back(CXXBaseInit); 3411 } 3412 } 3413 3414 // Fields. 3415 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3416 MemEnd = ClassDecl->decls_end(); 3417 Mem != MemEnd; ++Mem) { 3418 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3419 // C++ [class.bit]p2: 3420 // A declaration for a bit-field that omits the identifier declares an 3421 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3422 // initialized. 3423 if (F->isUnnamedBitfield()) 3424 continue; 3425 3426 // If we're not generating the implicit copy/move constructor, then we'll 3427 // handle anonymous struct/union fields based on their individual 3428 // indirect fields. 3429 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3430 continue; 3431 3432 if (CollectFieldInitializer(*this, Info, F)) 3433 HadError = true; 3434 continue; 3435 } 3436 3437 // Beyond this point, we only consider default initialization. 3438 if (Info.isImplicitCopyOrMove()) 3439 continue; 3440 3441 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3442 if (F->getType()->isIncompleteArrayType()) { 3443 assert(ClassDecl->hasFlexibleArrayMember() && 3444 "Incomplete array type is not valid"); 3445 continue; 3446 } 3447 3448 // Initialize each field of an anonymous struct individually. 3449 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3450 HadError = true; 3451 3452 continue; 3453 } 3454 } 3455 3456 unsigned NumInitializers = Info.AllToInit.size(); 3457 if (NumInitializers > 0) { 3458 Constructor->setNumCtorInitializers(NumInitializers); 3459 CXXCtorInitializer **baseOrMemberInitializers = 3460 new (Context) CXXCtorInitializer*[NumInitializers]; 3461 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3462 NumInitializers * sizeof(CXXCtorInitializer*)); 3463 Constructor->setCtorInitializers(baseOrMemberInitializers); 3464 3465 // Constructors implicitly reference the base and member 3466 // destructors. 3467 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3468 Constructor->getParent()); 3469 } 3470 3471 return HadError; 3472} 3473 3474static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3475 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3476 const RecordDecl *RD = RT->getDecl(); 3477 if (RD->isAnonymousStructOrUnion()) { 3478 for (RecordDecl::field_iterator Field = RD->field_begin(), 3479 E = RD->field_end(); Field != E; ++Field) 3480 PopulateKeysForFields(*Field, IdealInits); 3481 return; 3482 } 3483 } 3484 IdealInits.push_back(Field); 3485} 3486 3487static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3488 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3489} 3490 3491static void *GetKeyForMember(ASTContext &Context, 3492 CXXCtorInitializer *Member) { 3493 if (!Member->isAnyMemberInitializer()) 3494 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3495 3496 return Member->getAnyMember(); 3497} 3498 3499static void DiagnoseBaseOrMemInitializerOrder( 3500 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3501 ArrayRef<CXXCtorInitializer *> Inits) { 3502 if (Constructor->getDeclContext()->isDependentContext()) 3503 return; 3504 3505 // Don't check initializers order unless the warning is enabled at the 3506 // location of at least one initializer. 3507 bool ShouldCheckOrder = false; 3508 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3509 CXXCtorInitializer *Init = Inits[InitIndex]; 3510 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3511 Init->getSourceLocation()) 3512 != DiagnosticsEngine::Ignored) { 3513 ShouldCheckOrder = true; 3514 break; 3515 } 3516 } 3517 if (!ShouldCheckOrder) 3518 return; 3519 3520 // Build the list of bases and members in the order that they'll 3521 // actually be initialized. The explicit initializers should be in 3522 // this same order but may be missing things. 3523 SmallVector<const void*, 32> IdealInitKeys; 3524 3525 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3526 3527 // 1. Virtual bases. 3528 for (CXXRecordDecl::base_class_const_iterator VBase = 3529 ClassDecl->vbases_begin(), 3530 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3531 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3532 3533 // 2. Non-virtual bases. 3534 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3535 E = ClassDecl->bases_end(); Base != E; ++Base) { 3536 if (Base->isVirtual()) 3537 continue; 3538 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3539 } 3540 3541 // 3. Direct fields. 3542 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3543 E = ClassDecl->field_end(); Field != E; ++Field) { 3544 if (Field->isUnnamedBitfield()) 3545 continue; 3546 3547 PopulateKeysForFields(*Field, IdealInitKeys); 3548 } 3549 3550 unsigned NumIdealInits = IdealInitKeys.size(); 3551 unsigned IdealIndex = 0; 3552 3553 CXXCtorInitializer *PrevInit = 0; 3554 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3555 CXXCtorInitializer *Init = Inits[InitIndex]; 3556 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3557 3558 // Scan forward to try to find this initializer in the idealized 3559 // initializers list. 3560 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3561 if (InitKey == IdealInitKeys[IdealIndex]) 3562 break; 3563 3564 // If we didn't find this initializer, it must be because we 3565 // scanned past it on a previous iteration. That can only 3566 // happen if we're out of order; emit a warning. 3567 if (IdealIndex == NumIdealInits && PrevInit) { 3568 Sema::SemaDiagnosticBuilder D = 3569 SemaRef.Diag(PrevInit->getSourceLocation(), 3570 diag::warn_initializer_out_of_order); 3571 3572 if (PrevInit->isAnyMemberInitializer()) 3573 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3574 else 3575 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3576 3577 if (Init->isAnyMemberInitializer()) 3578 D << 0 << Init->getAnyMember()->getDeclName(); 3579 else 3580 D << 1 << Init->getTypeSourceInfo()->getType(); 3581 3582 // Move back to the initializer's location in the ideal list. 3583 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3584 if (InitKey == IdealInitKeys[IdealIndex]) 3585 break; 3586 3587 assert(IdealIndex != NumIdealInits && 3588 "initializer not found in initializer list"); 3589 } 3590 3591 PrevInit = Init; 3592 } 3593} 3594 3595namespace { 3596bool CheckRedundantInit(Sema &S, 3597 CXXCtorInitializer *Init, 3598 CXXCtorInitializer *&PrevInit) { 3599 if (!PrevInit) { 3600 PrevInit = Init; 3601 return false; 3602 } 3603 3604 if (FieldDecl *Field = Init->getAnyMember()) 3605 S.Diag(Init->getSourceLocation(), 3606 diag::err_multiple_mem_initialization) 3607 << Field->getDeclName() 3608 << Init->getSourceRange(); 3609 else { 3610 const Type *BaseClass = Init->getBaseClass(); 3611 assert(BaseClass && "neither field nor base"); 3612 S.Diag(Init->getSourceLocation(), 3613 diag::err_multiple_base_initialization) 3614 << QualType(BaseClass, 0) 3615 << Init->getSourceRange(); 3616 } 3617 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3618 << 0 << PrevInit->getSourceRange(); 3619 3620 return true; 3621} 3622 3623typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3624typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3625 3626bool CheckRedundantUnionInit(Sema &S, 3627 CXXCtorInitializer *Init, 3628 RedundantUnionMap &Unions) { 3629 FieldDecl *Field = Init->getAnyMember(); 3630 RecordDecl *Parent = Field->getParent(); 3631 NamedDecl *Child = Field; 3632 3633 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3634 if (Parent->isUnion()) { 3635 UnionEntry &En = Unions[Parent]; 3636 if (En.first && En.first != Child) { 3637 S.Diag(Init->getSourceLocation(), 3638 diag::err_multiple_mem_union_initialization) 3639 << Field->getDeclName() 3640 << Init->getSourceRange(); 3641 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3642 << 0 << En.second->getSourceRange(); 3643 return true; 3644 } 3645 if (!En.first) { 3646 En.first = Child; 3647 En.second = Init; 3648 } 3649 if (!Parent->isAnonymousStructOrUnion()) 3650 return false; 3651 } 3652 3653 Child = Parent; 3654 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3655 } 3656 3657 return false; 3658} 3659} 3660 3661/// ActOnMemInitializers - Handle the member initializers for a constructor. 3662void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3663 SourceLocation ColonLoc, 3664 ArrayRef<CXXCtorInitializer*> MemInits, 3665 bool AnyErrors) { 3666 if (!ConstructorDecl) 3667 return; 3668 3669 AdjustDeclIfTemplate(ConstructorDecl); 3670 3671 CXXConstructorDecl *Constructor 3672 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3673 3674 if (!Constructor) { 3675 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3676 return; 3677 } 3678 3679 // Mapping for the duplicate initializers check. 3680 // For member initializers, this is keyed with a FieldDecl*. 3681 // For base initializers, this is keyed with a Type*. 3682 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3683 3684 // Mapping for the inconsistent anonymous-union initializers check. 3685 RedundantUnionMap MemberUnions; 3686 3687 bool HadError = false; 3688 for (unsigned i = 0; i < MemInits.size(); i++) { 3689 CXXCtorInitializer *Init = MemInits[i]; 3690 3691 // Set the source order index. 3692 Init->setSourceOrder(i); 3693 3694 if (Init->isAnyMemberInitializer()) { 3695 FieldDecl *Field = Init->getAnyMember(); 3696 if (CheckRedundantInit(*this, Init, Members[Field]) || 3697 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3698 HadError = true; 3699 } else if (Init->isBaseInitializer()) { 3700 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3701 if (CheckRedundantInit(*this, Init, Members[Key])) 3702 HadError = true; 3703 } else { 3704 assert(Init->isDelegatingInitializer()); 3705 // This must be the only initializer 3706 if (MemInits.size() != 1) { 3707 Diag(Init->getSourceLocation(), 3708 diag::err_delegating_initializer_alone) 3709 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3710 // We will treat this as being the only initializer. 3711 } 3712 SetDelegatingInitializer(Constructor, MemInits[i]); 3713 // Return immediately as the initializer is set. 3714 return; 3715 } 3716 } 3717 3718 if (HadError) 3719 return; 3720 3721 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3722 3723 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3724} 3725 3726void 3727Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3728 CXXRecordDecl *ClassDecl) { 3729 // Ignore dependent contexts. Also ignore unions, since their members never 3730 // have destructors implicitly called. 3731 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3732 return; 3733 3734 // FIXME: all the access-control diagnostics are positioned on the 3735 // field/base declaration. That's probably good; that said, the 3736 // user might reasonably want to know why the destructor is being 3737 // emitted, and we currently don't say. 3738 3739 // Non-static data members. 3740 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3741 E = ClassDecl->field_end(); I != E; ++I) { 3742 FieldDecl *Field = *I; 3743 if (Field->isInvalidDecl()) 3744 continue; 3745 3746 // Don't destroy incomplete or zero-length arrays. 3747 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3748 continue; 3749 3750 QualType FieldType = Context.getBaseElementType(Field->getType()); 3751 3752 const RecordType* RT = FieldType->getAs<RecordType>(); 3753 if (!RT) 3754 continue; 3755 3756 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3757 if (FieldClassDecl->isInvalidDecl()) 3758 continue; 3759 if (FieldClassDecl->hasIrrelevantDestructor()) 3760 continue; 3761 // The destructor for an implicit anonymous union member is never invoked. 3762 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3763 continue; 3764 3765 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3766 assert(Dtor && "No dtor found for FieldClassDecl!"); 3767 CheckDestructorAccess(Field->getLocation(), Dtor, 3768 PDiag(diag::err_access_dtor_field) 3769 << Field->getDeclName() 3770 << FieldType); 3771 3772 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3773 DiagnoseUseOfDecl(Dtor, Location); 3774 } 3775 3776 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3777 3778 // Bases. 3779 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3780 E = ClassDecl->bases_end(); Base != E; ++Base) { 3781 // Bases are always records in a well-formed non-dependent class. 3782 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3783 3784 // Remember direct virtual bases. 3785 if (Base->isVirtual()) 3786 DirectVirtualBases.insert(RT); 3787 3788 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3789 // If our base class is invalid, we probably can't get its dtor anyway. 3790 if (BaseClassDecl->isInvalidDecl()) 3791 continue; 3792 if (BaseClassDecl->hasIrrelevantDestructor()) 3793 continue; 3794 3795 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3796 assert(Dtor && "No dtor found for BaseClassDecl!"); 3797 3798 // FIXME: caret should be on the start of the class name 3799 CheckDestructorAccess(Base->getLocStart(), Dtor, 3800 PDiag(diag::err_access_dtor_base) 3801 << Base->getType() 3802 << Base->getSourceRange(), 3803 Context.getTypeDeclType(ClassDecl)); 3804 3805 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3806 DiagnoseUseOfDecl(Dtor, Location); 3807 } 3808 3809 // Virtual bases. 3810 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3811 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3812 3813 // Bases are always records in a well-formed non-dependent class. 3814 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3815 3816 // Ignore direct virtual bases. 3817 if (DirectVirtualBases.count(RT)) 3818 continue; 3819 3820 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3821 // If our base class is invalid, we probably can't get its dtor anyway. 3822 if (BaseClassDecl->isInvalidDecl()) 3823 continue; 3824 if (BaseClassDecl->hasIrrelevantDestructor()) 3825 continue; 3826 3827 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3828 assert(Dtor && "No dtor found for BaseClassDecl!"); 3829 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3830 PDiag(diag::err_access_dtor_vbase) 3831 << VBase->getType(), 3832 Context.getTypeDeclType(ClassDecl)); 3833 3834 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3835 DiagnoseUseOfDecl(Dtor, Location); 3836 } 3837} 3838 3839void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3840 if (!CDtorDecl) 3841 return; 3842 3843 if (CXXConstructorDecl *Constructor 3844 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3845 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3846} 3847 3848bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3849 unsigned DiagID, AbstractDiagSelID SelID) { 3850 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3851 unsigned DiagID; 3852 AbstractDiagSelID SelID; 3853 3854 public: 3855 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3856 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3857 3858 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3859 if (Suppressed) return; 3860 if (SelID == -1) 3861 S.Diag(Loc, DiagID) << T; 3862 else 3863 S.Diag(Loc, DiagID) << SelID << T; 3864 } 3865 } Diagnoser(DiagID, SelID); 3866 3867 return RequireNonAbstractType(Loc, T, Diagnoser); 3868} 3869 3870bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3871 TypeDiagnoser &Diagnoser) { 3872 if (!getLangOpts().CPlusPlus) 3873 return false; 3874 3875 if (const ArrayType *AT = Context.getAsArrayType(T)) 3876 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3877 3878 if (const PointerType *PT = T->getAs<PointerType>()) { 3879 // Find the innermost pointer type. 3880 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3881 PT = T; 3882 3883 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3884 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3885 } 3886 3887 const RecordType *RT = T->getAs<RecordType>(); 3888 if (!RT) 3889 return false; 3890 3891 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3892 3893 // We can't answer whether something is abstract until it has a 3894 // definition. If it's currently being defined, we'll walk back 3895 // over all the declarations when we have a full definition. 3896 const CXXRecordDecl *Def = RD->getDefinition(); 3897 if (!Def || Def->isBeingDefined()) 3898 return false; 3899 3900 if (!RD->isAbstract()) 3901 return false; 3902 3903 Diagnoser.diagnose(*this, Loc, T); 3904 DiagnoseAbstractType(RD); 3905 3906 return true; 3907} 3908 3909void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3910 // Check if we've already emitted the list of pure virtual functions 3911 // for this class. 3912 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3913 return; 3914 3915 CXXFinalOverriderMap FinalOverriders; 3916 RD->getFinalOverriders(FinalOverriders); 3917 3918 // Keep a set of seen pure methods so we won't diagnose the same method 3919 // more than once. 3920 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3921 3922 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3923 MEnd = FinalOverriders.end(); 3924 M != MEnd; 3925 ++M) { 3926 for (OverridingMethods::iterator SO = M->second.begin(), 3927 SOEnd = M->second.end(); 3928 SO != SOEnd; ++SO) { 3929 // C++ [class.abstract]p4: 3930 // A class is abstract if it contains or inherits at least one 3931 // pure virtual function for which the final overrider is pure 3932 // virtual. 3933 3934 // 3935 if (SO->second.size() != 1) 3936 continue; 3937 3938 if (!SO->second.front().Method->isPure()) 3939 continue; 3940 3941 if (!SeenPureMethods.insert(SO->second.front().Method)) 3942 continue; 3943 3944 Diag(SO->second.front().Method->getLocation(), 3945 diag::note_pure_virtual_function) 3946 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3947 } 3948 } 3949 3950 if (!PureVirtualClassDiagSet) 3951 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3952 PureVirtualClassDiagSet->insert(RD); 3953} 3954 3955namespace { 3956struct AbstractUsageInfo { 3957 Sema &S; 3958 CXXRecordDecl *Record; 3959 CanQualType AbstractType; 3960 bool Invalid; 3961 3962 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3963 : S(S), Record(Record), 3964 AbstractType(S.Context.getCanonicalType( 3965 S.Context.getTypeDeclType(Record))), 3966 Invalid(false) {} 3967 3968 void DiagnoseAbstractType() { 3969 if (Invalid) return; 3970 S.DiagnoseAbstractType(Record); 3971 Invalid = true; 3972 } 3973 3974 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3975}; 3976 3977struct CheckAbstractUsage { 3978 AbstractUsageInfo &Info; 3979 const NamedDecl *Ctx; 3980 3981 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3982 : Info(Info), Ctx(Ctx) {} 3983 3984 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3985 switch (TL.getTypeLocClass()) { 3986#define ABSTRACT_TYPELOC(CLASS, PARENT) 3987#define TYPELOC(CLASS, PARENT) \ 3988 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 3989#include "clang/AST/TypeLocNodes.def" 3990 } 3991 } 3992 3993 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3994 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3995 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3996 if (!TL.getArg(I)) 3997 continue; 3998 3999 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 4000 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4001 } 4002 } 4003 4004 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4005 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4006 } 4007 4008 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4009 // Visit the type parameters from a permissive context. 4010 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4011 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4012 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4013 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4014 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4015 // TODO: other template argument types? 4016 } 4017 } 4018 4019 // Visit pointee types from a permissive context. 4020#define CheckPolymorphic(Type) \ 4021 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4022 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4023 } 4024 CheckPolymorphic(PointerTypeLoc) 4025 CheckPolymorphic(ReferenceTypeLoc) 4026 CheckPolymorphic(MemberPointerTypeLoc) 4027 CheckPolymorphic(BlockPointerTypeLoc) 4028 CheckPolymorphic(AtomicTypeLoc) 4029 4030 /// Handle all the types we haven't given a more specific 4031 /// implementation for above. 4032 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4033 // Every other kind of type that we haven't called out already 4034 // that has an inner type is either (1) sugar or (2) contains that 4035 // inner type in some way as a subobject. 4036 if (TypeLoc Next = TL.getNextTypeLoc()) 4037 return Visit(Next, Sel); 4038 4039 // If there's no inner type and we're in a permissive context, 4040 // don't diagnose. 4041 if (Sel == Sema::AbstractNone) return; 4042 4043 // Check whether the type matches the abstract type. 4044 QualType T = TL.getType(); 4045 if (T->isArrayType()) { 4046 Sel = Sema::AbstractArrayType; 4047 T = Info.S.Context.getBaseElementType(T); 4048 } 4049 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4050 if (CT != Info.AbstractType) return; 4051 4052 // It matched; do some magic. 4053 if (Sel == Sema::AbstractArrayType) { 4054 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4055 << T << TL.getSourceRange(); 4056 } else { 4057 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4058 << Sel << T << TL.getSourceRange(); 4059 } 4060 Info.DiagnoseAbstractType(); 4061 } 4062}; 4063 4064void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4065 Sema::AbstractDiagSelID Sel) { 4066 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4067} 4068 4069} 4070 4071/// Check for invalid uses of an abstract type in a method declaration. 4072static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4073 CXXMethodDecl *MD) { 4074 // No need to do the check on definitions, which require that 4075 // the return/param types be complete. 4076 if (MD->doesThisDeclarationHaveABody()) 4077 return; 4078 4079 // For safety's sake, just ignore it if we don't have type source 4080 // information. This should never happen for non-implicit methods, 4081 // but... 4082 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4083 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4084} 4085 4086/// Check for invalid uses of an abstract type within a class definition. 4087static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4088 CXXRecordDecl *RD) { 4089 for (CXXRecordDecl::decl_iterator 4090 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4091 Decl *D = *I; 4092 if (D->isImplicit()) continue; 4093 4094 // Methods and method templates. 4095 if (isa<CXXMethodDecl>(D)) { 4096 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4097 } else if (isa<FunctionTemplateDecl>(D)) { 4098 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4099 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4100 4101 // Fields and static variables. 4102 } else if (isa<FieldDecl>(D)) { 4103 FieldDecl *FD = cast<FieldDecl>(D); 4104 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4105 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4106 } else if (isa<VarDecl>(D)) { 4107 VarDecl *VD = cast<VarDecl>(D); 4108 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4109 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4110 4111 // Nested classes and class templates. 4112 } else if (isa<CXXRecordDecl>(D)) { 4113 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4114 } else if (isa<ClassTemplateDecl>(D)) { 4115 CheckAbstractClassUsage(Info, 4116 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4117 } 4118 } 4119} 4120 4121/// \brief Perform semantic checks on a class definition that has been 4122/// completing, introducing implicitly-declared members, checking for 4123/// abstract types, etc. 4124void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4125 if (!Record) 4126 return; 4127 4128 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4129 AbstractUsageInfo Info(*this, Record); 4130 CheckAbstractClassUsage(Info, Record); 4131 } 4132 4133 // If this is not an aggregate type and has no user-declared constructor, 4134 // complain about any non-static data members of reference or const scalar 4135 // type, since they will never get initializers. 4136 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4137 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4138 !Record->isLambda()) { 4139 bool Complained = false; 4140 for (RecordDecl::field_iterator F = Record->field_begin(), 4141 FEnd = Record->field_end(); 4142 F != FEnd; ++F) { 4143 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4144 continue; 4145 4146 if (F->getType()->isReferenceType() || 4147 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4148 if (!Complained) { 4149 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4150 << Record->getTagKind() << Record; 4151 Complained = true; 4152 } 4153 4154 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4155 << F->getType()->isReferenceType() 4156 << F->getDeclName(); 4157 } 4158 } 4159 } 4160 4161 if (Record->isDynamicClass() && !Record->isDependentType()) 4162 DynamicClasses.push_back(Record); 4163 4164 if (Record->getIdentifier()) { 4165 // C++ [class.mem]p13: 4166 // If T is the name of a class, then each of the following shall have a 4167 // name different from T: 4168 // - every member of every anonymous union that is a member of class T. 4169 // 4170 // C++ [class.mem]p14: 4171 // In addition, if class T has a user-declared constructor (12.1), every 4172 // non-static data member of class T shall have a name different from T. 4173 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4174 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4175 ++I) { 4176 NamedDecl *D = *I; 4177 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4178 isa<IndirectFieldDecl>(D)) { 4179 Diag(D->getLocation(), diag::err_member_name_of_class) 4180 << D->getDeclName(); 4181 break; 4182 } 4183 } 4184 } 4185 4186 // Warn if the class has virtual methods but non-virtual public destructor. 4187 if (Record->isPolymorphic() && !Record->isDependentType()) { 4188 CXXDestructorDecl *dtor = Record->getDestructor(); 4189 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4190 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4191 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4192 } 4193 4194 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4195 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4196 DiagnoseAbstractType(Record); 4197 } 4198 4199 if (!Record->isDependentType()) { 4200 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4201 MEnd = Record->method_end(); 4202 M != MEnd; ++M) { 4203 // See if a method overloads virtual methods in a base 4204 // class without overriding any. 4205 if (!M->isStatic()) 4206 DiagnoseHiddenVirtualMethods(Record, *M); 4207 4208 // Check whether the explicitly-defaulted special members are valid. 4209 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4210 CheckExplicitlyDefaultedSpecialMember(*M); 4211 4212 // For an explicitly defaulted or deleted special member, we defer 4213 // determining triviality until the class is complete. That time is now! 4214 if (!M->isImplicit() && !M->isUserProvided()) { 4215 CXXSpecialMember CSM = getSpecialMember(*M); 4216 if (CSM != CXXInvalid) { 4217 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4218 4219 // Inform the class that we've finished declaring this member. 4220 Record->finishedDefaultedOrDeletedMember(*M); 4221 } 4222 } 4223 } 4224 } 4225 4226 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4227 // function that is not a constructor declares that member function to be 4228 // const. [...] The class of which that function is a member shall be 4229 // a literal type. 4230 // 4231 // If the class has virtual bases, any constexpr members will already have 4232 // been diagnosed by the checks performed on the member declaration, so 4233 // suppress this (less useful) diagnostic. 4234 // 4235 // We delay this until we know whether an explicitly-defaulted (or deleted) 4236 // destructor for the class is trivial. 4237 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4238 !Record->isLiteral() && !Record->getNumVBases()) { 4239 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4240 MEnd = Record->method_end(); 4241 M != MEnd; ++M) { 4242 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4243 switch (Record->getTemplateSpecializationKind()) { 4244 case TSK_ImplicitInstantiation: 4245 case TSK_ExplicitInstantiationDeclaration: 4246 case TSK_ExplicitInstantiationDefinition: 4247 // If a template instantiates to a non-literal type, but its members 4248 // instantiate to constexpr functions, the template is technically 4249 // ill-formed, but we allow it for sanity. 4250 continue; 4251 4252 case TSK_Undeclared: 4253 case TSK_ExplicitSpecialization: 4254 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4255 diag::err_constexpr_method_non_literal); 4256 break; 4257 } 4258 4259 // Only produce one error per class. 4260 break; 4261 } 4262 } 4263 } 4264 4265 // Declare inheriting constructors. We do this eagerly here because: 4266 // - The standard requires an eager diagnostic for conflicting inheriting 4267 // constructors from different classes. 4268 // - The lazy declaration of the other implicit constructors is so as to not 4269 // waste space and performance on classes that are not meant to be 4270 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4271 // have inheriting constructors. 4272 DeclareInheritingConstructors(Record); 4273} 4274 4275/// Is the special member function which would be selected to perform the 4276/// specified operation on the specified class type a constexpr constructor? 4277static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4278 Sema::CXXSpecialMember CSM, 4279 bool ConstArg) { 4280 Sema::SpecialMemberOverloadResult *SMOR = 4281 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4282 false, false, false, false); 4283 if (!SMOR || !SMOR->getMethod()) 4284 // A constructor we wouldn't select can't be "involved in initializing" 4285 // anything. 4286 return true; 4287 return SMOR->getMethod()->isConstexpr(); 4288} 4289 4290/// Determine whether the specified special member function would be constexpr 4291/// if it were implicitly defined. 4292static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4293 Sema::CXXSpecialMember CSM, 4294 bool ConstArg) { 4295 if (!S.getLangOpts().CPlusPlus11) 4296 return false; 4297 4298 // C++11 [dcl.constexpr]p4: 4299 // In the definition of a constexpr constructor [...] 4300 switch (CSM) { 4301 case Sema::CXXDefaultConstructor: 4302 // Since default constructor lookup is essentially trivial (and cannot 4303 // involve, for instance, template instantiation), we compute whether a 4304 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4305 // 4306 // This is important for performance; we need to know whether the default 4307 // constructor is constexpr to determine whether the type is a literal type. 4308 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4309 4310 case Sema::CXXCopyConstructor: 4311 case Sema::CXXMoveConstructor: 4312 // For copy or move constructors, we need to perform overload resolution. 4313 break; 4314 4315 case Sema::CXXCopyAssignment: 4316 case Sema::CXXMoveAssignment: 4317 case Sema::CXXDestructor: 4318 case Sema::CXXInvalid: 4319 return false; 4320 } 4321 4322 // -- if the class is a non-empty union, or for each non-empty anonymous 4323 // union member of a non-union class, exactly one non-static data member 4324 // shall be initialized; [DR1359] 4325 // 4326 // If we squint, this is guaranteed, since exactly one non-static data member 4327 // will be initialized (if the constructor isn't deleted), we just don't know 4328 // which one. 4329 if (ClassDecl->isUnion()) 4330 return true; 4331 4332 // -- the class shall not have any virtual base classes; 4333 if (ClassDecl->getNumVBases()) 4334 return false; 4335 4336 // -- every constructor involved in initializing [...] base class 4337 // sub-objects shall be a constexpr constructor; 4338 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4339 BEnd = ClassDecl->bases_end(); 4340 B != BEnd; ++B) { 4341 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4342 if (!BaseType) continue; 4343 4344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4345 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4346 return false; 4347 } 4348 4349 // -- every constructor involved in initializing non-static data members 4350 // [...] shall be a constexpr constructor; 4351 // -- every non-static data member and base class sub-object shall be 4352 // initialized 4353 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4354 FEnd = ClassDecl->field_end(); 4355 F != FEnd; ++F) { 4356 if (F->isInvalidDecl()) 4357 continue; 4358 if (const RecordType *RecordTy = 4359 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4360 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4361 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4362 return false; 4363 } 4364 } 4365 4366 // All OK, it's constexpr! 4367 return true; 4368} 4369 4370static Sema::ImplicitExceptionSpecification 4371computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4372 switch (S.getSpecialMember(MD)) { 4373 case Sema::CXXDefaultConstructor: 4374 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4375 case Sema::CXXCopyConstructor: 4376 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4377 case Sema::CXXCopyAssignment: 4378 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4379 case Sema::CXXMoveConstructor: 4380 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4381 case Sema::CXXMoveAssignment: 4382 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4383 case Sema::CXXDestructor: 4384 return S.ComputeDefaultedDtorExceptionSpec(MD); 4385 case Sema::CXXInvalid: 4386 break; 4387 } 4388 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4389 "only special members have implicit exception specs"); 4390 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4391} 4392 4393static void 4394updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4395 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4396 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4397 ExceptSpec.getEPI(EPI); 4398 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4399 FPT->getArgTypes(), EPI)); 4400} 4401 4402void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4403 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4404 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4405 return; 4406 4407 // Evaluate the exception specification. 4408 ImplicitExceptionSpecification ExceptSpec = 4409 computeImplicitExceptionSpec(*this, Loc, MD); 4410 4411 // Update the type of the special member to use it. 4412 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4413 4414 // A user-provided destructor can be defined outside the class. When that 4415 // happens, be sure to update the exception specification on both 4416 // declarations. 4417 const FunctionProtoType *CanonicalFPT = 4418 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4419 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4420 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4421 CanonicalFPT, ExceptSpec); 4422} 4423 4424void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4425 CXXRecordDecl *RD = MD->getParent(); 4426 CXXSpecialMember CSM = getSpecialMember(MD); 4427 4428 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4429 "not an explicitly-defaulted special member"); 4430 4431 // Whether this was the first-declared instance of the constructor. 4432 // This affects whether we implicitly add an exception spec and constexpr. 4433 bool First = MD == MD->getCanonicalDecl(); 4434 4435 bool HadError = false; 4436 4437 // C++11 [dcl.fct.def.default]p1: 4438 // A function that is explicitly defaulted shall 4439 // -- be a special member function (checked elsewhere), 4440 // -- have the same type (except for ref-qualifiers, and except that a 4441 // copy operation can take a non-const reference) as an implicit 4442 // declaration, and 4443 // -- not have default arguments. 4444 unsigned ExpectedParams = 1; 4445 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4446 ExpectedParams = 0; 4447 if (MD->getNumParams() != ExpectedParams) { 4448 // This also checks for default arguments: a copy or move constructor with a 4449 // default argument is classified as a default constructor, and assignment 4450 // operations and destructors can't have default arguments. 4451 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4452 << CSM << MD->getSourceRange(); 4453 HadError = true; 4454 } else if (MD->isVariadic()) { 4455 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4456 << CSM << MD->getSourceRange(); 4457 HadError = true; 4458 } 4459 4460 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4461 4462 bool CanHaveConstParam = false; 4463 if (CSM == CXXCopyConstructor) 4464 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4465 else if (CSM == CXXCopyAssignment) 4466 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4467 4468 QualType ReturnType = Context.VoidTy; 4469 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4470 // Check for return type matching. 4471 ReturnType = Type->getResultType(); 4472 QualType ExpectedReturnType = 4473 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4474 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4475 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4476 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4477 HadError = true; 4478 } 4479 4480 // A defaulted special member cannot have cv-qualifiers. 4481 if (Type->getTypeQuals()) { 4482 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4483 << (CSM == CXXMoveAssignment); 4484 HadError = true; 4485 } 4486 } 4487 4488 // Check for parameter type matching. 4489 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4490 bool HasConstParam = false; 4491 if (ExpectedParams && ArgType->isReferenceType()) { 4492 // Argument must be reference to possibly-const T. 4493 QualType ReferentType = ArgType->getPointeeType(); 4494 HasConstParam = ReferentType.isConstQualified(); 4495 4496 if (ReferentType.isVolatileQualified()) { 4497 Diag(MD->getLocation(), 4498 diag::err_defaulted_special_member_volatile_param) << CSM; 4499 HadError = true; 4500 } 4501 4502 if (HasConstParam && !CanHaveConstParam) { 4503 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4504 Diag(MD->getLocation(), 4505 diag::err_defaulted_special_member_copy_const_param) 4506 << (CSM == CXXCopyAssignment); 4507 // FIXME: Explain why this special member can't be const. 4508 } else { 4509 Diag(MD->getLocation(), 4510 diag::err_defaulted_special_member_move_const_param) 4511 << (CSM == CXXMoveAssignment); 4512 } 4513 HadError = true; 4514 } 4515 } else if (ExpectedParams) { 4516 // A copy assignment operator can take its argument by value, but a 4517 // defaulted one cannot. 4518 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4519 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4520 HadError = true; 4521 } 4522 4523 // C++11 [dcl.fct.def.default]p2: 4524 // An explicitly-defaulted function may be declared constexpr only if it 4525 // would have been implicitly declared as constexpr, 4526 // Do not apply this rule to members of class templates, since core issue 1358 4527 // makes such functions always instantiate to constexpr functions. For 4528 // non-constructors, this is checked elsewhere. 4529 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4530 HasConstParam); 4531 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4532 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4533 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4534 // FIXME: Explain why the constructor can't be constexpr. 4535 HadError = true; 4536 } 4537 4538 // and may have an explicit exception-specification only if it is compatible 4539 // with the exception-specification on the implicit declaration. 4540 if (Type->hasExceptionSpec()) { 4541 // Delay the check if this is the first declaration of the special member, 4542 // since we may not have parsed some necessary in-class initializers yet. 4543 if (First) { 4544 // If the exception specification needs to be instantiated, do so now, 4545 // before we clobber it with an EST_Unevaluated specification below. 4546 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4547 InstantiateExceptionSpec(MD->getLocStart(), MD); 4548 Type = MD->getType()->getAs<FunctionProtoType>(); 4549 } 4550 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4551 } else 4552 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4553 } 4554 4555 // If a function is explicitly defaulted on its first declaration, 4556 if (First) { 4557 // -- it is implicitly considered to be constexpr if the implicit 4558 // definition would be, 4559 MD->setConstexpr(Constexpr); 4560 4561 // -- it is implicitly considered to have the same exception-specification 4562 // as if it had been implicitly declared, 4563 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4564 EPI.ExceptionSpecType = EST_Unevaluated; 4565 EPI.ExceptionSpecDecl = MD; 4566 MD->setType(Context.getFunctionType(ReturnType, 4567 ArrayRef<QualType>(&ArgType, 4568 ExpectedParams), 4569 EPI)); 4570 } 4571 4572 if (ShouldDeleteSpecialMember(MD, CSM)) { 4573 if (First) { 4574 SetDeclDeleted(MD, MD->getLocation()); 4575 } else { 4576 // C++11 [dcl.fct.def.default]p4: 4577 // [For a] user-provided explicitly-defaulted function [...] if such a 4578 // function is implicitly defined as deleted, the program is ill-formed. 4579 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4580 HadError = true; 4581 } 4582 } 4583 4584 if (HadError) 4585 MD->setInvalidDecl(); 4586} 4587 4588/// Check whether the exception specification provided for an 4589/// explicitly-defaulted special member matches the exception specification 4590/// that would have been generated for an implicit special member, per 4591/// C++11 [dcl.fct.def.default]p2. 4592void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4593 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4594 // Compute the implicit exception specification. 4595 FunctionProtoType::ExtProtoInfo EPI; 4596 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4597 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4598 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI)); 4599 4600 // Ensure that it matches. 4601 CheckEquivalentExceptionSpec( 4602 PDiag(diag::err_incorrect_defaulted_exception_spec) 4603 << getSpecialMember(MD), PDiag(), 4604 ImplicitType, SourceLocation(), 4605 SpecifiedType, MD->getLocation()); 4606} 4607 4608void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4609 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4610 I != N; ++I) 4611 CheckExplicitlyDefaultedMemberExceptionSpec( 4612 DelayedDefaultedMemberExceptionSpecs[I].first, 4613 DelayedDefaultedMemberExceptionSpecs[I].second); 4614 4615 DelayedDefaultedMemberExceptionSpecs.clear(); 4616} 4617 4618namespace { 4619struct SpecialMemberDeletionInfo { 4620 Sema &S; 4621 CXXMethodDecl *MD; 4622 Sema::CXXSpecialMember CSM; 4623 bool Diagnose; 4624 4625 // Properties of the special member, computed for convenience. 4626 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4627 SourceLocation Loc; 4628 4629 bool AllFieldsAreConst; 4630 4631 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4632 Sema::CXXSpecialMember CSM, bool Diagnose) 4633 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4634 IsConstructor(false), IsAssignment(false), IsMove(false), 4635 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4636 AllFieldsAreConst(true) { 4637 switch (CSM) { 4638 case Sema::CXXDefaultConstructor: 4639 case Sema::CXXCopyConstructor: 4640 IsConstructor = true; 4641 break; 4642 case Sema::CXXMoveConstructor: 4643 IsConstructor = true; 4644 IsMove = true; 4645 break; 4646 case Sema::CXXCopyAssignment: 4647 IsAssignment = true; 4648 break; 4649 case Sema::CXXMoveAssignment: 4650 IsAssignment = true; 4651 IsMove = true; 4652 break; 4653 case Sema::CXXDestructor: 4654 break; 4655 case Sema::CXXInvalid: 4656 llvm_unreachable("invalid special member kind"); 4657 } 4658 4659 if (MD->getNumParams()) { 4660 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4661 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4662 } 4663 } 4664 4665 bool inUnion() const { return MD->getParent()->isUnion(); } 4666 4667 /// Look up the corresponding special member in the given class. 4668 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4669 unsigned Quals) { 4670 unsigned TQ = MD->getTypeQualifiers(); 4671 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4672 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4673 Quals = 0; 4674 return S.LookupSpecialMember(Class, CSM, 4675 ConstArg || (Quals & Qualifiers::Const), 4676 VolatileArg || (Quals & Qualifiers::Volatile), 4677 MD->getRefQualifier() == RQ_RValue, 4678 TQ & Qualifiers::Const, 4679 TQ & Qualifiers::Volatile); 4680 } 4681 4682 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4683 4684 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4685 bool shouldDeleteForField(FieldDecl *FD); 4686 bool shouldDeleteForAllConstMembers(); 4687 4688 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4689 unsigned Quals); 4690 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4691 Sema::SpecialMemberOverloadResult *SMOR, 4692 bool IsDtorCallInCtor); 4693 4694 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4695}; 4696} 4697 4698/// Is the given special member inaccessible when used on the given 4699/// sub-object. 4700bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4701 CXXMethodDecl *target) { 4702 /// If we're operating on a base class, the object type is the 4703 /// type of this special member. 4704 QualType objectTy; 4705 AccessSpecifier access = target->getAccess(); 4706 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4707 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4708 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4709 4710 // If we're operating on a field, the object type is the type of the field. 4711 } else { 4712 objectTy = S.Context.getTypeDeclType(target->getParent()); 4713 } 4714 4715 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4716} 4717 4718/// Check whether we should delete a special member due to the implicit 4719/// definition containing a call to a special member of a subobject. 4720bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4721 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4722 bool IsDtorCallInCtor) { 4723 CXXMethodDecl *Decl = SMOR->getMethod(); 4724 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4725 4726 int DiagKind = -1; 4727 4728 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4729 DiagKind = !Decl ? 0 : 1; 4730 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4731 DiagKind = 2; 4732 else if (!isAccessible(Subobj, Decl)) 4733 DiagKind = 3; 4734 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4735 !Decl->isTrivial()) { 4736 // A member of a union must have a trivial corresponding special member. 4737 // As a weird special case, a destructor call from a union's constructor 4738 // must be accessible and non-deleted, but need not be trivial. Such a 4739 // destructor is never actually called, but is semantically checked as 4740 // if it were. 4741 DiagKind = 4; 4742 } 4743 4744 if (DiagKind == -1) 4745 return false; 4746 4747 if (Diagnose) { 4748 if (Field) { 4749 S.Diag(Field->getLocation(), 4750 diag::note_deleted_special_member_class_subobject) 4751 << CSM << MD->getParent() << /*IsField*/true 4752 << Field << DiagKind << IsDtorCallInCtor; 4753 } else { 4754 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4755 S.Diag(Base->getLocStart(), 4756 diag::note_deleted_special_member_class_subobject) 4757 << CSM << MD->getParent() << /*IsField*/false 4758 << Base->getType() << DiagKind << IsDtorCallInCtor; 4759 } 4760 4761 if (DiagKind == 1) 4762 S.NoteDeletedFunction(Decl); 4763 // FIXME: Explain inaccessibility if DiagKind == 3. 4764 } 4765 4766 return true; 4767} 4768 4769/// Check whether we should delete a special member function due to having a 4770/// direct or virtual base class or non-static data member of class type M. 4771bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4772 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4773 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4774 4775 // C++11 [class.ctor]p5: 4776 // -- any direct or virtual base class, or non-static data member with no 4777 // brace-or-equal-initializer, has class type M (or array thereof) and 4778 // either M has no default constructor or overload resolution as applied 4779 // to M's default constructor results in an ambiguity or in a function 4780 // that is deleted or inaccessible 4781 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4782 // -- a direct or virtual base class B that cannot be copied/moved because 4783 // overload resolution, as applied to B's corresponding special member, 4784 // results in an ambiguity or a function that is deleted or inaccessible 4785 // from the defaulted special member 4786 // C++11 [class.dtor]p5: 4787 // -- any direct or virtual base class [...] has a type with a destructor 4788 // that is deleted or inaccessible 4789 if (!(CSM == Sema::CXXDefaultConstructor && 4790 Field && Field->hasInClassInitializer()) && 4791 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4792 return true; 4793 4794 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4795 // -- any direct or virtual base class or non-static data member has a 4796 // type with a destructor that is deleted or inaccessible 4797 if (IsConstructor) { 4798 Sema::SpecialMemberOverloadResult *SMOR = 4799 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4800 false, false, false, false, false); 4801 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4802 return true; 4803 } 4804 4805 return false; 4806} 4807 4808/// Check whether we should delete a special member function due to the class 4809/// having a particular direct or virtual base class. 4810bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4811 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4812 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4813} 4814 4815/// Check whether we should delete a special member function due to the class 4816/// having a particular non-static data member. 4817bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4818 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4819 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4820 4821 if (CSM == Sema::CXXDefaultConstructor) { 4822 // For a default constructor, all references must be initialized in-class 4823 // and, if a union, it must have a non-const member. 4824 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4825 if (Diagnose) 4826 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4827 << MD->getParent() << FD << FieldType << /*Reference*/0; 4828 return true; 4829 } 4830 // C++11 [class.ctor]p5: any non-variant non-static data member of 4831 // const-qualified type (or array thereof) with no 4832 // brace-or-equal-initializer does not have a user-provided default 4833 // constructor. 4834 if (!inUnion() && FieldType.isConstQualified() && 4835 !FD->hasInClassInitializer() && 4836 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4837 if (Diagnose) 4838 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4839 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4840 return true; 4841 } 4842 4843 if (inUnion() && !FieldType.isConstQualified()) 4844 AllFieldsAreConst = false; 4845 } else if (CSM == Sema::CXXCopyConstructor) { 4846 // For a copy constructor, data members must not be of rvalue reference 4847 // type. 4848 if (FieldType->isRValueReferenceType()) { 4849 if (Diagnose) 4850 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4851 << MD->getParent() << FD << FieldType; 4852 return true; 4853 } 4854 } else if (IsAssignment) { 4855 // For an assignment operator, data members must not be of reference type. 4856 if (FieldType->isReferenceType()) { 4857 if (Diagnose) 4858 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4859 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4860 return true; 4861 } 4862 if (!FieldRecord && FieldType.isConstQualified()) { 4863 // C++11 [class.copy]p23: 4864 // -- a non-static data member of const non-class type (or array thereof) 4865 if (Diagnose) 4866 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4867 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4868 return true; 4869 } 4870 } 4871 4872 if (FieldRecord) { 4873 // Some additional restrictions exist on the variant members. 4874 if (!inUnion() && FieldRecord->isUnion() && 4875 FieldRecord->isAnonymousStructOrUnion()) { 4876 bool AllVariantFieldsAreConst = true; 4877 4878 // FIXME: Handle anonymous unions declared within anonymous unions. 4879 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4880 UE = FieldRecord->field_end(); 4881 UI != UE; ++UI) { 4882 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4883 4884 if (!UnionFieldType.isConstQualified()) 4885 AllVariantFieldsAreConst = false; 4886 4887 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4888 if (UnionFieldRecord && 4889 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4890 UnionFieldType.getCVRQualifiers())) 4891 return true; 4892 } 4893 4894 // At least one member in each anonymous union must be non-const 4895 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4896 FieldRecord->field_begin() != FieldRecord->field_end()) { 4897 if (Diagnose) 4898 S.Diag(FieldRecord->getLocation(), 4899 diag::note_deleted_default_ctor_all_const) 4900 << MD->getParent() << /*anonymous union*/1; 4901 return true; 4902 } 4903 4904 // Don't check the implicit member of the anonymous union type. 4905 // This is technically non-conformant, but sanity demands it. 4906 return false; 4907 } 4908 4909 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4910 FieldType.getCVRQualifiers())) 4911 return true; 4912 } 4913 4914 return false; 4915} 4916 4917/// C++11 [class.ctor] p5: 4918/// A defaulted default constructor for a class X is defined as deleted if 4919/// X is a union and all of its variant members are of const-qualified type. 4920bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4921 // This is a silly definition, because it gives an empty union a deleted 4922 // default constructor. Don't do that. 4923 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4924 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4925 if (Diagnose) 4926 S.Diag(MD->getParent()->getLocation(), 4927 diag::note_deleted_default_ctor_all_const) 4928 << MD->getParent() << /*not anonymous union*/0; 4929 return true; 4930 } 4931 return false; 4932} 4933 4934/// Determine whether a defaulted special member function should be defined as 4935/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4936/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4937bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4938 bool Diagnose) { 4939 if (MD->isInvalidDecl()) 4940 return false; 4941 CXXRecordDecl *RD = MD->getParent(); 4942 assert(!RD->isDependentType() && "do deletion after instantiation"); 4943 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4944 return false; 4945 4946 // C++11 [expr.lambda.prim]p19: 4947 // The closure type associated with a lambda-expression has a 4948 // deleted (8.4.3) default constructor and a deleted copy 4949 // assignment operator. 4950 if (RD->isLambda() && 4951 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4952 if (Diagnose) 4953 Diag(RD->getLocation(), diag::note_lambda_decl); 4954 return true; 4955 } 4956 4957 // For an anonymous struct or union, the copy and assignment special members 4958 // will never be used, so skip the check. For an anonymous union declared at 4959 // namespace scope, the constructor and destructor are used. 4960 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4961 RD->isAnonymousStructOrUnion()) 4962 return false; 4963 4964 // C++11 [class.copy]p7, p18: 4965 // If the class definition declares a move constructor or move assignment 4966 // operator, an implicitly declared copy constructor or copy assignment 4967 // operator is defined as deleted. 4968 if (MD->isImplicit() && 4969 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4970 CXXMethodDecl *UserDeclaredMove = 0; 4971 4972 // In Microsoft mode, a user-declared move only causes the deletion of the 4973 // corresponding copy operation, not both copy operations. 4974 if (RD->hasUserDeclaredMoveConstructor() && 4975 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4976 if (!Diagnose) return true; 4977 4978 // Find any user-declared move constructor. 4979 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4980 E = RD->ctor_end(); I != E; ++I) { 4981 if (I->isMoveConstructor()) { 4982 UserDeclaredMove = *I; 4983 break; 4984 } 4985 } 4986 assert(UserDeclaredMove); 4987 } else if (RD->hasUserDeclaredMoveAssignment() && 4988 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4989 if (!Diagnose) return true; 4990 4991 // Find any user-declared move assignment operator. 4992 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4993 E = RD->method_end(); I != E; ++I) { 4994 if (I->isMoveAssignmentOperator()) { 4995 UserDeclaredMove = *I; 4996 break; 4997 } 4998 } 4999 assert(UserDeclaredMove); 5000 } 5001 5002 if (UserDeclaredMove) { 5003 Diag(UserDeclaredMove->getLocation(), 5004 diag::note_deleted_copy_user_declared_move) 5005 << (CSM == CXXCopyAssignment) << RD 5006 << UserDeclaredMove->isMoveAssignmentOperator(); 5007 return true; 5008 } 5009 } 5010 5011 // Do access control from the special member function 5012 ContextRAII MethodContext(*this, MD); 5013 5014 // C++11 [class.dtor]p5: 5015 // -- for a virtual destructor, lookup of the non-array deallocation function 5016 // results in an ambiguity or in a function that is deleted or inaccessible 5017 if (CSM == CXXDestructor && MD->isVirtual()) { 5018 FunctionDecl *OperatorDelete = 0; 5019 DeclarationName Name = 5020 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5021 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5022 OperatorDelete, false)) { 5023 if (Diagnose) 5024 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5025 return true; 5026 } 5027 } 5028 5029 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5030 5031 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5032 BE = RD->bases_end(); BI != BE; ++BI) 5033 if (!BI->isVirtual() && 5034 SMI.shouldDeleteForBase(BI)) 5035 return true; 5036 5037 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5038 BE = RD->vbases_end(); BI != BE; ++BI) 5039 if (SMI.shouldDeleteForBase(BI)) 5040 return true; 5041 5042 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5043 FE = RD->field_end(); FI != FE; ++FI) 5044 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5045 SMI.shouldDeleteForField(*FI)) 5046 return true; 5047 5048 if (SMI.shouldDeleteForAllConstMembers()) 5049 return true; 5050 5051 return false; 5052} 5053 5054/// Perform lookup for a special member of the specified kind, and determine 5055/// whether it is trivial. If the triviality can be determined without the 5056/// lookup, skip it. This is intended for use when determining whether a 5057/// special member of a containing object is trivial, and thus does not ever 5058/// perform overload resolution for default constructors. 5059/// 5060/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5061/// member that was most likely to be intended to be trivial, if any. 5062static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5063 Sema::CXXSpecialMember CSM, unsigned Quals, 5064 CXXMethodDecl **Selected) { 5065 if (Selected) 5066 *Selected = 0; 5067 5068 switch (CSM) { 5069 case Sema::CXXInvalid: 5070 llvm_unreachable("not a special member"); 5071 5072 case Sema::CXXDefaultConstructor: 5073 // C++11 [class.ctor]p5: 5074 // A default constructor is trivial if: 5075 // - all the [direct subobjects] have trivial default constructors 5076 // 5077 // Note, no overload resolution is performed in this case. 5078 if (RD->hasTrivialDefaultConstructor()) 5079 return true; 5080 5081 if (Selected) { 5082 // If there's a default constructor which could have been trivial, dig it 5083 // out. Otherwise, if there's any user-provided default constructor, point 5084 // to that as an example of why there's not a trivial one. 5085 CXXConstructorDecl *DefCtor = 0; 5086 if (RD->needsImplicitDefaultConstructor()) 5087 S.DeclareImplicitDefaultConstructor(RD); 5088 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5089 CE = RD->ctor_end(); CI != CE; ++CI) { 5090 if (!CI->isDefaultConstructor()) 5091 continue; 5092 DefCtor = *CI; 5093 if (!DefCtor->isUserProvided()) 5094 break; 5095 } 5096 5097 *Selected = DefCtor; 5098 } 5099 5100 return false; 5101 5102 case Sema::CXXDestructor: 5103 // C++11 [class.dtor]p5: 5104 // A destructor is trivial if: 5105 // - all the direct [subobjects] have trivial destructors 5106 if (RD->hasTrivialDestructor()) 5107 return true; 5108 5109 if (Selected) { 5110 if (RD->needsImplicitDestructor()) 5111 S.DeclareImplicitDestructor(RD); 5112 *Selected = RD->getDestructor(); 5113 } 5114 5115 return false; 5116 5117 case Sema::CXXCopyConstructor: 5118 // C++11 [class.copy]p12: 5119 // A copy constructor is trivial if: 5120 // - the constructor selected to copy each direct [subobject] is trivial 5121 if (RD->hasTrivialCopyConstructor()) { 5122 if (Quals == Qualifiers::Const) 5123 // We must either select the trivial copy constructor or reach an 5124 // ambiguity; no need to actually perform overload resolution. 5125 return true; 5126 } else if (!Selected) { 5127 return false; 5128 } 5129 // In C++98, we are not supposed to perform overload resolution here, but we 5130 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5131 // cases like B as having a non-trivial copy constructor: 5132 // struct A { template<typename T> A(T&); }; 5133 // struct B { mutable A a; }; 5134 goto NeedOverloadResolution; 5135 5136 case Sema::CXXCopyAssignment: 5137 // C++11 [class.copy]p25: 5138 // A copy assignment operator is trivial if: 5139 // - the assignment operator selected to copy each direct [subobject] is 5140 // trivial 5141 if (RD->hasTrivialCopyAssignment()) { 5142 if (Quals == Qualifiers::Const) 5143 return true; 5144 } else if (!Selected) { 5145 return false; 5146 } 5147 // In C++98, we are not supposed to perform overload resolution here, but we 5148 // treat that as a language defect. 5149 goto NeedOverloadResolution; 5150 5151 case Sema::CXXMoveConstructor: 5152 case Sema::CXXMoveAssignment: 5153 NeedOverloadResolution: 5154 Sema::SpecialMemberOverloadResult *SMOR = 5155 S.LookupSpecialMember(RD, CSM, 5156 Quals & Qualifiers::Const, 5157 Quals & Qualifiers::Volatile, 5158 /*RValueThis*/false, /*ConstThis*/false, 5159 /*VolatileThis*/false); 5160 5161 // The standard doesn't describe how to behave if the lookup is ambiguous. 5162 // We treat it as not making the member non-trivial, just like the standard 5163 // mandates for the default constructor. This should rarely matter, because 5164 // the member will also be deleted. 5165 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5166 return true; 5167 5168 if (!SMOR->getMethod()) { 5169 assert(SMOR->getKind() == 5170 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5171 return false; 5172 } 5173 5174 // We deliberately don't check if we found a deleted special member. We're 5175 // not supposed to! 5176 if (Selected) 5177 *Selected = SMOR->getMethod(); 5178 return SMOR->getMethod()->isTrivial(); 5179 } 5180 5181 llvm_unreachable("unknown special method kind"); 5182} 5183 5184static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5185 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5186 CI != CE; ++CI) 5187 if (!CI->isImplicit()) 5188 return *CI; 5189 5190 // Look for constructor templates. 5191 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5192 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5193 if (CXXConstructorDecl *CD = 5194 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5195 return CD; 5196 } 5197 5198 return 0; 5199} 5200 5201/// The kind of subobject we are checking for triviality. The values of this 5202/// enumeration are used in diagnostics. 5203enum TrivialSubobjectKind { 5204 /// The subobject is a base class. 5205 TSK_BaseClass, 5206 /// The subobject is a non-static data member. 5207 TSK_Field, 5208 /// The object is actually the complete object. 5209 TSK_CompleteObject 5210}; 5211 5212/// Check whether the special member selected for a given type would be trivial. 5213static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5214 QualType SubType, 5215 Sema::CXXSpecialMember CSM, 5216 TrivialSubobjectKind Kind, 5217 bool Diagnose) { 5218 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5219 if (!SubRD) 5220 return true; 5221 5222 CXXMethodDecl *Selected; 5223 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5224 Diagnose ? &Selected : 0)) 5225 return true; 5226 5227 if (Diagnose) { 5228 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5229 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5230 << Kind << SubType.getUnqualifiedType(); 5231 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5232 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5233 } else if (!Selected) 5234 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5235 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5236 else if (Selected->isUserProvided()) { 5237 if (Kind == TSK_CompleteObject) 5238 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5239 << Kind << SubType.getUnqualifiedType() << CSM; 5240 else { 5241 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5242 << Kind << SubType.getUnqualifiedType() << CSM; 5243 S.Diag(Selected->getLocation(), diag::note_declared_at); 5244 } 5245 } else { 5246 if (Kind != TSK_CompleteObject) 5247 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5248 << Kind << SubType.getUnqualifiedType() << CSM; 5249 5250 // Explain why the defaulted or deleted special member isn't trivial. 5251 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5252 } 5253 } 5254 5255 return false; 5256} 5257 5258/// Check whether the members of a class type allow a special member to be 5259/// trivial. 5260static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5261 Sema::CXXSpecialMember CSM, 5262 bool ConstArg, bool Diagnose) { 5263 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5264 FE = RD->field_end(); FI != FE; ++FI) { 5265 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5266 continue; 5267 5268 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5269 5270 // Pretend anonymous struct or union members are members of this class. 5271 if (FI->isAnonymousStructOrUnion()) { 5272 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5273 CSM, ConstArg, Diagnose)) 5274 return false; 5275 continue; 5276 } 5277 5278 // C++11 [class.ctor]p5: 5279 // A default constructor is trivial if [...] 5280 // -- no non-static data member of its class has a 5281 // brace-or-equal-initializer 5282 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5283 if (Diagnose) 5284 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5285 return false; 5286 } 5287 5288 // Objective C ARC 4.3.5: 5289 // [...] nontrivally ownership-qualified types are [...] not trivially 5290 // default constructible, copy constructible, move constructible, copy 5291 // assignable, move assignable, or destructible [...] 5292 if (S.getLangOpts().ObjCAutoRefCount && 5293 FieldType.hasNonTrivialObjCLifetime()) { 5294 if (Diagnose) 5295 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5296 << RD << FieldType.getObjCLifetime(); 5297 return false; 5298 } 5299 5300 if (ConstArg && !FI->isMutable()) 5301 FieldType.addConst(); 5302 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5303 TSK_Field, Diagnose)) 5304 return false; 5305 } 5306 5307 return true; 5308} 5309 5310/// Diagnose why the specified class does not have a trivial special member of 5311/// the given kind. 5312void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5313 QualType Ty = Context.getRecordType(RD); 5314 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5315 Ty.addConst(); 5316 5317 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5318 TSK_CompleteObject, /*Diagnose*/true); 5319} 5320 5321/// Determine whether a defaulted or deleted special member function is trivial, 5322/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5323/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5324bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5325 bool Diagnose) { 5326 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5327 5328 CXXRecordDecl *RD = MD->getParent(); 5329 5330 bool ConstArg = false; 5331 5332 // C++11 [class.copy]p12, p25: 5333 // A [special member] is trivial if its declared parameter type is the same 5334 // as if it had been implicitly declared [...] 5335 switch (CSM) { 5336 case CXXDefaultConstructor: 5337 case CXXDestructor: 5338 // Trivial default constructors and destructors cannot have parameters. 5339 break; 5340 5341 case CXXCopyConstructor: 5342 case CXXCopyAssignment: { 5343 // Trivial copy operations always have const, non-volatile parameter types. 5344 ConstArg = true; 5345 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5346 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5347 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5348 if (Diagnose) 5349 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5350 << Param0->getSourceRange() << Param0->getType() 5351 << Context.getLValueReferenceType( 5352 Context.getRecordType(RD).withConst()); 5353 return false; 5354 } 5355 break; 5356 } 5357 5358 case CXXMoveConstructor: 5359 case CXXMoveAssignment: { 5360 // Trivial move operations always have non-cv-qualified parameters. 5361 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5362 const RValueReferenceType *RT = 5363 Param0->getType()->getAs<RValueReferenceType>(); 5364 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5365 if (Diagnose) 5366 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5367 << Param0->getSourceRange() << Param0->getType() 5368 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5369 return false; 5370 } 5371 break; 5372 } 5373 5374 case CXXInvalid: 5375 llvm_unreachable("not a special member"); 5376 } 5377 5378 // FIXME: We require that the parameter-declaration-clause is equivalent to 5379 // that of an implicit declaration, not just that the declared parameter type 5380 // matches, in order to prevent absuridities like a function simultaneously 5381 // being a trivial copy constructor and a non-trivial default constructor. 5382 // This issue has not yet been assigned a core issue number. 5383 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5384 if (Diagnose) 5385 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5386 diag::note_nontrivial_default_arg) 5387 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5388 return false; 5389 } 5390 if (MD->isVariadic()) { 5391 if (Diagnose) 5392 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5393 return false; 5394 } 5395 5396 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5397 // A copy/move [constructor or assignment operator] is trivial if 5398 // -- the [member] selected to copy/move each direct base class subobject 5399 // is trivial 5400 // 5401 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5402 // A [default constructor or destructor] is trivial if 5403 // -- all the direct base classes have trivial [default constructors or 5404 // destructors] 5405 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5406 BE = RD->bases_end(); BI != BE; ++BI) 5407 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5408 ConstArg ? BI->getType().withConst() 5409 : BI->getType(), 5410 CSM, TSK_BaseClass, Diagnose)) 5411 return false; 5412 5413 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5414 // A copy/move [constructor or assignment operator] for a class X is 5415 // trivial if 5416 // -- for each non-static data member of X that is of class type (or array 5417 // thereof), the constructor selected to copy/move that member is 5418 // trivial 5419 // 5420 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5421 // A [default constructor or destructor] is trivial if 5422 // -- for all of the non-static data members of its class that are of class 5423 // type (or array thereof), each such class has a trivial [default 5424 // constructor or destructor] 5425 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5426 return false; 5427 5428 // C++11 [class.dtor]p5: 5429 // A destructor is trivial if [...] 5430 // -- the destructor is not virtual 5431 if (CSM == CXXDestructor && MD->isVirtual()) { 5432 if (Diagnose) 5433 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5434 return false; 5435 } 5436 5437 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5438 // A [special member] for class X is trivial if [...] 5439 // -- class X has no virtual functions and no virtual base classes 5440 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5441 if (!Diagnose) 5442 return false; 5443 5444 if (RD->getNumVBases()) { 5445 // Check for virtual bases. We already know that the corresponding 5446 // member in all bases is trivial, so vbases must all be direct. 5447 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5448 assert(BS.isVirtual()); 5449 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5450 return false; 5451 } 5452 5453 // Must have a virtual method. 5454 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5455 ME = RD->method_end(); MI != ME; ++MI) { 5456 if (MI->isVirtual()) { 5457 SourceLocation MLoc = MI->getLocStart(); 5458 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5459 return false; 5460 } 5461 } 5462 5463 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5464 } 5465 5466 // Looks like it's trivial! 5467 return true; 5468} 5469 5470/// \brief Data used with FindHiddenVirtualMethod 5471namespace { 5472 struct FindHiddenVirtualMethodData { 5473 Sema *S; 5474 CXXMethodDecl *Method; 5475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5476 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5477 }; 5478} 5479 5480/// \brief Check whether any most overriden method from MD in Methods 5481static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5482 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5483 if (MD->size_overridden_methods() == 0) 5484 return Methods.count(MD->getCanonicalDecl()); 5485 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5486 E = MD->end_overridden_methods(); 5487 I != E; ++I) 5488 if (CheckMostOverridenMethods(*I, Methods)) 5489 return true; 5490 return false; 5491} 5492 5493/// \brief Member lookup function that determines whether a given C++ 5494/// method overloads virtual methods in a base class without overriding any, 5495/// to be used with CXXRecordDecl::lookupInBases(). 5496static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5497 CXXBasePath &Path, 5498 void *UserData) { 5499 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5500 5501 FindHiddenVirtualMethodData &Data 5502 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5503 5504 DeclarationName Name = Data.Method->getDeclName(); 5505 assert(Name.getNameKind() == DeclarationName::Identifier); 5506 5507 bool foundSameNameMethod = false; 5508 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5509 for (Path.Decls = BaseRecord->lookup(Name); 5510 !Path.Decls.empty(); 5511 Path.Decls = Path.Decls.slice(1)) { 5512 NamedDecl *D = Path.Decls.front(); 5513 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5514 MD = MD->getCanonicalDecl(); 5515 foundSameNameMethod = true; 5516 // Interested only in hidden virtual methods. 5517 if (!MD->isVirtual()) 5518 continue; 5519 // If the method we are checking overrides a method from its base 5520 // don't warn about the other overloaded methods. 5521 if (!Data.S->IsOverload(Data.Method, MD, false)) 5522 return true; 5523 // Collect the overload only if its hidden. 5524 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5525 overloadedMethods.push_back(MD); 5526 } 5527 } 5528 5529 if (foundSameNameMethod) 5530 Data.OverloadedMethods.append(overloadedMethods.begin(), 5531 overloadedMethods.end()); 5532 return foundSameNameMethod; 5533} 5534 5535/// \brief Add the most overriden methods from MD to Methods 5536static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5537 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5538 if (MD->size_overridden_methods() == 0) 5539 Methods.insert(MD->getCanonicalDecl()); 5540 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5541 E = MD->end_overridden_methods(); 5542 I != E; ++I) 5543 AddMostOverridenMethods(*I, Methods); 5544} 5545 5546/// \brief See if a method overloads virtual methods in a base class without 5547/// overriding any. 5548void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5549 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5550 MD->getLocation()) == DiagnosticsEngine::Ignored) 5551 return; 5552 if (!MD->getDeclName().isIdentifier()) 5553 return; 5554 5555 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5556 /*bool RecordPaths=*/false, 5557 /*bool DetectVirtual=*/false); 5558 FindHiddenVirtualMethodData Data; 5559 Data.Method = MD; 5560 Data.S = this; 5561 5562 // Keep the base methods that were overriden or introduced in the subclass 5563 // by 'using' in a set. A base method not in this set is hidden. 5564 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5565 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5566 NamedDecl *ND = *I; 5567 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5568 ND = shad->getTargetDecl(); 5569 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5570 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5571 } 5572 5573 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5574 !Data.OverloadedMethods.empty()) { 5575 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5576 << MD << (Data.OverloadedMethods.size() > 1); 5577 5578 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5579 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5580 PartialDiagnostic PD = PDiag( 5581 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5582 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5583 Diag(overloadedMD->getLocation(), PD); 5584 } 5585 } 5586} 5587 5588void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5589 Decl *TagDecl, 5590 SourceLocation LBrac, 5591 SourceLocation RBrac, 5592 AttributeList *AttrList) { 5593 if (!TagDecl) 5594 return; 5595 5596 AdjustDeclIfTemplate(TagDecl); 5597 5598 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5599 if (l->getKind() != AttributeList::AT_Visibility) 5600 continue; 5601 l->setInvalid(); 5602 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5603 l->getName(); 5604 } 5605 5606 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5607 // strict aliasing violation! 5608 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5609 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5610 5611 CheckCompletedCXXClass( 5612 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5613} 5614 5615/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5616/// special functions, such as the default constructor, copy 5617/// constructor, or destructor, to the given C++ class (C++ 5618/// [special]p1). This routine can only be executed just before the 5619/// definition of the class is complete. 5620void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5621 if (!ClassDecl->hasUserDeclaredConstructor()) 5622 ++ASTContext::NumImplicitDefaultConstructors; 5623 5624 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5625 ++ASTContext::NumImplicitCopyConstructors; 5626 5627 // If the properties or semantics of the copy constructor couldn't be 5628 // determined while the class was being declared, force a declaration 5629 // of it now. 5630 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5631 DeclareImplicitCopyConstructor(ClassDecl); 5632 } 5633 5634 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5635 ++ASTContext::NumImplicitMoveConstructors; 5636 5637 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5638 DeclareImplicitMoveConstructor(ClassDecl); 5639 } 5640 5641 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5642 ++ASTContext::NumImplicitCopyAssignmentOperators; 5643 5644 // If we have a dynamic class, then the copy assignment operator may be 5645 // virtual, so we have to declare it immediately. This ensures that, e.g., 5646 // it shows up in the right place in the vtable and that we diagnose 5647 // problems with the implicit exception specification. 5648 if (ClassDecl->isDynamicClass() || 5649 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5650 DeclareImplicitCopyAssignment(ClassDecl); 5651 } 5652 5653 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5654 ++ASTContext::NumImplicitMoveAssignmentOperators; 5655 5656 // Likewise for the move assignment operator. 5657 if (ClassDecl->isDynamicClass() || 5658 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5659 DeclareImplicitMoveAssignment(ClassDecl); 5660 } 5661 5662 if (!ClassDecl->hasUserDeclaredDestructor()) { 5663 ++ASTContext::NumImplicitDestructors; 5664 5665 // If we have a dynamic class, then the destructor may be virtual, so we 5666 // have to declare the destructor immediately. This ensures that, e.g., it 5667 // shows up in the right place in the vtable and that we diagnose problems 5668 // with the implicit exception specification. 5669 if (ClassDecl->isDynamicClass() || 5670 ClassDecl->needsOverloadResolutionForDestructor()) 5671 DeclareImplicitDestructor(ClassDecl); 5672 } 5673} 5674 5675void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5676 if (!D) 5677 return; 5678 5679 int NumParamList = D->getNumTemplateParameterLists(); 5680 for (int i = 0; i < NumParamList; i++) { 5681 TemplateParameterList* Params = D->getTemplateParameterList(i); 5682 for (TemplateParameterList::iterator Param = Params->begin(), 5683 ParamEnd = Params->end(); 5684 Param != ParamEnd; ++Param) { 5685 NamedDecl *Named = cast<NamedDecl>(*Param); 5686 if (Named->getDeclName()) { 5687 S->AddDecl(Named); 5688 IdResolver.AddDecl(Named); 5689 } 5690 } 5691 } 5692} 5693 5694void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5695 if (!D) 5696 return; 5697 5698 TemplateParameterList *Params = 0; 5699 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5700 Params = Template->getTemplateParameters(); 5701 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5702 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5703 Params = PartialSpec->getTemplateParameters(); 5704 else 5705 return; 5706 5707 for (TemplateParameterList::iterator Param = Params->begin(), 5708 ParamEnd = Params->end(); 5709 Param != ParamEnd; ++Param) { 5710 NamedDecl *Named = cast<NamedDecl>(*Param); 5711 if (Named->getDeclName()) { 5712 S->AddDecl(Named); 5713 IdResolver.AddDecl(Named); 5714 } 5715 } 5716} 5717 5718void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5719 if (!RecordD) return; 5720 AdjustDeclIfTemplate(RecordD); 5721 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5722 PushDeclContext(S, Record); 5723} 5724 5725void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5726 if (!RecordD) return; 5727 PopDeclContext(); 5728} 5729 5730/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5731/// parsing a top-level (non-nested) C++ class, and we are now 5732/// parsing those parts of the given Method declaration that could 5733/// not be parsed earlier (C++ [class.mem]p2), such as default 5734/// arguments. This action should enter the scope of the given 5735/// Method declaration as if we had just parsed the qualified method 5736/// name. However, it should not bring the parameters into scope; 5737/// that will be performed by ActOnDelayedCXXMethodParameter. 5738void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5739} 5740 5741/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5742/// C++ method declaration. We're (re-)introducing the given 5743/// function parameter into scope for use in parsing later parts of 5744/// the method declaration. For example, we could see an 5745/// ActOnParamDefaultArgument event for this parameter. 5746void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5747 if (!ParamD) 5748 return; 5749 5750 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5751 5752 // If this parameter has an unparsed default argument, clear it out 5753 // to make way for the parsed default argument. 5754 if (Param->hasUnparsedDefaultArg()) 5755 Param->setDefaultArg(0); 5756 5757 S->AddDecl(Param); 5758 if (Param->getDeclName()) 5759 IdResolver.AddDecl(Param); 5760} 5761 5762/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5763/// processing the delayed method declaration for Method. The method 5764/// declaration is now considered finished. There may be a separate 5765/// ActOnStartOfFunctionDef action later (not necessarily 5766/// immediately!) for this method, if it was also defined inside the 5767/// class body. 5768void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5769 if (!MethodD) 5770 return; 5771 5772 AdjustDeclIfTemplate(MethodD); 5773 5774 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5775 5776 // Now that we have our default arguments, check the constructor 5777 // again. It could produce additional diagnostics or affect whether 5778 // the class has implicitly-declared destructors, among other 5779 // things. 5780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5781 CheckConstructor(Constructor); 5782 5783 // Check the default arguments, which we may have added. 5784 if (!Method->isInvalidDecl()) 5785 CheckCXXDefaultArguments(Method); 5786} 5787 5788/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5789/// the well-formedness of the constructor declarator @p D with type @p 5790/// R. If there are any errors in the declarator, this routine will 5791/// emit diagnostics and set the invalid bit to true. In any case, the type 5792/// will be updated to reflect a well-formed type for the constructor and 5793/// returned. 5794QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5795 StorageClass &SC) { 5796 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5797 5798 // C++ [class.ctor]p3: 5799 // A constructor shall not be virtual (10.3) or static (9.4). A 5800 // constructor can be invoked for a const, volatile or const 5801 // volatile object. A constructor shall not be declared const, 5802 // volatile, or const volatile (9.3.2). 5803 if (isVirtual) { 5804 if (!D.isInvalidType()) 5805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5806 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5807 << SourceRange(D.getIdentifierLoc()); 5808 D.setInvalidType(); 5809 } 5810 if (SC == SC_Static) { 5811 if (!D.isInvalidType()) 5812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5814 << SourceRange(D.getIdentifierLoc()); 5815 D.setInvalidType(); 5816 SC = SC_None; 5817 } 5818 5819 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5820 if (FTI.TypeQuals != 0) { 5821 if (FTI.TypeQuals & Qualifiers::Const) 5822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5823 << "const" << SourceRange(D.getIdentifierLoc()); 5824 if (FTI.TypeQuals & Qualifiers::Volatile) 5825 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5826 << "volatile" << SourceRange(D.getIdentifierLoc()); 5827 if (FTI.TypeQuals & Qualifiers::Restrict) 5828 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5829 << "restrict" << SourceRange(D.getIdentifierLoc()); 5830 D.setInvalidType(); 5831 } 5832 5833 // C++0x [class.ctor]p4: 5834 // A constructor shall not be declared with a ref-qualifier. 5835 if (FTI.hasRefQualifier()) { 5836 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5837 << FTI.RefQualifierIsLValueRef 5838 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5839 D.setInvalidType(); 5840 } 5841 5842 // Rebuild the function type "R" without any type qualifiers (in 5843 // case any of the errors above fired) and with "void" as the 5844 // return type, since constructors don't have return types. 5845 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5846 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5847 return R; 5848 5849 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5850 EPI.TypeQuals = 0; 5851 EPI.RefQualifier = RQ_None; 5852 5853 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5854} 5855 5856/// CheckConstructor - Checks a fully-formed constructor for 5857/// well-formedness, issuing any diagnostics required. Returns true if 5858/// the constructor declarator is invalid. 5859void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5860 CXXRecordDecl *ClassDecl 5861 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5862 if (!ClassDecl) 5863 return Constructor->setInvalidDecl(); 5864 5865 // C++ [class.copy]p3: 5866 // A declaration of a constructor for a class X is ill-formed if 5867 // its first parameter is of type (optionally cv-qualified) X and 5868 // either there are no other parameters or else all other 5869 // parameters have default arguments. 5870 if (!Constructor->isInvalidDecl() && 5871 ((Constructor->getNumParams() == 1) || 5872 (Constructor->getNumParams() > 1 && 5873 Constructor->getParamDecl(1)->hasDefaultArg())) && 5874 Constructor->getTemplateSpecializationKind() 5875 != TSK_ImplicitInstantiation) { 5876 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5877 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5878 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5879 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5880 const char *ConstRef 5881 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5882 : " const &"; 5883 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5884 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5885 5886 // FIXME: Rather that making the constructor invalid, we should endeavor 5887 // to fix the type. 5888 Constructor->setInvalidDecl(); 5889 } 5890 } 5891} 5892 5893/// CheckDestructor - Checks a fully-formed destructor definition for 5894/// well-formedness, issuing any diagnostics required. Returns true 5895/// on error. 5896bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5897 CXXRecordDecl *RD = Destructor->getParent(); 5898 5899 if (Destructor->isVirtual()) { 5900 SourceLocation Loc; 5901 5902 if (!Destructor->isImplicit()) 5903 Loc = Destructor->getLocation(); 5904 else 5905 Loc = RD->getLocation(); 5906 5907 // If we have a virtual destructor, look up the deallocation function 5908 FunctionDecl *OperatorDelete = 0; 5909 DeclarationName Name = 5910 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5911 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5912 return true; 5913 5914 MarkFunctionReferenced(Loc, OperatorDelete); 5915 5916 Destructor->setOperatorDelete(OperatorDelete); 5917 } 5918 5919 return false; 5920} 5921 5922static inline bool 5923FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5924 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5925 FTI.ArgInfo[0].Param && 5926 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5927} 5928 5929/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5930/// the well-formednes of the destructor declarator @p D with type @p 5931/// R. If there are any errors in the declarator, this routine will 5932/// emit diagnostics and set the declarator to invalid. Even if this happens, 5933/// will be updated to reflect a well-formed type for the destructor and 5934/// returned. 5935QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5936 StorageClass& SC) { 5937 // C++ [class.dtor]p1: 5938 // [...] A typedef-name that names a class is a class-name 5939 // (7.1.3); however, a typedef-name that names a class shall not 5940 // be used as the identifier in the declarator for a destructor 5941 // declaration. 5942 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5943 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5944 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5945 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5946 else if (const TemplateSpecializationType *TST = 5947 DeclaratorType->getAs<TemplateSpecializationType>()) 5948 if (TST->isTypeAlias()) 5949 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5950 << DeclaratorType << 1; 5951 5952 // C++ [class.dtor]p2: 5953 // A destructor is used to destroy objects of its class type. A 5954 // destructor takes no parameters, and no return type can be 5955 // specified for it (not even void). The address of a destructor 5956 // shall not be taken. A destructor shall not be static. A 5957 // destructor can be invoked for a const, volatile or const 5958 // volatile object. A destructor shall not be declared const, 5959 // volatile or const volatile (9.3.2). 5960 if (SC == SC_Static) { 5961 if (!D.isInvalidType()) 5962 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5963 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5964 << SourceRange(D.getIdentifierLoc()) 5965 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5966 5967 SC = SC_None; 5968 } 5969 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5970 // Destructors don't have return types, but the parser will 5971 // happily parse something like: 5972 // 5973 // class X { 5974 // float ~X(); 5975 // }; 5976 // 5977 // The return type will be eliminated later. 5978 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5979 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5980 << SourceRange(D.getIdentifierLoc()); 5981 } 5982 5983 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5984 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5985 if (FTI.TypeQuals & Qualifiers::Const) 5986 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5987 << "const" << SourceRange(D.getIdentifierLoc()); 5988 if (FTI.TypeQuals & Qualifiers::Volatile) 5989 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5990 << "volatile" << SourceRange(D.getIdentifierLoc()); 5991 if (FTI.TypeQuals & Qualifiers::Restrict) 5992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5993 << "restrict" << SourceRange(D.getIdentifierLoc()); 5994 D.setInvalidType(); 5995 } 5996 5997 // C++0x [class.dtor]p2: 5998 // A destructor shall not be declared with a ref-qualifier. 5999 if (FTI.hasRefQualifier()) { 6000 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6001 << FTI.RefQualifierIsLValueRef 6002 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6003 D.setInvalidType(); 6004 } 6005 6006 // Make sure we don't have any parameters. 6007 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6008 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6009 6010 // Delete the parameters. 6011 FTI.freeArgs(); 6012 D.setInvalidType(); 6013 } 6014 6015 // Make sure the destructor isn't variadic. 6016 if (FTI.isVariadic) { 6017 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6018 D.setInvalidType(); 6019 } 6020 6021 // Rebuild the function type "R" without any type qualifiers or 6022 // parameters (in case any of the errors above fired) and with 6023 // "void" as the return type, since destructors don't have return 6024 // types. 6025 if (!D.isInvalidType()) 6026 return R; 6027 6028 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6029 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6030 EPI.Variadic = false; 6031 EPI.TypeQuals = 0; 6032 EPI.RefQualifier = RQ_None; 6033 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI); 6034} 6035 6036/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6037/// well-formednes of the conversion function declarator @p D with 6038/// type @p R. If there are any errors in the declarator, this routine 6039/// will emit diagnostics and return true. Otherwise, it will return 6040/// false. Either way, the type @p R will be updated to reflect a 6041/// well-formed type for the conversion operator. 6042void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6043 StorageClass& SC) { 6044 // C++ [class.conv.fct]p1: 6045 // Neither parameter types nor return type can be specified. The 6046 // type of a conversion function (8.3.5) is "function taking no 6047 // parameter returning conversion-type-id." 6048 if (SC == SC_Static) { 6049 if (!D.isInvalidType()) 6050 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6051 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6052 << SourceRange(D.getIdentifierLoc()); 6053 D.setInvalidType(); 6054 SC = SC_None; 6055 } 6056 6057 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6058 6059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6060 // Conversion functions don't have return types, but the parser will 6061 // happily parse something like: 6062 // 6063 // class X { 6064 // float operator bool(); 6065 // }; 6066 // 6067 // The return type will be changed later anyway. 6068 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6070 << SourceRange(D.getIdentifierLoc()); 6071 D.setInvalidType(); 6072 } 6073 6074 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6075 6076 // Make sure we don't have any parameters. 6077 if (Proto->getNumArgs() > 0) { 6078 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6079 6080 // Delete the parameters. 6081 D.getFunctionTypeInfo().freeArgs(); 6082 D.setInvalidType(); 6083 } else if (Proto->isVariadic()) { 6084 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6085 D.setInvalidType(); 6086 } 6087 6088 // Diagnose "&operator bool()" and other such nonsense. This 6089 // is actually a gcc extension which we don't support. 6090 if (Proto->getResultType() != ConvType) { 6091 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6092 << Proto->getResultType(); 6093 D.setInvalidType(); 6094 ConvType = Proto->getResultType(); 6095 } 6096 6097 // C++ [class.conv.fct]p4: 6098 // The conversion-type-id shall not represent a function type nor 6099 // an array type. 6100 if (ConvType->isArrayType()) { 6101 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6102 ConvType = Context.getPointerType(ConvType); 6103 D.setInvalidType(); 6104 } else if (ConvType->isFunctionType()) { 6105 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6106 ConvType = Context.getPointerType(ConvType); 6107 D.setInvalidType(); 6108 } 6109 6110 // Rebuild the function type "R" without any parameters (in case any 6111 // of the errors above fired) and with the conversion type as the 6112 // return type. 6113 if (D.isInvalidType()) 6114 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(), 6115 Proto->getExtProtoInfo()); 6116 6117 // C++0x explicit conversion operators. 6118 if (D.getDeclSpec().isExplicitSpecified()) 6119 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6120 getLangOpts().CPlusPlus11 ? 6121 diag::warn_cxx98_compat_explicit_conversion_functions : 6122 diag::ext_explicit_conversion_functions) 6123 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6124} 6125 6126/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6127/// the declaration of the given C++ conversion function. This routine 6128/// is responsible for recording the conversion function in the C++ 6129/// class, if possible. 6130Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6131 assert(Conversion && "Expected to receive a conversion function declaration"); 6132 6133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6134 6135 // Make sure we aren't redeclaring the conversion function. 6136 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6137 6138 // C++ [class.conv.fct]p1: 6139 // [...] A conversion function is never used to convert a 6140 // (possibly cv-qualified) object to the (possibly cv-qualified) 6141 // same object type (or a reference to it), to a (possibly 6142 // cv-qualified) base class of that type (or a reference to it), 6143 // or to (possibly cv-qualified) void. 6144 // FIXME: Suppress this warning if the conversion function ends up being a 6145 // virtual function that overrides a virtual function in a base class. 6146 QualType ClassType 6147 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6148 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6149 ConvType = ConvTypeRef->getPointeeType(); 6150 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6151 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6152 /* Suppress diagnostics for instantiations. */; 6153 else if (ConvType->isRecordType()) { 6154 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6155 if (ConvType == ClassType) 6156 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6157 << ClassType; 6158 else if (IsDerivedFrom(ClassType, ConvType)) 6159 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6160 << ClassType << ConvType; 6161 } else if (ConvType->isVoidType()) { 6162 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6163 << ClassType << ConvType; 6164 } 6165 6166 if (FunctionTemplateDecl *ConversionTemplate 6167 = Conversion->getDescribedFunctionTemplate()) 6168 return ConversionTemplate; 6169 6170 return Conversion; 6171} 6172 6173//===----------------------------------------------------------------------===// 6174// Namespace Handling 6175//===----------------------------------------------------------------------===// 6176 6177/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6178/// reopened. 6179static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6180 SourceLocation Loc, 6181 IdentifierInfo *II, bool *IsInline, 6182 NamespaceDecl *PrevNS) { 6183 assert(*IsInline != PrevNS->isInline()); 6184 6185 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6186 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6187 // inline namespaces, with the intention of bringing names into namespace std. 6188 // 6189 // We support this just well enough to get that case working; this is not 6190 // sufficient to support reopening namespaces as inline in general. 6191 if (*IsInline && II && II->getName().startswith("__atomic") && 6192 S.getSourceManager().isInSystemHeader(Loc)) { 6193 // Mark all prior declarations of the namespace as inline. 6194 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6195 NS = NS->getPreviousDecl()) 6196 NS->setInline(*IsInline); 6197 // Patch up the lookup table for the containing namespace. This isn't really 6198 // correct, but it's good enough for this particular case. 6199 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6200 E = PrevNS->decls_end(); I != E; ++I) 6201 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6202 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6203 return; 6204 } 6205 6206 if (PrevNS->isInline()) 6207 // The user probably just forgot the 'inline', so suggest that it 6208 // be added back. 6209 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6210 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6211 else 6212 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6213 << IsInline; 6214 6215 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6216 *IsInline = PrevNS->isInline(); 6217} 6218 6219/// ActOnStartNamespaceDef - This is called at the start of a namespace 6220/// definition. 6221Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6222 SourceLocation InlineLoc, 6223 SourceLocation NamespaceLoc, 6224 SourceLocation IdentLoc, 6225 IdentifierInfo *II, 6226 SourceLocation LBrace, 6227 AttributeList *AttrList) { 6228 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6229 // For anonymous namespace, take the location of the left brace. 6230 SourceLocation Loc = II ? IdentLoc : LBrace; 6231 bool IsInline = InlineLoc.isValid(); 6232 bool IsInvalid = false; 6233 bool IsStd = false; 6234 bool AddToKnown = false; 6235 Scope *DeclRegionScope = NamespcScope->getParent(); 6236 6237 NamespaceDecl *PrevNS = 0; 6238 if (II) { 6239 // C++ [namespace.def]p2: 6240 // The identifier in an original-namespace-definition shall not 6241 // have been previously defined in the declarative region in 6242 // which the original-namespace-definition appears. The 6243 // identifier in an original-namespace-definition is the name of 6244 // the namespace. Subsequently in that declarative region, it is 6245 // treated as an original-namespace-name. 6246 // 6247 // Since namespace names are unique in their scope, and we don't 6248 // look through using directives, just look for any ordinary names. 6249 6250 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6251 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6252 Decl::IDNS_Namespace; 6253 NamedDecl *PrevDecl = 0; 6254 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6255 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6256 ++I) { 6257 if ((*I)->getIdentifierNamespace() & IDNS) { 6258 PrevDecl = *I; 6259 break; 6260 } 6261 } 6262 6263 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6264 6265 if (PrevNS) { 6266 // This is an extended namespace definition. 6267 if (IsInline != PrevNS->isInline()) 6268 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6269 &IsInline, PrevNS); 6270 } else if (PrevDecl) { 6271 // This is an invalid name redefinition. 6272 Diag(Loc, diag::err_redefinition_different_kind) 6273 << II; 6274 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6275 IsInvalid = true; 6276 // Continue on to push Namespc as current DeclContext and return it. 6277 } else if (II->isStr("std") && 6278 CurContext->getRedeclContext()->isTranslationUnit()) { 6279 // This is the first "real" definition of the namespace "std", so update 6280 // our cache of the "std" namespace to point at this definition. 6281 PrevNS = getStdNamespace(); 6282 IsStd = true; 6283 AddToKnown = !IsInline; 6284 } else { 6285 // We've seen this namespace for the first time. 6286 AddToKnown = !IsInline; 6287 } 6288 } else { 6289 // Anonymous namespaces. 6290 6291 // Determine whether the parent already has an anonymous namespace. 6292 DeclContext *Parent = CurContext->getRedeclContext(); 6293 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6294 PrevNS = TU->getAnonymousNamespace(); 6295 } else { 6296 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6297 PrevNS = ND->getAnonymousNamespace(); 6298 } 6299 6300 if (PrevNS && IsInline != PrevNS->isInline()) 6301 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6302 &IsInline, PrevNS); 6303 } 6304 6305 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6306 StartLoc, Loc, II, PrevNS); 6307 if (IsInvalid) 6308 Namespc->setInvalidDecl(); 6309 6310 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6311 6312 // FIXME: Should we be merging attributes? 6313 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6314 PushNamespaceVisibilityAttr(Attr, Loc); 6315 6316 if (IsStd) 6317 StdNamespace = Namespc; 6318 if (AddToKnown) 6319 KnownNamespaces[Namespc] = false; 6320 6321 if (II) { 6322 PushOnScopeChains(Namespc, DeclRegionScope); 6323 } else { 6324 // Link the anonymous namespace into its parent. 6325 DeclContext *Parent = CurContext->getRedeclContext(); 6326 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6327 TU->setAnonymousNamespace(Namespc); 6328 } else { 6329 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6330 } 6331 6332 CurContext->addDecl(Namespc); 6333 6334 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6335 // behaves as if it were replaced by 6336 // namespace unique { /* empty body */ } 6337 // using namespace unique; 6338 // namespace unique { namespace-body } 6339 // where all occurrences of 'unique' in a translation unit are 6340 // replaced by the same identifier and this identifier differs 6341 // from all other identifiers in the entire program. 6342 6343 // We just create the namespace with an empty name and then add an 6344 // implicit using declaration, just like the standard suggests. 6345 // 6346 // CodeGen enforces the "universally unique" aspect by giving all 6347 // declarations semantically contained within an anonymous 6348 // namespace internal linkage. 6349 6350 if (!PrevNS) { 6351 UsingDirectiveDecl* UD 6352 = UsingDirectiveDecl::Create(Context, Parent, 6353 /* 'using' */ LBrace, 6354 /* 'namespace' */ SourceLocation(), 6355 /* qualifier */ NestedNameSpecifierLoc(), 6356 /* identifier */ SourceLocation(), 6357 Namespc, 6358 /* Ancestor */ Parent); 6359 UD->setImplicit(); 6360 Parent->addDecl(UD); 6361 } 6362 } 6363 6364 ActOnDocumentableDecl(Namespc); 6365 6366 // Although we could have an invalid decl (i.e. the namespace name is a 6367 // redefinition), push it as current DeclContext and try to continue parsing. 6368 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6369 // for the namespace has the declarations that showed up in that particular 6370 // namespace definition. 6371 PushDeclContext(NamespcScope, Namespc); 6372 return Namespc; 6373} 6374 6375/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6376/// is a namespace alias, returns the namespace it points to. 6377static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6378 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6379 return AD->getNamespace(); 6380 return dyn_cast_or_null<NamespaceDecl>(D); 6381} 6382 6383/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6384/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6385void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6386 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6387 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6388 Namespc->setRBraceLoc(RBrace); 6389 PopDeclContext(); 6390 if (Namespc->hasAttr<VisibilityAttr>()) 6391 PopPragmaVisibility(true, RBrace); 6392} 6393 6394CXXRecordDecl *Sema::getStdBadAlloc() const { 6395 return cast_or_null<CXXRecordDecl>( 6396 StdBadAlloc.get(Context.getExternalSource())); 6397} 6398 6399NamespaceDecl *Sema::getStdNamespace() const { 6400 return cast_or_null<NamespaceDecl>( 6401 StdNamespace.get(Context.getExternalSource())); 6402} 6403 6404/// \brief Retrieve the special "std" namespace, which may require us to 6405/// implicitly define the namespace. 6406NamespaceDecl *Sema::getOrCreateStdNamespace() { 6407 if (!StdNamespace) { 6408 // The "std" namespace has not yet been defined, so build one implicitly. 6409 StdNamespace = NamespaceDecl::Create(Context, 6410 Context.getTranslationUnitDecl(), 6411 /*Inline=*/false, 6412 SourceLocation(), SourceLocation(), 6413 &PP.getIdentifierTable().get("std"), 6414 /*PrevDecl=*/0); 6415 getStdNamespace()->setImplicit(true); 6416 } 6417 6418 return getStdNamespace(); 6419} 6420 6421bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6422 assert(getLangOpts().CPlusPlus && 6423 "Looking for std::initializer_list outside of C++."); 6424 6425 // We're looking for implicit instantiations of 6426 // template <typename E> class std::initializer_list. 6427 6428 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6429 return false; 6430 6431 ClassTemplateDecl *Template = 0; 6432 const TemplateArgument *Arguments = 0; 6433 6434 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6435 6436 ClassTemplateSpecializationDecl *Specialization = 6437 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6438 if (!Specialization) 6439 return false; 6440 6441 Template = Specialization->getSpecializedTemplate(); 6442 Arguments = Specialization->getTemplateArgs().data(); 6443 } else if (const TemplateSpecializationType *TST = 6444 Ty->getAs<TemplateSpecializationType>()) { 6445 Template = dyn_cast_or_null<ClassTemplateDecl>( 6446 TST->getTemplateName().getAsTemplateDecl()); 6447 Arguments = TST->getArgs(); 6448 } 6449 if (!Template) 6450 return false; 6451 6452 if (!StdInitializerList) { 6453 // Haven't recognized std::initializer_list yet, maybe this is it. 6454 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6455 if (TemplateClass->getIdentifier() != 6456 &PP.getIdentifierTable().get("initializer_list") || 6457 !getStdNamespace()->InEnclosingNamespaceSetOf( 6458 TemplateClass->getDeclContext())) 6459 return false; 6460 // This is a template called std::initializer_list, but is it the right 6461 // template? 6462 TemplateParameterList *Params = Template->getTemplateParameters(); 6463 if (Params->getMinRequiredArguments() != 1) 6464 return false; 6465 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6466 return false; 6467 6468 // It's the right template. 6469 StdInitializerList = Template; 6470 } 6471 6472 if (Template != StdInitializerList) 6473 return false; 6474 6475 // This is an instance of std::initializer_list. Find the argument type. 6476 if (Element) 6477 *Element = Arguments[0].getAsType(); 6478 return true; 6479} 6480 6481static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6482 NamespaceDecl *Std = S.getStdNamespace(); 6483 if (!Std) { 6484 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6485 return 0; 6486 } 6487 6488 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6489 Loc, Sema::LookupOrdinaryName); 6490 if (!S.LookupQualifiedName(Result, Std)) { 6491 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6492 return 0; 6493 } 6494 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6495 if (!Template) { 6496 Result.suppressDiagnostics(); 6497 // We found something weird. Complain about the first thing we found. 6498 NamedDecl *Found = *Result.begin(); 6499 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6500 return 0; 6501 } 6502 6503 // We found some template called std::initializer_list. Now verify that it's 6504 // correct. 6505 TemplateParameterList *Params = Template->getTemplateParameters(); 6506 if (Params->getMinRequiredArguments() != 1 || 6507 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6508 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6509 return 0; 6510 } 6511 6512 return Template; 6513} 6514 6515QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6516 if (!StdInitializerList) { 6517 StdInitializerList = LookupStdInitializerList(*this, Loc); 6518 if (!StdInitializerList) 6519 return QualType(); 6520 } 6521 6522 TemplateArgumentListInfo Args(Loc, Loc); 6523 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6524 Context.getTrivialTypeSourceInfo(Element, 6525 Loc))); 6526 return Context.getCanonicalType( 6527 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6528} 6529 6530bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6531 // C++ [dcl.init.list]p2: 6532 // A constructor is an initializer-list constructor if its first parameter 6533 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6534 // std::initializer_list<E> for some type E, and either there are no other 6535 // parameters or else all other parameters have default arguments. 6536 if (Ctor->getNumParams() < 1 || 6537 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6538 return false; 6539 6540 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6541 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6542 ArgType = RT->getPointeeType().getUnqualifiedType(); 6543 6544 return isStdInitializerList(ArgType, 0); 6545} 6546 6547/// \brief Determine whether a using statement is in a context where it will be 6548/// apply in all contexts. 6549static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6550 switch (CurContext->getDeclKind()) { 6551 case Decl::TranslationUnit: 6552 return true; 6553 case Decl::LinkageSpec: 6554 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6555 default: 6556 return false; 6557 } 6558} 6559 6560namespace { 6561 6562// Callback to only accept typo corrections that are namespaces. 6563class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6564 public: 6565 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6566 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6567 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6568 } 6569 return false; 6570 } 6571}; 6572 6573} 6574 6575static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6576 CXXScopeSpec &SS, 6577 SourceLocation IdentLoc, 6578 IdentifierInfo *Ident) { 6579 NamespaceValidatorCCC Validator; 6580 R.clear(); 6581 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6582 R.getLookupKind(), Sc, &SS, 6583 Validator)) { 6584 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6585 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6586 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6587 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6588 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6589 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6590 CorrectedStr); 6591 else 6592 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6593 << Ident << CorrectedQuotedStr 6594 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6595 6596 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6597 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6598 6599 R.addDecl(Corrected.getCorrectionDecl()); 6600 return true; 6601 } 6602 return false; 6603} 6604 6605Decl *Sema::ActOnUsingDirective(Scope *S, 6606 SourceLocation UsingLoc, 6607 SourceLocation NamespcLoc, 6608 CXXScopeSpec &SS, 6609 SourceLocation IdentLoc, 6610 IdentifierInfo *NamespcName, 6611 AttributeList *AttrList) { 6612 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6613 assert(NamespcName && "Invalid NamespcName."); 6614 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6615 6616 // This can only happen along a recovery path. 6617 while (S->getFlags() & Scope::TemplateParamScope) 6618 S = S->getParent(); 6619 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6620 6621 UsingDirectiveDecl *UDir = 0; 6622 NestedNameSpecifier *Qualifier = 0; 6623 if (SS.isSet()) 6624 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6625 6626 // Lookup namespace name. 6627 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6628 LookupParsedName(R, S, &SS); 6629 if (R.isAmbiguous()) 6630 return 0; 6631 6632 if (R.empty()) { 6633 R.clear(); 6634 // Allow "using namespace std;" or "using namespace ::std;" even if 6635 // "std" hasn't been defined yet, for GCC compatibility. 6636 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6637 NamespcName->isStr("std")) { 6638 Diag(IdentLoc, diag::ext_using_undefined_std); 6639 R.addDecl(getOrCreateStdNamespace()); 6640 R.resolveKind(); 6641 } 6642 // Otherwise, attempt typo correction. 6643 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6644 } 6645 6646 if (!R.empty()) { 6647 NamedDecl *Named = R.getFoundDecl(); 6648 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6649 && "expected namespace decl"); 6650 // C++ [namespace.udir]p1: 6651 // A using-directive specifies that the names in the nominated 6652 // namespace can be used in the scope in which the 6653 // using-directive appears after the using-directive. During 6654 // unqualified name lookup (3.4.1), the names appear as if they 6655 // were declared in the nearest enclosing namespace which 6656 // contains both the using-directive and the nominated 6657 // namespace. [Note: in this context, "contains" means "contains 6658 // directly or indirectly". ] 6659 6660 // Find enclosing context containing both using-directive and 6661 // nominated namespace. 6662 NamespaceDecl *NS = getNamespaceDecl(Named); 6663 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6664 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6665 CommonAncestor = CommonAncestor->getParent(); 6666 6667 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6668 SS.getWithLocInContext(Context), 6669 IdentLoc, Named, CommonAncestor); 6670 6671 if (IsUsingDirectiveInToplevelContext(CurContext) && 6672 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6673 Diag(IdentLoc, diag::warn_using_directive_in_header); 6674 } 6675 6676 PushUsingDirective(S, UDir); 6677 } else { 6678 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6679 } 6680 6681 if (UDir) 6682 ProcessDeclAttributeList(S, UDir, AttrList); 6683 6684 return UDir; 6685} 6686 6687void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6688 // If the scope has an associated entity and the using directive is at 6689 // namespace or translation unit scope, add the UsingDirectiveDecl into 6690 // its lookup structure so qualified name lookup can find it. 6691 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6692 if (Ctx && !Ctx->isFunctionOrMethod()) 6693 Ctx->addDecl(UDir); 6694 else 6695 // Otherwise, it is at block sope. The using-directives will affect lookup 6696 // only to the end of the scope. 6697 S->PushUsingDirective(UDir); 6698} 6699 6700 6701Decl *Sema::ActOnUsingDeclaration(Scope *S, 6702 AccessSpecifier AS, 6703 bool HasUsingKeyword, 6704 SourceLocation UsingLoc, 6705 CXXScopeSpec &SS, 6706 UnqualifiedId &Name, 6707 AttributeList *AttrList, 6708 bool IsTypeName, 6709 SourceLocation TypenameLoc) { 6710 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6711 6712 switch (Name.getKind()) { 6713 case UnqualifiedId::IK_ImplicitSelfParam: 6714 case UnqualifiedId::IK_Identifier: 6715 case UnqualifiedId::IK_OperatorFunctionId: 6716 case UnqualifiedId::IK_LiteralOperatorId: 6717 case UnqualifiedId::IK_ConversionFunctionId: 6718 break; 6719 6720 case UnqualifiedId::IK_ConstructorName: 6721 case UnqualifiedId::IK_ConstructorTemplateId: 6722 // C++11 inheriting constructors. 6723 Diag(Name.getLocStart(), 6724 getLangOpts().CPlusPlus11 ? 6725 diag::warn_cxx98_compat_using_decl_constructor : 6726 diag::err_using_decl_constructor) 6727 << SS.getRange(); 6728 6729 if (getLangOpts().CPlusPlus11) break; 6730 6731 return 0; 6732 6733 case UnqualifiedId::IK_DestructorName: 6734 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6735 << SS.getRange(); 6736 return 0; 6737 6738 case UnqualifiedId::IK_TemplateId: 6739 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6740 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6741 return 0; 6742 } 6743 6744 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6745 DeclarationName TargetName = TargetNameInfo.getName(); 6746 if (!TargetName) 6747 return 0; 6748 6749 // Warn about access declarations. 6750 // TODO: store that the declaration was written without 'using' and 6751 // talk about access decls instead of using decls in the 6752 // diagnostics. 6753 if (!HasUsingKeyword) { 6754 UsingLoc = Name.getLocStart(); 6755 6756 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6757 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6758 } 6759 6760 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6761 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6762 return 0; 6763 6764 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6765 TargetNameInfo, AttrList, 6766 /* IsInstantiation */ false, 6767 IsTypeName, TypenameLoc); 6768 if (UD) 6769 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6770 6771 return UD; 6772} 6773 6774/// \brief Determine whether a using declaration considers the given 6775/// declarations as "equivalent", e.g., if they are redeclarations of 6776/// the same entity or are both typedefs of the same type. 6777static bool 6778IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6779 bool &SuppressRedeclaration) { 6780 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6781 SuppressRedeclaration = false; 6782 return true; 6783 } 6784 6785 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6786 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6787 SuppressRedeclaration = true; 6788 return Context.hasSameType(TD1->getUnderlyingType(), 6789 TD2->getUnderlyingType()); 6790 } 6791 6792 return false; 6793} 6794 6795 6796/// Determines whether to create a using shadow decl for a particular 6797/// decl, given the set of decls existing prior to this using lookup. 6798bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6799 const LookupResult &Previous) { 6800 // Diagnose finding a decl which is not from a base class of the 6801 // current class. We do this now because there are cases where this 6802 // function will silently decide not to build a shadow decl, which 6803 // will pre-empt further diagnostics. 6804 // 6805 // We don't need to do this in C++0x because we do the check once on 6806 // the qualifier. 6807 // 6808 // FIXME: diagnose the following if we care enough: 6809 // struct A { int foo; }; 6810 // struct B : A { using A::foo; }; 6811 // template <class T> struct C : A {}; 6812 // template <class T> struct D : C<T> { using B::foo; } // <--- 6813 // This is invalid (during instantiation) in C++03 because B::foo 6814 // resolves to the using decl in B, which is not a base class of D<T>. 6815 // We can't diagnose it immediately because C<T> is an unknown 6816 // specialization. The UsingShadowDecl in D<T> then points directly 6817 // to A::foo, which will look well-formed when we instantiate. 6818 // The right solution is to not collapse the shadow-decl chain. 6819 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6820 DeclContext *OrigDC = Orig->getDeclContext(); 6821 6822 // Handle enums and anonymous structs. 6823 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6824 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6825 while (OrigRec->isAnonymousStructOrUnion()) 6826 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6827 6828 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6829 if (OrigDC == CurContext) { 6830 Diag(Using->getLocation(), 6831 diag::err_using_decl_nested_name_specifier_is_current_class) 6832 << Using->getQualifierLoc().getSourceRange(); 6833 Diag(Orig->getLocation(), diag::note_using_decl_target); 6834 return true; 6835 } 6836 6837 Diag(Using->getQualifierLoc().getBeginLoc(), 6838 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6839 << Using->getQualifier() 6840 << cast<CXXRecordDecl>(CurContext) 6841 << Using->getQualifierLoc().getSourceRange(); 6842 Diag(Orig->getLocation(), diag::note_using_decl_target); 6843 return true; 6844 } 6845 } 6846 6847 if (Previous.empty()) return false; 6848 6849 NamedDecl *Target = Orig; 6850 if (isa<UsingShadowDecl>(Target)) 6851 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6852 6853 // If the target happens to be one of the previous declarations, we 6854 // don't have a conflict. 6855 // 6856 // FIXME: but we might be increasing its access, in which case we 6857 // should redeclare it. 6858 NamedDecl *NonTag = 0, *Tag = 0; 6859 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6860 I != E; ++I) { 6861 NamedDecl *D = (*I)->getUnderlyingDecl(); 6862 bool Result; 6863 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6864 return Result; 6865 6866 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6867 } 6868 6869 if (Target->isFunctionOrFunctionTemplate()) { 6870 FunctionDecl *FD; 6871 if (isa<FunctionTemplateDecl>(Target)) 6872 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6873 else 6874 FD = cast<FunctionDecl>(Target); 6875 6876 NamedDecl *OldDecl = 0; 6877 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6878 case Ovl_Overload: 6879 return false; 6880 6881 case Ovl_NonFunction: 6882 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6883 break; 6884 6885 // We found a decl with the exact signature. 6886 case Ovl_Match: 6887 // If we're in a record, we want to hide the target, so we 6888 // return true (without a diagnostic) to tell the caller not to 6889 // build a shadow decl. 6890 if (CurContext->isRecord()) 6891 return true; 6892 6893 // If we're not in a record, this is an error. 6894 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6895 break; 6896 } 6897 6898 Diag(Target->getLocation(), diag::note_using_decl_target); 6899 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6900 return true; 6901 } 6902 6903 // Target is not a function. 6904 6905 if (isa<TagDecl>(Target)) { 6906 // No conflict between a tag and a non-tag. 6907 if (!Tag) return false; 6908 6909 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6910 Diag(Target->getLocation(), diag::note_using_decl_target); 6911 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6912 return true; 6913 } 6914 6915 // No conflict between a tag and a non-tag. 6916 if (!NonTag) return false; 6917 6918 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6919 Diag(Target->getLocation(), diag::note_using_decl_target); 6920 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6921 return true; 6922} 6923 6924/// Builds a shadow declaration corresponding to a 'using' declaration. 6925UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6926 UsingDecl *UD, 6927 NamedDecl *Orig) { 6928 6929 // If we resolved to another shadow declaration, just coalesce them. 6930 NamedDecl *Target = Orig; 6931 if (isa<UsingShadowDecl>(Target)) { 6932 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6933 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6934 } 6935 6936 UsingShadowDecl *Shadow 6937 = UsingShadowDecl::Create(Context, CurContext, 6938 UD->getLocation(), UD, Target); 6939 UD->addShadowDecl(Shadow); 6940 6941 Shadow->setAccess(UD->getAccess()); 6942 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6943 Shadow->setInvalidDecl(); 6944 6945 if (S) 6946 PushOnScopeChains(Shadow, S); 6947 else 6948 CurContext->addDecl(Shadow); 6949 6950 6951 return Shadow; 6952} 6953 6954/// Hides a using shadow declaration. This is required by the current 6955/// using-decl implementation when a resolvable using declaration in a 6956/// class is followed by a declaration which would hide or override 6957/// one or more of the using decl's targets; for example: 6958/// 6959/// struct Base { void foo(int); }; 6960/// struct Derived : Base { 6961/// using Base::foo; 6962/// void foo(int); 6963/// }; 6964/// 6965/// The governing language is C++03 [namespace.udecl]p12: 6966/// 6967/// When a using-declaration brings names from a base class into a 6968/// derived class scope, member functions in the derived class 6969/// override and/or hide member functions with the same name and 6970/// parameter types in a base class (rather than conflicting). 6971/// 6972/// There are two ways to implement this: 6973/// (1) optimistically create shadow decls when they're not hidden 6974/// by existing declarations, or 6975/// (2) don't create any shadow decls (or at least don't make them 6976/// visible) until we've fully parsed/instantiated the class. 6977/// The problem with (1) is that we might have to retroactively remove 6978/// a shadow decl, which requires several O(n) operations because the 6979/// decl structures are (very reasonably) not designed for removal. 6980/// (2) avoids this but is very fiddly and phase-dependent. 6981void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6982 if (Shadow->getDeclName().getNameKind() == 6983 DeclarationName::CXXConversionFunctionName) 6984 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6985 6986 // Remove it from the DeclContext... 6987 Shadow->getDeclContext()->removeDecl(Shadow); 6988 6989 // ...and the scope, if applicable... 6990 if (S) { 6991 S->RemoveDecl(Shadow); 6992 IdResolver.RemoveDecl(Shadow); 6993 } 6994 6995 // ...and the using decl. 6996 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6997 6998 // TODO: complain somehow if Shadow was used. It shouldn't 6999 // be possible for this to happen, because...? 7000} 7001 7002/// Builds a using declaration. 7003/// 7004/// \param IsInstantiation - Whether this call arises from an 7005/// instantiation of an unresolved using declaration. We treat 7006/// the lookup differently for these declarations. 7007NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7008 SourceLocation UsingLoc, 7009 CXXScopeSpec &SS, 7010 const DeclarationNameInfo &NameInfo, 7011 AttributeList *AttrList, 7012 bool IsInstantiation, 7013 bool IsTypeName, 7014 SourceLocation TypenameLoc) { 7015 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7016 SourceLocation IdentLoc = NameInfo.getLoc(); 7017 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7018 7019 // FIXME: We ignore attributes for now. 7020 7021 if (SS.isEmpty()) { 7022 Diag(IdentLoc, diag::err_using_requires_qualname); 7023 return 0; 7024 } 7025 7026 // Do the redeclaration lookup in the current scope. 7027 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7028 ForRedeclaration); 7029 Previous.setHideTags(false); 7030 if (S) { 7031 LookupName(Previous, S); 7032 7033 // It is really dumb that we have to do this. 7034 LookupResult::Filter F = Previous.makeFilter(); 7035 while (F.hasNext()) { 7036 NamedDecl *D = F.next(); 7037 if (!isDeclInScope(D, CurContext, S)) 7038 F.erase(); 7039 } 7040 F.done(); 7041 } else { 7042 assert(IsInstantiation && "no scope in non-instantiation"); 7043 assert(CurContext->isRecord() && "scope not record in instantiation"); 7044 LookupQualifiedName(Previous, CurContext); 7045 } 7046 7047 // Check for invalid redeclarations. 7048 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 7049 return 0; 7050 7051 // Check for bad qualifiers. 7052 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7053 return 0; 7054 7055 DeclContext *LookupContext = computeDeclContext(SS); 7056 NamedDecl *D; 7057 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7058 if (!LookupContext) { 7059 if (IsTypeName) { 7060 // FIXME: not all declaration name kinds are legal here 7061 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7062 UsingLoc, TypenameLoc, 7063 QualifierLoc, 7064 IdentLoc, NameInfo.getName()); 7065 } else { 7066 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7067 QualifierLoc, NameInfo); 7068 } 7069 } else { 7070 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7071 NameInfo, IsTypeName); 7072 } 7073 D->setAccess(AS); 7074 CurContext->addDecl(D); 7075 7076 if (!LookupContext) return D; 7077 UsingDecl *UD = cast<UsingDecl>(D); 7078 7079 if (RequireCompleteDeclContext(SS, LookupContext)) { 7080 UD->setInvalidDecl(); 7081 return UD; 7082 } 7083 7084 // The normal rules do not apply to inheriting constructor declarations. 7085 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7086 if (CheckInheritingConstructorUsingDecl(UD)) 7087 UD->setInvalidDecl(); 7088 return UD; 7089 } 7090 7091 // Otherwise, look up the target name. 7092 7093 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7094 7095 // Unlike most lookups, we don't always want to hide tag 7096 // declarations: tag names are visible through the using declaration 7097 // even if hidden by ordinary names, *except* in a dependent context 7098 // where it's important for the sanity of two-phase lookup. 7099 if (!IsInstantiation) 7100 R.setHideTags(false); 7101 7102 // For the purposes of this lookup, we have a base object type 7103 // equal to that of the current context. 7104 if (CurContext->isRecord()) { 7105 R.setBaseObjectType( 7106 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7107 } 7108 7109 LookupQualifiedName(R, LookupContext); 7110 7111 if (R.empty()) { 7112 Diag(IdentLoc, diag::err_no_member) 7113 << NameInfo.getName() << LookupContext << SS.getRange(); 7114 UD->setInvalidDecl(); 7115 return UD; 7116 } 7117 7118 if (R.isAmbiguous()) { 7119 UD->setInvalidDecl(); 7120 return UD; 7121 } 7122 7123 if (IsTypeName) { 7124 // If we asked for a typename and got a non-type decl, error out. 7125 if (!R.getAsSingle<TypeDecl>()) { 7126 Diag(IdentLoc, diag::err_using_typename_non_type); 7127 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7128 Diag((*I)->getUnderlyingDecl()->getLocation(), 7129 diag::note_using_decl_target); 7130 UD->setInvalidDecl(); 7131 return UD; 7132 } 7133 } else { 7134 // If we asked for a non-typename and we got a type, error out, 7135 // but only if this is an instantiation of an unresolved using 7136 // decl. Otherwise just silently find the type name. 7137 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7138 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7139 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7140 UD->setInvalidDecl(); 7141 return UD; 7142 } 7143 } 7144 7145 // C++0x N2914 [namespace.udecl]p6: 7146 // A using-declaration shall not name a namespace. 7147 if (R.getAsSingle<NamespaceDecl>()) { 7148 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7149 << SS.getRange(); 7150 UD->setInvalidDecl(); 7151 return UD; 7152 } 7153 7154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7155 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7156 BuildUsingShadowDecl(S, UD, *I); 7157 } 7158 7159 return UD; 7160} 7161 7162/// Additional checks for a using declaration referring to a constructor name. 7163bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7164 assert(!UD->isTypeName() && "expecting a constructor name"); 7165 7166 const Type *SourceType = UD->getQualifier()->getAsType(); 7167 assert(SourceType && 7168 "Using decl naming constructor doesn't have type in scope spec."); 7169 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7170 7171 // Check whether the named type is a direct base class. 7172 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7173 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7174 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7175 BaseIt != BaseE; ++BaseIt) { 7176 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7177 if (CanonicalSourceType == BaseType) 7178 break; 7179 if (BaseIt->getType()->isDependentType()) 7180 break; 7181 } 7182 7183 if (BaseIt == BaseE) { 7184 // Did not find SourceType in the bases. 7185 Diag(UD->getUsingLocation(), 7186 diag::err_using_decl_constructor_not_in_direct_base) 7187 << UD->getNameInfo().getSourceRange() 7188 << QualType(SourceType, 0) << TargetClass; 7189 return true; 7190 } 7191 7192 if (!CurContext->isDependentContext()) 7193 BaseIt->setInheritConstructors(); 7194 7195 return false; 7196} 7197 7198/// Checks that the given using declaration is not an invalid 7199/// redeclaration. Note that this is checking only for the using decl 7200/// itself, not for any ill-formedness among the UsingShadowDecls. 7201bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7202 bool isTypeName, 7203 const CXXScopeSpec &SS, 7204 SourceLocation NameLoc, 7205 const LookupResult &Prev) { 7206 // C++03 [namespace.udecl]p8: 7207 // C++0x [namespace.udecl]p10: 7208 // A using-declaration is a declaration and can therefore be used 7209 // repeatedly where (and only where) multiple declarations are 7210 // allowed. 7211 // 7212 // That's in non-member contexts. 7213 if (!CurContext->getRedeclContext()->isRecord()) 7214 return false; 7215 7216 NestedNameSpecifier *Qual 7217 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7218 7219 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7220 NamedDecl *D = *I; 7221 7222 bool DTypename; 7223 NestedNameSpecifier *DQual; 7224 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7225 DTypename = UD->isTypeName(); 7226 DQual = UD->getQualifier(); 7227 } else if (UnresolvedUsingValueDecl *UD 7228 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7229 DTypename = false; 7230 DQual = UD->getQualifier(); 7231 } else if (UnresolvedUsingTypenameDecl *UD 7232 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7233 DTypename = true; 7234 DQual = UD->getQualifier(); 7235 } else continue; 7236 7237 // using decls differ if one says 'typename' and the other doesn't. 7238 // FIXME: non-dependent using decls? 7239 if (isTypeName != DTypename) continue; 7240 7241 // using decls differ if they name different scopes (but note that 7242 // template instantiation can cause this check to trigger when it 7243 // didn't before instantiation). 7244 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7245 Context.getCanonicalNestedNameSpecifier(DQual)) 7246 continue; 7247 7248 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7249 Diag(D->getLocation(), diag::note_using_decl) << 1; 7250 return true; 7251 } 7252 7253 return false; 7254} 7255 7256 7257/// Checks that the given nested-name qualifier used in a using decl 7258/// in the current context is appropriately related to the current 7259/// scope. If an error is found, diagnoses it and returns true. 7260bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7261 const CXXScopeSpec &SS, 7262 SourceLocation NameLoc) { 7263 DeclContext *NamedContext = computeDeclContext(SS); 7264 7265 if (!CurContext->isRecord()) { 7266 // C++03 [namespace.udecl]p3: 7267 // C++0x [namespace.udecl]p8: 7268 // A using-declaration for a class member shall be a member-declaration. 7269 7270 // If we weren't able to compute a valid scope, it must be a 7271 // dependent class scope. 7272 if (!NamedContext || NamedContext->isRecord()) { 7273 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7274 << SS.getRange(); 7275 return true; 7276 } 7277 7278 // Otherwise, everything is known to be fine. 7279 return false; 7280 } 7281 7282 // The current scope is a record. 7283 7284 // If the named context is dependent, we can't decide much. 7285 if (!NamedContext) { 7286 // FIXME: in C++0x, we can diagnose if we can prove that the 7287 // nested-name-specifier does not refer to a base class, which is 7288 // still possible in some cases. 7289 7290 // Otherwise we have to conservatively report that things might be 7291 // okay. 7292 return false; 7293 } 7294 7295 if (!NamedContext->isRecord()) { 7296 // Ideally this would point at the last name in the specifier, 7297 // but we don't have that level of source info. 7298 Diag(SS.getRange().getBegin(), 7299 diag::err_using_decl_nested_name_specifier_is_not_class) 7300 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7301 return true; 7302 } 7303 7304 if (!NamedContext->isDependentContext() && 7305 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7306 return true; 7307 7308 if (getLangOpts().CPlusPlus11) { 7309 // C++0x [namespace.udecl]p3: 7310 // In a using-declaration used as a member-declaration, the 7311 // nested-name-specifier shall name a base class of the class 7312 // being defined. 7313 7314 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7315 cast<CXXRecordDecl>(NamedContext))) { 7316 if (CurContext == NamedContext) { 7317 Diag(NameLoc, 7318 diag::err_using_decl_nested_name_specifier_is_current_class) 7319 << SS.getRange(); 7320 return true; 7321 } 7322 7323 Diag(SS.getRange().getBegin(), 7324 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7325 << (NestedNameSpecifier*) SS.getScopeRep() 7326 << cast<CXXRecordDecl>(CurContext) 7327 << SS.getRange(); 7328 return true; 7329 } 7330 7331 return false; 7332 } 7333 7334 // C++03 [namespace.udecl]p4: 7335 // A using-declaration used as a member-declaration shall refer 7336 // to a member of a base class of the class being defined [etc.]. 7337 7338 // Salient point: SS doesn't have to name a base class as long as 7339 // lookup only finds members from base classes. Therefore we can 7340 // diagnose here only if we can prove that that can't happen, 7341 // i.e. if the class hierarchies provably don't intersect. 7342 7343 // TODO: it would be nice if "definitely valid" results were cached 7344 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7345 // need to be repeated. 7346 7347 struct UserData { 7348 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7349 7350 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7351 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7352 Data->Bases.insert(Base); 7353 return true; 7354 } 7355 7356 bool hasDependentBases(const CXXRecordDecl *Class) { 7357 return !Class->forallBases(collect, this); 7358 } 7359 7360 /// Returns true if the base is dependent or is one of the 7361 /// accumulated base classes. 7362 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7363 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7364 return !Data->Bases.count(Base); 7365 } 7366 7367 bool mightShareBases(const CXXRecordDecl *Class) { 7368 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7369 } 7370 }; 7371 7372 UserData Data; 7373 7374 // Returns false if we find a dependent base. 7375 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7376 return false; 7377 7378 // Returns false if the class has a dependent base or if it or one 7379 // of its bases is present in the base set of the current context. 7380 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7381 return false; 7382 7383 Diag(SS.getRange().getBegin(), 7384 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7385 << (NestedNameSpecifier*) SS.getScopeRep() 7386 << cast<CXXRecordDecl>(CurContext) 7387 << SS.getRange(); 7388 7389 return true; 7390} 7391 7392Decl *Sema::ActOnAliasDeclaration(Scope *S, 7393 AccessSpecifier AS, 7394 MultiTemplateParamsArg TemplateParamLists, 7395 SourceLocation UsingLoc, 7396 UnqualifiedId &Name, 7397 AttributeList *AttrList, 7398 TypeResult Type) { 7399 // Skip up to the relevant declaration scope. 7400 while (S->getFlags() & Scope::TemplateParamScope) 7401 S = S->getParent(); 7402 assert((S->getFlags() & Scope::DeclScope) && 7403 "got alias-declaration outside of declaration scope"); 7404 7405 if (Type.isInvalid()) 7406 return 0; 7407 7408 bool Invalid = false; 7409 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7410 TypeSourceInfo *TInfo = 0; 7411 GetTypeFromParser(Type.get(), &TInfo); 7412 7413 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7414 return 0; 7415 7416 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7417 UPPC_DeclarationType)) { 7418 Invalid = true; 7419 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7420 TInfo->getTypeLoc().getBeginLoc()); 7421 } 7422 7423 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7424 LookupName(Previous, S); 7425 7426 // Warn about shadowing the name of a template parameter. 7427 if (Previous.isSingleResult() && 7428 Previous.getFoundDecl()->isTemplateParameter()) { 7429 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7430 Previous.clear(); 7431 } 7432 7433 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7434 "name in alias declaration must be an identifier"); 7435 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7436 Name.StartLocation, 7437 Name.Identifier, TInfo); 7438 7439 NewTD->setAccess(AS); 7440 7441 if (Invalid) 7442 NewTD->setInvalidDecl(); 7443 7444 ProcessDeclAttributeList(S, NewTD, AttrList); 7445 7446 CheckTypedefForVariablyModifiedType(S, NewTD); 7447 Invalid |= NewTD->isInvalidDecl(); 7448 7449 bool Redeclaration = false; 7450 7451 NamedDecl *NewND; 7452 if (TemplateParamLists.size()) { 7453 TypeAliasTemplateDecl *OldDecl = 0; 7454 TemplateParameterList *OldTemplateParams = 0; 7455 7456 if (TemplateParamLists.size() != 1) { 7457 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7458 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7459 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7460 } 7461 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7462 7463 // Only consider previous declarations in the same scope. 7464 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7465 /*ExplicitInstantiationOrSpecialization*/false); 7466 if (!Previous.empty()) { 7467 Redeclaration = true; 7468 7469 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7470 if (!OldDecl && !Invalid) { 7471 Diag(UsingLoc, diag::err_redefinition_different_kind) 7472 << Name.Identifier; 7473 7474 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7475 if (OldD->getLocation().isValid()) 7476 Diag(OldD->getLocation(), diag::note_previous_definition); 7477 7478 Invalid = true; 7479 } 7480 7481 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7482 if (TemplateParameterListsAreEqual(TemplateParams, 7483 OldDecl->getTemplateParameters(), 7484 /*Complain=*/true, 7485 TPL_TemplateMatch)) 7486 OldTemplateParams = OldDecl->getTemplateParameters(); 7487 else 7488 Invalid = true; 7489 7490 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7491 if (!Invalid && 7492 !Context.hasSameType(OldTD->getUnderlyingType(), 7493 NewTD->getUnderlyingType())) { 7494 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7495 // but we can't reasonably accept it. 7496 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7497 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7498 if (OldTD->getLocation().isValid()) 7499 Diag(OldTD->getLocation(), diag::note_previous_definition); 7500 Invalid = true; 7501 } 7502 } 7503 } 7504 7505 // Merge any previous default template arguments into our parameters, 7506 // and check the parameter list. 7507 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7508 TPC_TypeAliasTemplate)) 7509 return 0; 7510 7511 TypeAliasTemplateDecl *NewDecl = 7512 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7513 Name.Identifier, TemplateParams, 7514 NewTD); 7515 7516 NewDecl->setAccess(AS); 7517 7518 if (Invalid) 7519 NewDecl->setInvalidDecl(); 7520 else if (OldDecl) 7521 NewDecl->setPreviousDeclaration(OldDecl); 7522 7523 NewND = NewDecl; 7524 } else { 7525 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7526 NewND = NewTD; 7527 } 7528 7529 if (!Redeclaration) 7530 PushOnScopeChains(NewND, S); 7531 7532 ActOnDocumentableDecl(NewND); 7533 return NewND; 7534} 7535 7536Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7537 SourceLocation NamespaceLoc, 7538 SourceLocation AliasLoc, 7539 IdentifierInfo *Alias, 7540 CXXScopeSpec &SS, 7541 SourceLocation IdentLoc, 7542 IdentifierInfo *Ident) { 7543 7544 // Lookup the namespace name. 7545 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7546 LookupParsedName(R, S, &SS); 7547 7548 // Check if we have a previous declaration with the same name. 7549 NamedDecl *PrevDecl 7550 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7551 ForRedeclaration); 7552 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7553 PrevDecl = 0; 7554 7555 if (PrevDecl) { 7556 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7557 // We already have an alias with the same name that points to the same 7558 // namespace, so don't create a new one. 7559 // FIXME: At some point, we'll want to create the (redundant) 7560 // declaration to maintain better source information. 7561 if (!R.isAmbiguous() && !R.empty() && 7562 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7563 return 0; 7564 } 7565 7566 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7567 diag::err_redefinition_different_kind; 7568 Diag(AliasLoc, DiagID) << Alias; 7569 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7570 return 0; 7571 } 7572 7573 if (R.isAmbiguous()) 7574 return 0; 7575 7576 if (R.empty()) { 7577 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7578 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7579 return 0; 7580 } 7581 } 7582 7583 NamespaceAliasDecl *AliasDecl = 7584 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7585 Alias, SS.getWithLocInContext(Context), 7586 IdentLoc, R.getFoundDecl()); 7587 7588 PushOnScopeChains(AliasDecl, S); 7589 return AliasDecl; 7590} 7591 7592Sema::ImplicitExceptionSpecification 7593Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7594 CXXMethodDecl *MD) { 7595 CXXRecordDecl *ClassDecl = MD->getParent(); 7596 7597 // C++ [except.spec]p14: 7598 // An implicitly declared special member function (Clause 12) shall have an 7599 // exception-specification. [...] 7600 ImplicitExceptionSpecification ExceptSpec(*this); 7601 if (ClassDecl->isInvalidDecl()) 7602 return ExceptSpec; 7603 7604 // Direct base-class constructors. 7605 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7606 BEnd = ClassDecl->bases_end(); 7607 B != BEnd; ++B) { 7608 if (B->isVirtual()) // Handled below. 7609 continue; 7610 7611 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7612 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7613 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7614 // If this is a deleted function, add it anyway. This might be conformant 7615 // with the standard. This might not. I'm not sure. It might not matter. 7616 if (Constructor) 7617 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7618 } 7619 } 7620 7621 // Virtual base-class constructors. 7622 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7623 BEnd = ClassDecl->vbases_end(); 7624 B != BEnd; ++B) { 7625 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7626 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7627 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7628 // If this is a deleted function, add it anyway. This might be conformant 7629 // with the standard. This might not. I'm not sure. It might not matter. 7630 if (Constructor) 7631 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7632 } 7633 } 7634 7635 // Field constructors. 7636 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7637 FEnd = ClassDecl->field_end(); 7638 F != FEnd; ++F) { 7639 if (F->hasInClassInitializer()) { 7640 if (Expr *E = F->getInClassInitializer()) 7641 ExceptSpec.CalledExpr(E); 7642 else if (!F->isInvalidDecl()) 7643 // DR1351: 7644 // If the brace-or-equal-initializer of a non-static data member 7645 // invokes a defaulted default constructor of its class or of an 7646 // enclosing class in a potentially evaluated subexpression, the 7647 // program is ill-formed. 7648 // 7649 // This resolution is unworkable: the exception specification of the 7650 // default constructor can be needed in an unevaluated context, in 7651 // particular, in the operand of a noexcept-expression, and we can be 7652 // unable to compute an exception specification for an enclosed class. 7653 // 7654 // We do not allow an in-class initializer to require the evaluation 7655 // of the exception specification for any in-class initializer whose 7656 // definition is not lexically complete. 7657 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7658 } else if (const RecordType *RecordTy 7659 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7660 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7661 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7662 // If this is a deleted function, add it anyway. This might be conformant 7663 // with the standard. This might not. I'm not sure. It might not matter. 7664 // In particular, the problem is that this function never gets called. It 7665 // might just be ill-formed because this function attempts to refer to 7666 // a deleted function here. 7667 if (Constructor) 7668 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7669 } 7670 } 7671 7672 return ExceptSpec; 7673} 7674 7675Sema::ImplicitExceptionSpecification 7676Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7677 CXXRecordDecl *ClassDecl = CD->getParent(); 7678 7679 // C++ [except.spec]p14: 7680 // An inheriting constructor [...] shall have an exception-specification. [...] 7681 ImplicitExceptionSpecification ExceptSpec(*this); 7682 if (ClassDecl->isInvalidDecl()) 7683 return ExceptSpec; 7684 7685 // Inherited constructor. 7686 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7687 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7688 // FIXME: Copying or moving the parameters could add extra exceptions to the 7689 // set, as could the default arguments for the inherited constructor. This 7690 // will be addressed when we implement the resolution of core issue 1351. 7691 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7692 7693 // Direct base-class constructors. 7694 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7695 BEnd = ClassDecl->bases_end(); 7696 B != BEnd; ++B) { 7697 if (B->isVirtual()) // Handled below. 7698 continue; 7699 7700 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7701 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7702 if (BaseClassDecl == InheritedDecl) 7703 continue; 7704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7705 if (Constructor) 7706 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7707 } 7708 } 7709 7710 // Virtual base-class constructors. 7711 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7712 BEnd = ClassDecl->vbases_end(); 7713 B != BEnd; ++B) { 7714 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7715 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7716 if (BaseClassDecl == InheritedDecl) 7717 continue; 7718 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7719 if (Constructor) 7720 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7721 } 7722 } 7723 7724 // Field constructors. 7725 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7726 FEnd = ClassDecl->field_end(); 7727 F != FEnd; ++F) { 7728 if (F->hasInClassInitializer()) { 7729 if (Expr *E = F->getInClassInitializer()) 7730 ExceptSpec.CalledExpr(E); 7731 else if (!F->isInvalidDecl()) 7732 Diag(CD->getLocation(), 7733 diag::err_in_class_initializer_references_def_ctor) << CD; 7734 } else if (const RecordType *RecordTy 7735 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7736 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7737 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7738 if (Constructor) 7739 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7740 } 7741 } 7742 7743 return ExceptSpec; 7744} 7745 7746namespace { 7747/// RAII object to register a special member as being currently declared. 7748struct DeclaringSpecialMember { 7749 Sema &S; 7750 Sema::SpecialMemberDecl D; 7751 bool WasAlreadyBeingDeclared; 7752 7753 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7754 : S(S), D(RD, CSM) { 7755 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7756 if (WasAlreadyBeingDeclared) 7757 // This almost never happens, but if it does, ensure that our cache 7758 // doesn't contain a stale result. 7759 S.SpecialMemberCache.clear(); 7760 7761 // FIXME: Register a note to be produced if we encounter an error while 7762 // declaring the special member. 7763 } 7764 ~DeclaringSpecialMember() { 7765 if (!WasAlreadyBeingDeclared) 7766 S.SpecialMembersBeingDeclared.erase(D); 7767 } 7768 7769 /// \brief Are we already trying to declare this special member? 7770 bool isAlreadyBeingDeclared() const { 7771 return WasAlreadyBeingDeclared; 7772 } 7773}; 7774} 7775 7776CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7777 CXXRecordDecl *ClassDecl) { 7778 // C++ [class.ctor]p5: 7779 // A default constructor for a class X is a constructor of class X 7780 // that can be called without an argument. If there is no 7781 // user-declared constructor for class X, a default constructor is 7782 // implicitly declared. An implicitly-declared default constructor 7783 // is an inline public member of its class. 7784 assert(ClassDecl->needsImplicitDefaultConstructor() && 7785 "Should not build implicit default constructor!"); 7786 7787 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7788 if (DSM.isAlreadyBeingDeclared()) 7789 return 0; 7790 7791 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7792 CXXDefaultConstructor, 7793 false); 7794 7795 // Create the actual constructor declaration. 7796 CanQualType ClassType 7797 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7798 SourceLocation ClassLoc = ClassDecl->getLocation(); 7799 DeclarationName Name 7800 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7801 DeclarationNameInfo NameInfo(Name, ClassLoc); 7802 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7803 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7804 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7805 Constexpr); 7806 DefaultCon->setAccess(AS_public); 7807 DefaultCon->setDefaulted(); 7808 DefaultCon->setImplicit(); 7809 7810 // Build an exception specification pointing back at this constructor. 7811 FunctionProtoType::ExtProtoInfo EPI; 7812 EPI.ExceptionSpecType = EST_Unevaluated; 7813 EPI.ExceptionSpecDecl = DefaultCon; 7814 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 7815 ArrayRef<QualType>(), 7816 EPI)); 7817 7818 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7819 // constructors is easy to compute. 7820 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7821 7822 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7823 SetDeclDeleted(DefaultCon, ClassLoc); 7824 7825 // Note that we have declared this constructor. 7826 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7827 7828 if (Scope *S = getScopeForContext(ClassDecl)) 7829 PushOnScopeChains(DefaultCon, S, false); 7830 ClassDecl->addDecl(DefaultCon); 7831 7832 return DefaultCon; 7833} 7834 7835void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7836 CXXConstructorDecl *Constructor) { 7837 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7838 !Constructor->doesThisDeclarationHaveABody() && 7839 !Constructor->isDeleted()) && 7840 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7841 7842 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7843 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7844 7845 SynthesizedFunctionScope Scope(*this, Constructor); 7846 DiagnosticErrorTrap Trap(Diags); 7847 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7848 Trap.hasErrorOccurred()) { 7849 Diag(CurrentLocation, diag::note_member_synthesized_at) 7850 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7851 Constructor->setInvalidDecl(); 7852 return; 7853 } 7854 7855 SourceLocation Loc = Constructor->getLocation(); 7856 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7857 7858 Constructor->setUsed(); 7859 MarkVTableUsed(CurrentLocation, ClassDecl); 7860 7861 if (ASTMutationListener *L = getASTMutationListener()) { 7862 L->CompletedImplicitDefinition(Constructor); 7863 } 7864} 7865 7866void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7867 // Check that any explicitly-defaulted methods have exception specifications 7868 // compatible with their implicit exception specifications. 7869 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7870} 7871 7872namespace { 7873/// Information on inheriting constructors to declare. 7874class InheritingConstructorInfo { 7875public: 7876 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 7877 : SemaRef(SemaRef), Derived(Derived) { 7878 // Mark the constructors that we already have in the derived class. 7879 // 7880 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7881 // unless there is a user-declared constructor with the same signature in 7882 // the class where the using-declaration appears. 7883 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 7884 } 7885 7886 void inheritAll(CXXRecordDecl *RD) { 7887 visitAll(RD, &InheritingConstructorInfo::inherit); 7888 } 7889 7890private: 7891 /// Information about an inheriting constructor. 7892 struct InheritingConstructor { 7893 InheritingConstructor() 7894 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 7895 7896 /// If \c true, a constructor with this signature is already declared 7897 /// in the derived class. 7898 bool DeclaredInDerived; 7899 7900 /// The constructor which is inherited. 7901 const CXXConstructorDecl *BaseCtor; 7902 7903 /// The derived constructor we declared. 7904 CXXConstructorDecl *DerivedCtor; 7905 }; 7906 7907 /// Inheriting constructors with a given canonical type. There can be at 7908 /// most one such non-template constructor, and any number of templated 7909 /// constructors. 7910 struct InheritingConstructorsForType { 7911 InheritingConstructor NonTemplate; 7912 llvm::SmallVector< 7913 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates; 7914 7915 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 7916 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 7917 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 7918 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 7919 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 7920 false, S.TPL_TemplateMatch)) 7921 return Templates[I].second; 7922 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 7923 return Templates.back().second; 7924 } 7925 7926 return NonTemplate; 7927 } 7928 }; 7929 7930 /// Get or create the inheriting constructor record for a constructor. 7931 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 7932 QualType CtorType) { 7933 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 7934 .getEntry(SemaRef, Ctor); 7935 } 7936 7937 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 7938 7939 /// Process all constructors for a class. 7940 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 7941 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 7942 CtorE = RD->ctor_end(); 7943 CtorIt != CtorE; ++CtorIt) 7944 (this->*Callback)(*CtorIt); 7945 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 7946 I(RD->decls_begin()), E(RD->decls_end()); 7947 I != E; ++I) { 7948 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 7949 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 7950 (this->*Callback)(CD); 7951 } 7952 } 7953 7954 /// Note that a constructor (or constructor template) was declared in Derived. 7955 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 7956 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 7957 } 7958 7959 /// Inherit a single constructor. 7960 void inherit(const CXXConstructorDecl *Ctor) { 7961 const FunctionProtoType *CtorType = 7962 Ctor->getType()->castAs<FunctionProtoType>(); 7963 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 7964 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 7965 7966 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 7967 7968 // Core issue (no number yet): the ellipsis is always discarded. 7969 if (EPI.Variadic) { 7970 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7971 SemaRef.Diag(Ctor->getLocation(), 7972 diag::note_using_decl_constructor_ellipsis); 7973 EPI.Variadic = false; 7974 } 7975 7976 // Declare a constructor for each number of parameters. 7977 // 7978 // C++11 [class.inhctor]p1: 7979 // The candidate set of inherited constructors from the class X named in 7980 // the using-declaration consists of [... modulo defects ...] for each 7981 // constructor or constructor template of X, the set of constructors or 7982 // constructor templates that results from omitting any ellipsis parameter 7983 // specification and successively omitting parameters with a default 7984 // argument from the end of the parameter-type-list 7985 unsigned MinParams = minParamsToInherit(Ctor); 7986 unsigned Params = Ctor->getNumParams(); 7987 if (Params >= MinParams) { 7988 do 7989 declareCtor(UsingLoc, Ctor, 7990 SemaRef.Context.getFunctionType( 7991 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 7992 while (Params > MinParams && 7993 Ctor->getParamDecl(--Params)->hasDefaultArg()); 7994 } 7995 } 7996 7997 /// Find the using-declaration which specified that we should inherit the 7998 /// constructors of \p Base. 7999 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8000 // No fancy lookup required; just look for the base constructor name 8001 // directly within the derived class. 8002 ASTContext &Context = SemaRef.Context; 8003 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8004 Context.getCanonicalType(Context.getRecordType(Base))); 8005 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8006 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8007 } 8008 8009 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8010 // C++11 [class.inhctor]p3: 8011 // [F]or each constructor template in the candidate set of inherited 8012 // constructors, a constructor template is implicitly declared 8013 if (Ctor->getDescribedFunctionTemplate()) 8014 return 0; 8015 8016 // For each non-template constructor in the candidate set of inherited 8017 // constructors other than a constructor having no parameters or a 8018 // copy/move constructor having a single parameter, a constructor is 8019 // implicitly declared [...] 8020 if (Ctor->getNumParams() == 0) 8021 return 1; 8022 if (Ctor->isCopyOrMoveConstructor()) 8023 return 2; 8024 8025 // Per discussion on core reflector, never inherit a constructor which 8026 // would become a default, copy, or move constructor of Derived either. 8027 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8028 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8029 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8030 } 8031 8032 /// Declare a single inheriting constructor, inheriting the specified 8033 /// constructor, with the given type. 8034 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8035 QualType DerivedType) { 8036 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8037 8038 // C++11 [class.inhctor]p3: 8039 // ... a constructor is implicitly declared with the same constructor 8040 // characteristics unless there is a user-declared constructor with 8041 // the same signature in the class where the using-declaration appears 8042 if (Entry.DeclaredInDerived) 8043 return; 8044 8045 // C++11 [class.inhctor]p7: 8046 // If two using-declarations declare inheriting constructors with the 8047 // same signature, the program is ill-formed 8048 if (Entry.DerivedCtor) { 8049 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8050 // Only diagnose this once per constructor. 8051 if (Entry.DerivedCtor->isInvalidDecl()) 8052 return; 8053 Entry.DerivedCtor->setInvalidDecl(); 8054 8055 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8056 SemaRef.Diag(BaseCtor->getLocation(), 8057 diag::note_using_decl_constructor_conflict_current_ctor); 8058 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8059 diag::note_using_decl_constructor_conflict_previous_ctor); 8060 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8061 diag::note_using_decl_constructor_conflict_previous_using); 8062 } else { 8063 // Core issue (no number): if the same inheriting constructor is 8064 // produced by multiple base class constructors from the same base 8065 // class, the inheriting constructor is defined as deleted. 8066 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8067 } 8068 8069 return; 8070 } 8071 8072 ASTContext &Context = SemaRef.Context; 8073 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8074 Context.getCanonicalType(Context.getRecordType(Derived))); 8075 DeclarationNameInfo NameInfo(Name, UsingLoc); 8076 8077 TemplateParameterList *TemplateParams = 0; 8078 if (const FunctionTemplateDecl *FTD = 8079 BaseCtor->getDescribedFunctionTemplate()) { 8080 TemplateParams = FTD->getTemplateParameters(); 8081 // We're reusing template parameters from a different DeclContext. This 8082 // is questionable at best, but works out because the template depth in 8083 // both places is guaranteed to be 0. 8084 // FIXME: Rebuild the template parameters in the new context, and 8085 // transform the function type to refer to them. 8086 } 8087 8088 // Build type source info pointing at the using-declaration. This is 8089 // required by template instantiation. 8090 TypeSourceInfo *TInfo = 8091 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8092 FunctionProtoTypeLoc ProtoLoc = 8093 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8094 8095 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8096 Context, Derived, UsingLoc, NameInfo, DerivedType, 8097 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8098 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8099 8100 // Build an unevaluated exception specification for this constructor. 8101 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8103 EPI.ExceptionSpecType = EST_Unevaluated; 8104 EPI.ExceptionSpecDecl = DerivedCtor; 8105 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8106 FPT->getArgTypes(), EPI)); 8107 8108 // Build the parameter declarations. 8109 SmallVector<ParmVarDecl *, 16> ParamDecls; 8110 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8111 TypeSourceInfo *TInfo = 8112 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8113 ParmVarDecl *PD = ParmVarDecl::Create( 8114 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8115 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8116 PD->setScopeInfo(0, I); 8117 PD->setImplicit(); 8118 ParamDecls.push_back(PD); 8119 ProtoLoc.setArg(I, PD); 8120 } 8121 8122 // Set up the new constructor. 8123 DerivedCtor->setAccess(BaseCtor->getAccess()); 8124 DerivedCtor->setParams(ParamDecls); 8125 DerivedCtor->setInheritedConstructor(BaseCtor); 8126 if (BaseCtor->isDeleted()) 8127 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8128 8129 // If this is a constructor template, build the template declaration. 8130 if (TemplateParams) { 8131 FunctionTemplateDecl *DerivedTemplate = 8132 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8133 TemplateParams, DerivedCtor); 8134 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8135 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8136 Derived->addDecl(DerivedTemplate); 8137 } else { 8138 Derived->addDecl(DerivedCtor); 8139 } 8140 8141 Entry.BaseCtor = BaseCtor; 8142 Entry.DerivedCtor = DerivedCtor; 8143 } 8144 8145 Sema &SemaRef; 8146 CXXRecordDecl *Derived; 8147 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8148 MapType Map; 8149}; 8150} 8151 8152void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8153 // Defer declaring the inheriting constructors until the class is 8154 // instantiated. 8155 if (ClassDecl->isDependentContext()) 8156 return; 8157 8158 // Find base classes from which we might inherit constructors. 8159 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8160 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8161 BaseE = ClassDecl->bases_end(); 8162 BaseIt != BaseE; ++BaseIt) 8163 if (BaseIt->getInheritConstructors()) 8164 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8165 8166 // Go no further if we're not inheriting any constructors. 8167 if (InheritedBases.empty()) 8168 return; 8169 8170 // Declare the inherited constructors. 8171 InheritingConstructorInfo ICI(*this, ClassDecl); 8172 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8173 ICI.inheritAll(InheritedBases[I]); 8174} 8175 8176void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8177 CXXConstructorDecl *Constructor) { 8178 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8179 assert(Constructor->getInheritedConstructor() && 8180 !Constructor->doesThisDeclarationHaveABody() && 8181 !Constructor->isDeleted()); 8182 8183 SynthesizedFunctionScope Scope(*this, Constructor); 8184 DiagnosticErrorTrap Trap(Diags); 8185 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8186 Trap.hasErrorOccurred()) { 8187 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8188 << Context.getTagDeclType(ClassDecl); 8189 Constructor->setInvalidDecl(); 8190 return; 8191 } 8192 8193 SourceLocation Loc = Constructor->getLocation(); 8194 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8195 8196 Constructor->setUsed(); 8197 MarkVTableUsed(CurrentLocation, ClassDecl); 8198 8199 if (ASTMutationListener *L = getASTMutationListener()) { 8200 L->CompletedImplicitDefinition(Constructor); 8201 } 8202} 8203 8204 8205Sema::ImplicitExceptionSpecification 8206Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8207 CXXRecordDecl *ClassDecl = MD->getParent(); 8208 8209 // C++ [except.spec]p14: 8210 // An implicitly declared special member function (Clause 12) shall have 8211 // an exception-specification. 8212 ImplicitExceptionSpecification ExceptSpec(*this); 8213 if (ClassDecl->isInvalidDecl()) 8214 return ExceptSpec; 8215 8216 // Direct base-class destructors. 8217 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8218 BEnd = ClassDecl->bases_end(); 8219 B != BEnd; ++B) { 8220 if (B->isVirtual()) // Handled below. 8221 continue; 8222 8223 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8224 ExceptSpec.CalledDecl(B->getLocStart(), 8225 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8226 } 8227 8228 // Virtual base-class destructors. 8229 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8230 BEnd = ClassDecl->vbases_end(); 8231 B != BEnd; ++B) { 8232 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8233 ExceptSpec.CalledDecl(B->getLocStart(), 8234 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8235 } 8236 8237 // Field destructors. 8238 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8239 FEnd = ClassDecl->field_end(); 8240 F != FEnd; ++F) { 8241 if (const RecordType *RecordTy 8242 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8243 ExceptSpec.CalledDecl(F->getLocation(), 8244 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8245 } 8246 8247 return ExceptSpec; 8248} 8249 8250CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8251 // C++ [class.dtor]p2: 8252 // If a class has no user-declared destructor, a destructor is 8253 // declared implicitly. An implicitly-declared destructor is an 8254 // inline public member of its class. 8255 assert(ClassDecl->needsImplicitDestructor()); 8256 8257 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8258 if (DSM.isAlreadyBeingDeclared()) 8259 return 0; 8260 8261 // Create the actual destructor declaration. 8262 CanQualType ClassType 8263 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8264 SourceLocation ClassLoc = ClassDecl->getLocation(); 8265 DeclarationName Name 8266 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8267 DeclarationNameInfo NameInfo(Name, ClassLoc); 8268 CXXDestructorDecl *Destructor 8269 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8270 QualType(), 0, /*isInline=*/true, 8271 /*isImplicitlyDeclared=*/true); 8272 Destructor->setAccess(AS_public); 8273 Destructor->setDefaulted(); 8274 Destructor->setImplicit(); 8275 8276 // Build an exception specification pointing back at this destructor. 8277 FunctionProtoType::ExtProtoInfo EPI; 8278 EPI.ExceptionSpecType = EST_Unevaluated; 8279 EPI.ExceptionSpecDecl = Destructor; 8280 Destructor->setType(Context.getFunctionType(Context.VoidTy, 8281 ArrayRef<QualType>(), 8282 EPI)); 8283 8284 AddOverriddenMethods(ClassDecl, Destructor); 8285 8286 // We don't need to use SpecialMemberIsTrivial here; triviality for 8287 // destructors is easy to compute. 8288 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8289 8290 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8291 SetDeclDeleted(Destructor, ClassLoc); 8292 8293 // Note that we have declared this destructor. 8294 ++ASTContext::NumImplicitDestructorsDeclared; 8295 8296 // Introduce this destructor into its scope. 8297 if (Scope *S = getScopeForContext(ClassDecl)) 8298 PushOnScopeChains(Destructor, S, false); 8299 ClassDecl->addDecl(Destructor); 8300 8301 return Destructor; 8302} 8303 8304void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8305 CXXDestructorDecl *Destructor) { 8306 assert((Destructor->isDefaulted() && 8307 !Destructor->doesThisDeclarationHaveABody() && 8308 !Destructor->isDeleted()) && 8309 "DefineImplicitDestructor - call it for implicit default dtor"); 8310 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8311 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8312 8313 if (Destructor->isInvalidDecl()) 8314 return; 8315 8316 SynthesizedFunctionScope Scope(*this, Destructor); 8317 8318 DiagnosticErrorTrap Trap(Diags); 8319 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8320 Destructor->getParent()); 8321 8322 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8323 Diag(CurrentLocation, diag::note_member_synthesized_at) 8324 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8325 8326 Destructor->setInvalidDecl(); 8327 return; 8328 } 8329 8330 SourceLocation Loc = Destructor->getLocation(); 8331 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8332 Destructor->setImplicitlyDefined(true); 8333 Destructor->setUsed(); 8334 MarkVTableUsed(CurrentLocation, ClassDecl); 8335 8336 if (ASTMutationListener *L = getASTMutationListener()) { 8337 L->CompletedImplicitDefinition(Destructor); 8338 } 8339} 8340 8341/// \brief Perform any semantic analysis which needs to be delayed until all 8342/// pending class member declarations have been parsed. 8343void Sema::ActOnFinishCXXMemberDecls() { 8344 // If the context is an invalid C++ class, just suppress these checks. 8345 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8346 if (Record->isInvalidDecl()) { 8347 DelayedDestructorExceptionSpecChecks.clear(); 8348 return; 8349 } 8350 } 8351 8352 // Perform any deferred checking of exception specifications for virtual 8353 // destructors. 8354 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8355 i != e; ++i) { 8356 const CXXDestructorDecl *Dtor = 8357 DelayedDestructorExceptionSpecChecks[i].first; 8358 assert(!Dtor->getParent()->isDependentType() && 8359 "Should not ever add destructors of templates into the list."); 8360 CheckOverridingFunctionExceptionSpec(Dtor, 8361 DelayedDestructorExceptionSpecChecks[i].second); 8362 } 8363 DelayedDestructorExceptionSpecChecks.clear(); 8364} 8365 8366void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8367 CXXDestructorDecl *Destructor) { 8368 assert(getLangOpts().CPlusPlus11 && 8369 "adjusting dtor exception specs was introduced in c++11"); 8370 8371 // C++11 [class.dtor]p3: 8372 // A declaration of a destructor that does not have an exception- 8373 // specification is implicitly considered to have the same exception- 8374 // specification as an implicit declaration. 8375 const FunctionProtoType *DtorType = Destructor->getType()-> 8376 getAs<FunctionProtoType>(); 8377 if (DtorType->hasExceptionSpec()) 8378 return; 8379 8380 // Replace the destructor's type, building off the existing one. Fortunately, 8381 // the only thing of interest in the destructor type is its extended info. 8382 // The return and arguments are fixed. 8383 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8384 EPI.ExceptionSpecType = EST_Unevaluated; 8385 EPI.ExceptionSpecDecl = Destructor; 8386 Destructor->setType(Context.getFunctionType(Context.VoidTy, 8387 ArrayRef<QualType>(), 8388 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, 1, 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 if (ClassDecl->implicitCopyAssignmentHasConstParam()) 8766 ArgType = ArgType.withConst(); 8767 ArgType = Context.getLValueReferenceType(ArgType); 8768 8769 // An implicitly-declared copy assignment operator is an inline public 8770 // member of its class. 8771 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8772 SourceLocation ClassLoc = ClassDecl->getLocation(); 8773 DeclarationNameInfo NameInfo(Name, ClassLoc); 8774 CXXMethodDecl *CopyAssignment 8775 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8776 /*TInfo=*/0, 8777 /*StorageClass=*/SC_None, 8778 /*isInline=*/true, /*isConstexpr=*/false, 8779 SourceLocation()); 8780 CopyAssignment->setAccess(AS_public); 8781 CopyAssignment->setDefaulted(); 8782 CopyAssignment->setImplicit(); 8783 8784 // Build an exception specification pointing back at this member. 8785 FunctionProtoType::ExtProtoInfo EPI; 8786 EPI.ExceptionSpecType = EST_Unevaluated; 8787 EPI.ExceptionSpecDecl = CopyAssignment; 8788 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8789 8790 // Add the parameter to the operator. 8791 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8792 ClassLoc, ClassLoc, /*Id=*/0, 8793 ArgType, /*TInfo=*/0, 8794 SC_None, 0); 8795 CopyAssignment->setParams(FromParam); 8796 8797 AddOverriddenMethods(ClassDecl, CopyAssignment); 8798 8799 CopyAssignment->setTrivial( 8800 ClassDecl->needsOverloadResolutionForCopyAssignment() 8801 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8802 : ClassDecl->hasTrivialCopyAssignment()); 8803 8804 // C++0x [class.copy]p19: 8805 // .... If the class definition does not explicitly declare a copy 8806 // assignment operator, there is no user-declared move constructor, and 8807 // there is no user-declared move assignment operator, a copy assignment 8808 // operator is implicitly declared as defaulted. 8809 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8810 SetDeclDeleted(CopyAssignment, ClassLoc); 8811 8812 // Note that we have added this copy-assignment operator. 8813 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8814 8815 if (Scope *S = getScopeForContext(ClassDecl)) 8816 PushOnScopeChains(CopyAssignment, S, false); 8817 ClassDecl->addDecl(CopyAssignment); 8818 8819 return CopyAssignment; 8820} 8821 8822void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8823 CXXMethodDecl *CopyAssignOperator) { 8824 assert((CopyAssignOperator->isDefaulted() && 8825 CopyAssignOperator->isOverloadedOperator() && 8826 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8827 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8828 !CopyAssignOperator->isDeleted()) && 8829 "DefineImplicitCopyAssignment called for wrong function"); 8830 8831 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8832 8833 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8834 CopyAssignOperator->setInvalidDecl(); 8835 return; 8836 } 8837 8838 CopyAssignOperator->setUsed(); 8839 8840 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8841 DiagnosticErrorTrap Trap(Diags); 8842 8843 // C++0x [class.copy]p30: 8844 // The implicitly-defined or explicitly-defaulted copy assignment operator 8845 // for a non-union class X performs memberwise copy assignment of its 8846 // subobjects. The direct base classes of X are assigned first, in the 8847 // order of their declaration in the base-specifier-list, and then the 8848 // immediate non-static data members of X are assigned, in the order in 8849 // which they were declared in the class definition. 8850 8851 // The statements that form the synthesized function body. 8852 SmallVector<Stmt*, 8> Statements; 8853 8854 // The parameter for the "other" object, which we are copying from. 8855 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8856 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8857 QualType OtherRefType = Other->getType(); 8858 if (const LValueReferenceType *OtherRef 8859 = OtherRefType->getAs<LValueReferenceType>()) { 8860 OtherRefType = OtherRef->getPointeeType(); 8861 OtherQuals = OtherRefType.getQualifiers(); 8862 } 8863 8864 // Our location for everything implicitly-generated. 8865 SourceLocation Loc = CopyAssignOperator->getLocation(); 8866 8867 // Construct a reference to the "other" object. We'll be using this 8868 // throughout the generated ASTs. 8869 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8870 assert(OtherRef && "Reference to parameter cannot fail!"); 8871 8872 // Construct the "this" pointer. We'll be using this throughout the generated 8873 // ASTs. 8874 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8875 assert(This && "Reference to this cannot fail!"); 8876 8877 // Assign base classes. 8878 bool Invalid = false; 8879 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8880 E = ClassDecl->bases_end(); Base != E; ++Base) { 8881 // Form the assignment: 8882 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8883 QualType BaseType = Base->getType().getUnqualifiedType(); 8884 if (!BaseType->isRecordType()) { 8885 Invalid = true; 8886 continue; 8887 } 8888 8889 CXXCastPath BasePath; 8890 BasePath.push_back(Base); 8891 8892 // Construct the "from" expression, which is an implicit cast to the 8893 // appropriately-qualified base type. 8894 Expr *From = OtherRef; 8895 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8896 CK_UncheckedDerivedToBase, 8897 VK_LValue, &BasePath).take(); 8898 8899 // Dereference "this". 8900 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8901 8902 // Implicitly cast "this" to the appropriately-qualified base type. 8903 To = ImpCastExprToType(To.take(), 8904 Context.getCVRQualifiedType(BaseType, 8905 CopyAssignOperator->getTypeQualifiers()), 8906 CK_UncheckedDerivedToBase, 8907 VK_LValue, &BasePath); 8908 8909 // Build the copy. 8910 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8911 To.get(), From, 8912 /*CopyingBaseSubobject=*/true, 8913 /*Copying=*/true); 8914 if (Copy.isInvalid()) { 8915 Diag(CurrentLocation, diag::note_member_synthesized_at) 8916 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8917 CopyAssignOperator->setInvalidDecl(); 8918 return; 8919 } 8920 8921 // Success! Record the copy. 8922 Statements.push_back(Copy.takeAs<Expr>()); 8923 } 8924 8925 // Assign non-static members. 8926 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8927 FieldEnd = ClassDecl->field_end(); 8928 Field != FieldEnd; ++Field) { 8929 if (Field->isUnnamedBitfield()) 8930 continue; 8931 8932 // Check for members of reference type; we can't copy those. 8933 if (Field->getType()->isReferenceType()) { 8934 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8935 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8936 Diag(Field->getLocation(), diag::note_declared_at); 8937 Diag(CurrentLocation, diag::note_member_synthesized_at) 8938 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8939 Invalid = true; 8940 continue; 8941 } 8942 8943 // Check for members of const-qualified, non-class type. 8944 QualType BaseType = Context.getBaseElementType(Field->getType()); 8945 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8946 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8947 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8948 Diag(Field->getLocation(), diag::note_declared_at); 8949 Diag(CurrentLocation, diag::note_member_synthesized_at) 8950 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8951 Invalid = true; 8952 continue; 8953 } 8954 8955 // Suppress assigning zero-width bitfields. 8956 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8957 continue; 8958 8959 QualType FieldType = Field->getType().getNonReferenceType(); 8960 if (FieldType->isIncompleteArrayType()) { 8961 assert(ClassDecl->hasFlexibleArrayMember() && 8962 "Incomplete array type is not valid"); 8963 continue; 8964 } 8965 8966 // Build references to the field in the object we're copying from and to. 8967 CXXScopeSpec SS; // Intentionally empty 8968 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8969 LookupMemberName); 8970 MemberLookup.addDecl(*Field); 8971 MemberLookup.resolveKind(); 8972 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8973 Loc, /*IsArrow=*/false, 8974 SS, SourceLocation(), 0, 8975 MemberLookup, 0); 8976 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8977 Loc, /*IsArrow=*/true, 8978 SS, SourceLocation(), 0, 8979 MemberLookup, 0); 8980 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8981 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8982 8983 // Build the copy of this field. 8984 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8985 To.get(), From.get(), 8986 /*CopyingBaseSubobject=*/false, 8987 /*Copying=*/true); 8988 if (Copy.isInvalid()) { 8989 Diag(CurrentLocation, diag::note_member_synthesized_at) 8990 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8991 CopyAssignOperator->setInvalidDecl(); 8992 return; 8993 } 8994 8995 // Success! Record the copy. 8996 Statements.push_back(Copy.takeAs<Stmt>()); 8997 } 8998 8999 if (!Invalid) { 9000 // Add a "return *this;" 9001 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9002 9003 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9004 if (Return.isInvalid()) 9005 Invalid = true; 9006 else { 9007 Statements.push_back(Return.takeAs<Stmt>()); 9008 9009 if (Trap.hasErrorOccurred()) { 9010 Diag(CurrentLocation, diag::note_member_synthesized_at) 9011 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9012 Invalid = true; 9013 } 9014 } 9015 } 9016 9017 if (Invalid) { 9018 CopyAssignOperator->setInvalidDecl(); 9019 return; 9020 } 9021 9022 StmtResult Body; 9023 { 9024 CompoundScopeRAII CompoundScope(*this); 9025 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9026 /*isStmtExpr=*/false); 9027 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9028 } 9029 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9030 9031 if (ASTMutationListener *L = getASTMutationListener()) { 9032 L->CompletedImplicitDefinition(CopyAssignOperator); 9033 } 9034} 9035 9036Sema::ImplicitExceptionSpecification 9037Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9038 CXXRecordDecl *ClassDecl = MD->getParent(); 9039 9040 ImplicitExceptionSpecification ExceptSpec(*this); 9041 if (ClassDecl->isInvalidDecl()) 9042 return ExceptSpec; 9043 9044 // C++0x [except.spec]p14: 9045 // An implicitly declared special member function (Clause 12) shall have an 9046 // exception-specification. [...] 9047 9048 // It is unspecified whether or not an implicit move assignment operator 9049 // attempts to deduplicate calls to assignment operators of virtual bases are 9050 // made. As such, this exception specification is effectively unspecified. 9051 // Based on a similar decision made for constness in C++0x, we're erring on 9052 // the side of assuming such calls to be made regardless of whether they 9053 // actually happen. 9054 // Note that a move constructor is not implicitly declared when there are 9055 // virtual bases, but it can still be user-declared and explicitly defaulted. 9056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9057 BaseEnd = ClassDecl->bases_end(); 9058 Base != BaseEnd; ++Base) { 9059 if (Base->isVirtual()) 9060 continue; 9061 9062 CXXRecordDecl *BaseClassDecl 9063 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9064 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9065 0, false, 0)) 9066 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9067 } 9068 9069 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9070 BaseEnd = ClassDecl->vbases_end(); 9071 Base != BaseEnd; ++Base) { 9072 CXXRecordDecl *BaseClassDecl 9073 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9074 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9075 0, false, 0)) 9076 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9077 } 9078 9079 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9080 FieldEnd = ClassDecl->field_end(); 9081 Field != FieldEnd; 9082 ++Field) { 9083 QualType FieldType = Context.getBaseElementType(Field->getType()); 9084 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9085 if (CXXMethodDecl *MoveAssign = 9086 LookupMovingAssignment(FieldClassDecl, 9087 FieldType.getCVRQualifiers(), 9088 false, 0)) 9089 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9090 } 9091 } 9092 9093 return ExceptSpec; 9094} 9095 9096/// Determine whether the class type has any direct or indirect virtual base 9097/// classes which have a non-trivial move assignment operator. 9098static bool 9099hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9100 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9101 BaseEnd = ClassDecl->vbases_end(); 9102 Base != BaseEnd; ++Base) { 9103 CXXRecordDecl *BaseClass = 9104 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9105 9106 // Try to declare the move assignment. If it would be deleted, then the 9107 // class does not have a non-trivial move assignment. 9108 if (BaseClass->needsImplicitMoveAssignment()) 9109 S.DeclareImplicitMoveAssignment(BaseClass); 9110 9111 if (BaseClass->hasNonTrivialMoveAssignment()) 9112 return true; 9113 } 9114 9115 return false; 9116} 9117 9118/// Determine whether the given type either has a move constructor or is 9119/// trivially copyable. 9120static bool 9121hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9122 Type = S.Context.getBaseElementType(Type); 9123 9124 // FIXME: Technically, non-trivially-copyable non-class types, such as 9125 // reference types, are supposed to return false here, but that appears 9126 // to be a standard defect. 9127 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9128 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9129 return true; 9130 9131 if (Type.isTriviallyCopyableType(S.Context)) 9132 return true; 9133 9134 if (IsConstructor) { 9135 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9136 // give the right answer. 9137 if (ClassDecl->needsImplicitMoveConstructor()) 9138 S.DeclareImplicitMoveConstructor(ClassDecl); 9139 return ClassDecl->hasMoveConstructor(); 9140 } 9141 9142 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9143 // give the right answer. 9144 if (ClassDecl->needsImplicitMoveAssignment()) 9145 S.DeclareImplicitMoveAssignment(ClassDecl); 9146 return ClassDecl->hasMoveAssignment(); 9147} 9148 9149/// Determine whether all non-static data members and direct or virtual bases 9150/// of class \p ClassDecl have either a move operation, or are trivially 9151/// copyable. 9152static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9153 bool IsConstructor) { 9154 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9155 BaseEnd = ClassDecl->bases_end(); 9156 Base != BaseEnd; ++Base) { 9157 if (Base->isVirtual()) 9158 continue; 9159 9160 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9161 return false; 9162 } 9163 9164 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9165 BaseEnd = ClassDecl->vbases_end(); 9166 Base != BaseEnd; ++Base) { 9167 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9168 return false; 9169 } 9170 9171 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9172 FieldEnd = ClassDecl->field_end(); 9173 Field != FieldEnd; ++Field) { 9174 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9175 return false; 9176 } 9177 9178 return true; 9179} 9180 9181CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9182 // C++11 [class.copy]p20: 9183 // If the definition of a class X does not explicitly declare a move 9184 // assignment operator, one will be implicitly declared as defaulted 9185 // if and only if: 9186 // 9187 // - [first 4 bullets] 9188 assert(ClassDecl->needsImplicitMoveAssignment()); 9189 9190 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9191 if (DSM.isAlreadyBeingDeclared()) 9192 return 0; 9193 9194 // [Checked after we build the declaration] 9195 // - the move assignment operator would not be implicitly defined as 9196 // deleted, 9197 9198 // [DR1402]: 9199 // - X has no direct or indirect virtual base class with a non-trivial 9200 // move assignment operator, and 9201 // - each of X's non-static data members and direct or virtual base classes 9202 // has a type that either has a move assignment operator or is trivially 9203 // copyable. 9204 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9205 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9206 ClassDecl->setFailedImplicitMoveAssignment(); 9207 return 0; 9208 } 9209 9210 // Note: The following rules are largely analoguous to the move 9211 // constructor rules. 9212 9213 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9214 QualType RetType = Context.getLValueReferenceType(ArgType); 9215 ArgType = Context.getRValueReferenceType(ArgType); 9216 9217 // An implicitly-declared move assignment operator is an inline public 9218 // member of its class. 9219 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9220 SourceLocation ClassLoc = ClassDecl->getLocation(); 9221 DeclarationNameInfo NameInfo(Name, ClassLoc); 9222 CXXMethodDecl *MoveAssignment 9223 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9224 /*TInfo=*/0, 9225 /*StorageClass=*/SC_None, 9226 /*isInline=*/true, 9227 /*isConstexpr=*/false, 9228 SourceLocation()); 9229 MoveAssignment->setAccess(AS_public); 9230 MoveAssignment->setDefaulted(); 9231 MoveAssignment->setImplicit(); 9232 9233 // Build an exception specification pointing back at this member. 9234 FunctionProtoType::ExtProtoInfo EPI; 9235 EPI.ExceptionSpecType = EST_Unevaluated; 9236 EPI.ExceptionSpecDecl = MoveAssignment; 9237 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9238 9239 // Add the parameter to the operator. 9240 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9241 ClassLoc, ClassLoc, /*Id=*/0, 9242 ArgType, /*TInfo=*/0, 9243 SC_None, 0); 9244 MoveAssignment->setParams(FromParam); 9245 9246 AddOverriddenMethods(ClassDecl, MoveAssignment); 9247 9248 MoveAssignment->setTrivial( 9249 ClassDecl->needsOverloadResolutionForMoveAssignment() 9250 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9251 : ClassDecl->hasTrivialMoveAssignment()); 9252 9253 // C++0x [class.copy]p9: 9254 // If the definition of a class X does not explicitly declare a move 9255 // assignment operator, one will be implicitly declared as defaulted if and 9256 // only if: 9257 // [...] 9258 // - the move assignment operator would not be implicitly defined as 9259 // deleted. 9260 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9261 // Cache this result so that we don't try to generate this over and over 9262 // on every lookup, leaking memory and wasting time. 9263 ClassDecl->setFailedImplicitMoveAssignment(); 9264 return 0; 9265 } 9266 9267 // Note that we have added this copy-assignment operator. 9268 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9269 9270 if (Scope *S = getScopeForContext(ClassDecl)) 9271 PushOnScopeChains(MoveAssignment, S, false); 9272 ClassDecl->addDecl(MoveAssignment); 9273 9274 return MoveAssignment; 9275} 9276 9277void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9278 CXXMethodDecl *MoveAssignOperator) { 9279 assert((MoveAssignOperator->isDefaulted() && 9280 MoveAssignOperator->isOverloadedOperator() && 9281 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9282 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9283 !MoveAssignOperator->isDeleted()) && 9284 "DefineImplicitMoveAssignment called for wrong function"); 9285 9286 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9287 9288 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9289 MoveAssignOperator->setInvalidDecl(); 9290 return; 9291 } 9292 9293 MoveAssignOperator->setUsed(); 9294 9295 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9296 DiagnosticErrorTrap Trap(Diags); 9297 9298 // C++0x [class.copy]p28: 9299 // The implicitly-defined or move assignment operator for a non-union class 9300 // X performs memberwise move assignment of its subobjects. The direct base 9301 // classes of X are assigned first, in the order of their declaration in the 9302 // base-specifier-list, and then the immediate non-static data members of X 9303 // are assigned, in the order in which they were declared in the class 9304 // definition. 9305 9306 // The statements that form the synthesized function body. 9307 SmallVector<Stmt*, 8> Statements; 9308 9309 // The parameter for the "other" object, which we are move from. 9310 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9311 QualType OtherRefType = Other->getType()-> 9312 getAs<RValueReferenceType>()->getPointeeType(); 9313 assert(OtherRefType.getQualifiers() == 0 && 9314 "Bad argument type of defaulted move assignment"); 9315 9316 // Our location for everything implicitly-generated. 9317 SourceLocation Loc = MoveAssignOperator->getLocation(); 9318 9319 // Construct a reference to the "other" object. We'll be using this 9320 // throughout the generated ASTs. 9321 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9322 assert(OtherRef && "Reference to parameter cannot fail!"); 9323 // Cast to rvalue. 9324 OtherRef = CastForMoving(*this, OtherRef); 9325 9326 // Construct the "this" pointer. We'll be using this throughout the generated 9327 // ASTs. 9328 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9329 assert(This && "Reference to this cannot fail!"); 9330 9331 // Assign base classes. 9332 bool Invalid = false; 9333 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9334 E = ClassDecl->bases_end(); Base != E; ++Base) { 9335 // Form the assignment: 9336 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9337 QualType BaseType = Base->getType().getUnqualifiedType(); 9338 if (!BaseType->isRecordType()) { 9339 Invalid = true; 9340 continue; 9341 } 9342 9343 CXXCastPath BasePath; 9344 BasePath.push_back(Base); 9345 9346 // Construct the "from" expression, which is an implicit cast to the 9347 // appropriately-qualified base type. 9348 Expr *From = OtherRef; 9349 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9350 VK_XValue, &BasePath).take(); 9351 9352 // Dereference "this". 9353 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9354 9355 // Implicitly cast "this" to the appropriately-qualified base type. 9356 To = ImpCastExprToType(To.take(), 9357 Context.getCVRQualifiedType(BaseType, 9358 MoveAssignOperator->getTypeQualifiers()), 9359 CK_UncheckedDerivedToBase, 9360 VK_LValue, &BasePath); 9361 9362 // Build the move. 9363 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9364 To.get(), From, 9365 /*CopyingBaseSubobject=*/true, 9366 /*Copying=*/false); 9367 if (Move.isInvalid()) { 9368 Diag(CurrentLocation, diag::note_member_synthesized_at) 9369 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9370 MoveAssignOperator->setInvalidDecl(); 9371 return; 9372 } 9373 9374 // Success! Record the move. 9375 Statements.push_back(Move.takeAs<Expr>()); 9376 } 9377 9378 // Assign non-static members. 9379 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9380 FieldEnd = ClassDecl->field_end(); 9381 Field != FieldEnd; ++Field) { 9382 if (Field->isUnnamedBitfield()) 9383 continue; 9384 9385 // Check for members of reference type; we can't move those. 9386 if (Field->getType()->isReferenceType()) { 9387 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9388 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9389 Diag(Field->getLocation(), diag::note_declared_at); 9390 Diag(CurrentLocation, diag::note_member_synthesized_at) 9391 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9392 Invalid = true; 9393 continue; 9394 } 9395 9396 // Check for members of const-qualified, non-class type. 9397 QualType BaseType = Context.getBaseElementType(Field->getType()); 9398 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9399 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9400 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9401 Diag(Field->getLocation(), diag::note_declared_at); 9402 Diag(CurrentLocation, diag::note_member_synthesized_at) 9403 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9404 Invalid = true; 9405 continue; 9406 } 9407 9408 // Suppress assigning zero-width bitfields. 9409 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9410 continue; 9411 9412 QualType FieldType = Field->getType().getNonReferenceType(); 9413 if (FieldType->isIncompleteArrayType()) { 9414 assert(ClassDecl->hasFlexibleArrayMember() && 9415 "Incomplete array type is not valid"); 9416 continue; 9417 } 9418 9419 // Build references to the field in the object we're copying from and to. 9420 CXXScopeSpec SS; // Intentionally empty 9421 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9422 LookupMemberName); 9423 MemberLookup.addDecl(*Field); 9424 MemberLookup.resolveKind(); 9425 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9426 Loc, /*IsArrow=*/false, 9427 SS, SourceLocation(), 0, 9428 MemberLookup, 0); 9429 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9430 Loc, /*IsArrow=*/true, 9431 SS, SourceLocation(), 0, 9432 MemberLookup, 0); 9433 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9434 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9435 9436 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9437 "Member reference with rvalue base must be rvalue except for reference " 9438 "members, which aren't allowed for move assignment."); 9439 9440 // Build the move of this field. 9441 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9442 To.get(), From.get(), 9443 /*CopyingBaseSubobject=*/false, 9444 /*Copying=*/false); 9445 if (Move.isInvalid()) { 9446 Diag(CurrentLocation, diag::note_member_synthesized_at) 9447 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9448 MoveAssignOperator->setInvalidDecl(); 9449 return; 9450 } 9451 9452 // Success! Record the copy. 9453 Statements.push_back(Move.takeAs<Stmt>()); 9454 } 9455 9456 if (!Invalid) { 9457 // Add a "return *this;" 9458 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9459 9460 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9461 if (Return.isInvalid()) 9462 Invalid = true; 9463 else { 9464 Statements.push_back(Return.takeAs<Stmt>()); 9465 9466 if (Trap.hasErrorOccurred()) { 9467 Diag(CurrentLocation, diag::note_member_synthesized_at) 9468 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9469 Invalid = true; 9470 } 9471 } 9472 } 9473 9474 if (Invalid) { 9475 MoveAssignOperator->setInvalidDecl(); 9476 return; 9477 } 9478 9479 StmtResult Body; 9480 { 9481 CompoundScopeRAII CompoundScope(*this); 9482 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9483 /*isStmtExpr=*/false); 9484 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9485 } 9486 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9487 9488 if (ASTMutationListener *L = getASTMutationListener()) { 9489 L->CompletedImplicitDefinition(MoveAssignOperator); 9490 } 9491} 9492 9493Sema::ImplicitExceptionSpecification 9494Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9495 CXXRecordDecl *ClassDecl = MD->getParent(); 9496 9497 ImplicitExceptionSpecification ExceptSpec(*this); 9498 if (ClassDecl->isInvalidDecl()) 9499 return ExceptSpec; 9500 9501 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9502 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9503 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9504 9505 // C++ [except.spec]p14: 9506 // An implicitly declared special member function (Clause 12) shall have an 9507 // exception-specification. [...] 9508 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9509 BaseEnd = ClassDecl->bases_end(); 9510 Base != BaseEnd; 9511 ++Base) { 9512 // Virtual bases are handled below. 9513 if (Base->isVirtual()) 9514 continue; 9515 9516 CXXRecordDecl *BaseClassDecl 9517 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9518 if (CXXConstructorDecl *CopyConstructor = 9519 LookupCopyingConstructor(BaseClassDecl, Quals)) 9520 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9521 } 9522 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9523 BaseEnd = ClassDecl->vbases_end(); 9524 Base != BaseEnd; 9525 ++Base) { 9526 CXXRecordDecl *BaseClassDecl 9527 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9528 if (CXXConstructorDecl *CopyConstructor = 9529 LookupCopyingConstructor(BaseClassDecl, Quals)) 9530 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9531 } 9532 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9533 FieldEnd = ClassDecl->field_end(); 9534 Field != FieldEnd; 9535 ++Field) { 9536 QualType FieldType = Context.getBaseElementType(Field->getType()); 9537 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9538 if (CXXConstructorDecl *CopyConstructor = 9539 LookupCopyingConstructor(FieldClassDecl, 9540 Quals | FieldType.getCVRQualifiers())) 9541 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9542 } 9543 } 9544 9545 return ExceptSpec; 9546} 9547 9548CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9549 CXXRecordDecl *ClassDecl) { 9550 // C++ [class.copy]p4: 9551 // If the class definition does not explicitly declare a copy 9552 // constructor, one is declared implicitly. 9553 assert(ClassDecl->needsImplicitCopyConstructor()); 9554 9555 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9556 if (DSM.isAlreadyBeingDeclared()) 9557 return 0; 9558 9559 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9560 QualType ArgType = ClassType; 9561 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9562 if (Const) 9563 ArgType = ArgType.withConst(); 9564 ArgType = Context.getLValueReferenceType(ArgType); 9565 9566 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9567 CXXCopyConstructor, 9568 Const); 9569 9570 DeclarationName Name 9571 = Context.DeclarationNames.getCXXConstructorName( 9572 Context.getCanonicalType(ClassType)); 9573 SourceLocation ClassLoc = ClassDecl->getLocation(); 9574 DeclarationNameInfo NameInfo(Name, ClassLoc); 9575 9576 // An implicitly-declared copy constructor is an inline public 9577 // member of its class. 9578 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9579 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9580 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9581 Constexpr); 9582 CopyConstructor->setAccess(AS_public); 9583 CopyConstructor->setDefaulted(); 9584 9585 // Build an exception specification pointing back at this member. 9586 FunctionProtoType::ExtProtoInfo EPI; 9587 EPI.ExceptionSpecType = EST_Unevaluated; 9588 EPI.ExceptionSpecDecl = CopyConstructor; 9589 CopyConstructor->setType( 9590 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9591 9592 // Add the parameter to the constructor. 9593 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9594 ClassLoc, ClassLoc, 9595 /*IdentifierInfo=*/0, 9596 ArgType, /*TInfo=*/0, 9597 SC_None, 0); 9598 CopyConstructor->setParams(FromParam); 9599 9600 CopyConstructor->setTrivial( 9601 ClassDecl->needsOverloadResolutionForCopyConstructor() 9602 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9603 : ClassDecl->hasTrivialCopyConstructor()); 9604 9605 // C++11 [class.copy]p8: 9606 // ... If the class definition does not explicitly declare a copy 9607 // constructor, there is no user-declared move constructor, and there is no 9608 // user-declared move assignment operator, a copy constructor is implicitly 9609 // declared as defaulted. 9610 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9611 SetDeclDeleted(CopyConstructor, ClassLoc); 9612 9613 // Note that we have declared this constructor. 9614 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9615 9616 if (Scope *S = getScopeForContext(ClassDecl)) 9617 PushOnScopeChains(CopyConstructor, S, false); 9618 ClassDecl->addDecl(CopyConstructor); 9619 9620 return CopyConstructor; 9621} 9622 9623void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9624 CXXConstructorDecl *CopyConstructor) { 9625 assert((CopyConstructor->isDefaulted() && 9626 CopyConstructor->isCopyConstructor() && 9627 !CopyConstructor->doesThisDeclarationHaveABody() && 9628 !CopyConstructor->isDeleted()) && 9629 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9630 9631 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9632 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9633 9634 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9635 DiagnosticErrorTrap Trap(Diags); 9636 9637 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9638 Trap.hasErrorOccurred()) { 9639 Diag(CurrentLocation, diag::note_member_synthesized_at) 9640 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9641 CopyConstructor->setInvalidDecl(); 9642 } else { 9643 Sema::CompoundScopeRAII CompoundScope(*this); 9644 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9645 CopyConstructor->getLocation(), 9646 MultiStmtArg(), 9647 /*isStmtExpr=*/false) 9648 .takeAs<Stmt>()); 9649 CopyConstructor->setImplicitlyDefined(true); 9650 } 9651 9652 CopyConstructor->setUsed(); 9653 if (ASTMutationListener *L = getASTMutationListener()) { 9654 L->CompletedImplicitDefinition(CopyConstructor); 9655 } 9656} 9657 9658Sema::ImplicitExceptionSpecification 9659Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9660 CXXRecordDecl *ClassDecl = MD->getParent(); 9661 9662 // C++ [except.spec]p14: 9663 // An implicitly declared special member function (Clause 12) shall have an 9664 // exception-specification. [...] 9665 ImplicitExceptionSpecification ExceptSpec(*this); 9666 if (ClassDecl->isInvalidDecl()) 9667 return ExceptSpec; 9668 9669 // Direct base-class constructors. 9670 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9671 BEnd = ClassDecl->bases_end(); 9672 B != BEnd; ++B) { 9673 if (B->isVirtual()) // Handled below. 9674 continue; 9675 9676 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9677 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9678 CXXConstructorDecl *Constructor = 9679 LookupMovingConstructor(BaseClassDecl, 0); 9680 // If this is a deleted function, add it anyway. This might be conformant 9681 // with the standard. This might not. I'm not sure. It might not matter. 9682 if (Constructor) 9683 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9684 } 9685 } 9686 9687 // Virtual base-class constructors. 9688 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9689 BEnd = ClassDecl->vbases_end(); 9690 B != BEnd; ++B) { 9691 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9692 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9693 CXXConstructorDecl *Constructor = 9694 LookupMovingConstructor(BaseClassDecl, 0); 9695 // If this is a deleted function, add it anyway. This might be conformant 9696 // with the standard. This might not. I'm not sure. It might not matter. 9697 if (Constructor) 9698 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9699 } 9700 } 9701 9702 // Field constructors. 9703 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9704 FEnd = ClassDecl->field_end(); 9705 F != FEnd; ++F) { 9706 QualType FieldType = Context.getBaseElementType(F->getType()); 9707 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9708 CXXConstructorDecl *Constructor = 9709 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9710 // If this is a deleted function, add it anyway. This might be conformant 9711 // with the standard. This might not. I'm not sure. It might not matter. 9712 // In particular, the problem is that this function never gets called. It 9713 // might just be ill-formed because this function attempts to refer to 9714 // a deleted function here. 9715 if (Constructor) 9716 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9717 } 9718 } 9719 9720 return ExceptSpec; 9721} 9722 9723CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9724 CXXRecordDecl *ClassDecl) { 9725 // C++11 [class.copy]p9: 9726 // If the definition of a class X does not explicitly declare a move 9727 // constructor, one will be implicitly declared as defaulted if and only if: 9728 // 9729 // - [first 4 bullets] 9730 assert(ClassDecl->needsImplicitMoveConstructor()); 9731 9732 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9733 if (DSM.isAlreadyBeingDeclared()) 9734 return 0; 9735 9736 // [Checked after we build the declaration] 9737 // - the move assignment operator would not be implicitly defined as 9738 // deleted, 9739 9740 // [DR1402]: 9741 // - each of X's non-static data members and direct or virtual base classes 9742 // has a type that either has a move constructor or is trivially copyable. 9743 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9744 ClassDecl->setFailedImplicitMoveConstructor(); 9745 return 0; 9746 } 9747 9748 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9749 QualType ArgType = Context.getRValueReferenceType(ClassType); 9750 9751 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9752 CXXMoveConstructor, 9753 false); 9754 9755 DeclarationName Name 9756 = Context.DeclarationNames.getCXXConstructorName( 9757 Context.getCanonicalType(ClassType)); 9758 SourceLocation ClassLoc = ClassDecl->getLocation(); 9759 DeclarationNameInfo NameInfo(Name, ClassLoc); 9760 9761 // C++0x [class.copy]p11: 9762 // An implicitly-declared copy/move constructor is an inline public 9763 // member of its class. 9764 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9765 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9766 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9767 Constexpr); 9768 MoveConstructor->setAccess(AS_public); 9769 MoveConstructor->setDefaulted(); 9770 9771 // Build an exception specification pointing back at this member. 9772 FunctionProtoType::ExtProtoInfo EPI; 9773 EPI.ExceptionSpecType = EST_Unevaluated; 9774 EPI.ExceptionSpecDecl = MoveConstructor; 9775 MoveConstructor->setType( 9776 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9777 9778 // Add the parameter to the constructor. 9779 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9780 ClassLoc, ClassLoc, 9781 /*IdentifierInfo=*/0, 9782 ArgType, /*TInfo=*/0, 9783 SC_None, 0); 9784 MoveConstructor->setParams(FromParam); 9785 9786 MoveConstructor->setTrivial( 9787 ClassDecl->needsOverloadResolutionForMoveConstructor() 9788 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9789 : ClassDecl->hasTrivialMoveConstructor()); 9790 9791 // C++0x [class.copy]p9: 9792 // If the definition of a class X does not explicitly declare a move 9793 // constructor, one will be implicitly declared as defaulted if and only if: 9794 // [...] 9795 // - the move constructor would not be implicitly defined as deleted. 9796 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9797 // Cache this result so that we don't try to generate this over and over 9798 // on every lookup, leaking memory and wasting time. 9799 ClassDecl->setFailedImplicitMoveConstructor(); 9800 return 0; 9801 } 9802 9803 // Note that we have declared this constructor. 9804 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9805 9806 if (Scope *S = getScopeForContext(ClassDecl)) 9807 PushOnScopeChains(MoveConstructor, S, false); 9808 ClassDecl->addDecl(MoveConstructor); 9809 9810 return MoveConstructor; 9811} 9812 9813void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9814 CXXConstructorDecl *MoveConstructor) { 9815 assert((MoveConstructor->isDefaulted() && 9816 MoveConstructor->isMoveConstructor() && 9817 !MoveConstructor->doesThisDeclarationHaveABody() && 9818 !MoveConstructor->isDeleted()) && 9819 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9820 9821 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9822 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9823 9824 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9825 DiagnosticErrorTrap Trap(Diags); 9826 9827 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9828 Trap.hasErrorOccurred()) { 9829 Diag(CurrentLocation, diag::note_member_synthesized_at) 9830 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9831 MoveConstructor->setInvalidDecl(); 9832 } else { 9833 Sema::CompoundScopeRAII CompoundScope(*this); 9834 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9835 MoveConstructor->getLocation(), 9836 MultiStmtArg(), 9837 /*isStmtExpr=*/false) 9838 .takeAs<Stmt>()); 9839 MoveConstructor->setImplicitlyDefined(true); 9840 } 9841 9842 MoveConstructor->setUsed(); 9843 9844 if (ASTMutationListener *L = getASTMutationListener()) { 9845 L->CompletedImplicitDefinition(MoveConstructor); 9846 } 9847} 9848 9849bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9850 return FD->isDeleted() && 9851 (FD->isDefaulted() || FD->isImplicit()) && 9852 isa<CXXMethodDecl>(FD); 9853} 9854 9855/// \brief Mark the call operator of the given lambda closure type as "used". 9856static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9857 CXXMethodDecl *CallOperator 9858 = cast<CXXMethodDecl>( 9859 Lambda->lookup( 9860 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9861 CallOperator->setReferenced(); 9862 CallOperator->setUsed(); 9863} 9864 9865void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9866 SourceLocation CurrentLocation, 9867 CXXConversionDecl *Conv) 9868{ 9869 CXXRecordDecl *Lambda = Conv->getParent(); 9870 9871 // Make sure that the lambda call operator is marked used. 9872 markLambdaCallOperatorUsed(*this, Lambda); 9873 9874 Conv->setUsed(); 9875 9876 SynthesizedFunctionScope Scope(*this, Conv); 9877 DiagnosticErrorTrap Trap(Diags); 9878 9879 // Return the address of the __invoke function. 9880 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9881 CXXMethodDecl *Invoke 9882 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9883 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9884 VK_LValue, Conv->getLocation()).take(); 9885 assert(FunctionRef && "Can't refer to __invoke function?"); 9886 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9887 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9888 Conv->getLocation(), 9889 Conv->getLocation())); 9890 9891 // Fill in the __invoke function with a dummy implementation. IR generation 9892 // will fill in the actual details. 9893 Invoke->setUsed(); 9894 Invoke->setReferenced(); 9895 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9896 9897 if (ASTMutationListener *L = getASTMutationListener()) { 9898 L->CompletedImplicitDefinition(Conv); 9899 L->CompletedImplicitDefinition(Invoke); 9900 } 9901} 9902 9903void Sema::DefineImplicitLambdaToBlockPointerConversion( 9904 SourceLocation CurrentLocation, 9905 CXXConversionDecl *Conv) 9906{ 9907 Conv->setUsed(); 9908 9909 SynthesizedFunctionScope Scope(*this, Conv); 9910 DiagnosticErrorTrap Trap(Diags); 9911 9912 // Copy-initialize the lambda object as needed to capture it. 9913 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9914 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9915 9916 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9917 Conv->getLocation(), 9918 Conv, DerefThis); 9919 9920 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9921 // behavior. Note that only the general conversion function does this 9922 // (since it's unusable otherwise); in the case where we inline the 9923 // block literal, it has block literal lifetime semantics. 9924 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9925 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9926 CK_CopyAndAutoreleaseBlockObject, 9927 BuildBlock.get(), 0, VK_RValue); 9928 9929 if (BuildBlock.isInvalid()) { 9930 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9931 Conv->setInvalidDecl(); 9932 return; 9933 } 9934 9935 // Create the return statement that returns the block from the conversion 9936 // function. 9937 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9938 if (Return.isInvalid()) { 9939 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9940 Conv->setInvalidDecl(); 9941 return; 9942 } 9943 9944 // Set the body of the conversion function. 9945 Stmt *ReturnS = Return.take(); 9946 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9947 Conv->getLocation(), 9948 Conv->getLocation())); 9949 9950 // We're done; notify the mutation listener, if any. 9951 if (ASTMutationListener *L = getASTMutationListener()) { 9952 L->CompletedImplicitDefinition(Conv); 9953 } 9954} 9955 9956/// \brief Determine whether the given list arguments contains exactly one 9957/// "real" (non-default) argument. 9958static bool hasOneRealArgument(MultiExprArg Args) { 9959 switch (Args.size()) { 9960 case 0: 9961 return false; 9962 9963 default: 9964 if (!Args[1]->isDefaultArgument()) 9965 return false; 9966 9967 // fall through 9968 case 1: 9969 return !Args[0]->isDefaultArgument(); 9970 } 9971 9972 return false; 9973} 9974 9975ExprResult 9976Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9977 CXXConstructorDecl *Constructor, 9978 MultiExprArg ExprArgs, 9979 bool HadMultipleCandidates, 9980 bool IsListInitialization, 9981 bool RequiresZeroInit, 9982 unsigned ConstructKind, 9983 SourceRange ParenRange) { 9984 bool Elidable = false; 9985 9986 // C++0x [class.copy]p34: 9987 // When certain criteria are met, an implementation is allowed to 9988 // omit the copy/move construction of a class object, even if the 9989 // copy/move constructor and/or destructor for the object have 9990 // side effects. [...] 9991 // - when a temporary class object that has not been bound to a 9992 // reference (12.2) would be copied/moved to a class object 9993 // with the same cv-unqualified type, the copy/move operation 9994 // can be omitted by constructing the temporary object 9995 // directly into the target of the omitted copy/move 9996 if (ConstructKind == CXXConstructExpr::CK_Complete && 9997 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9998 Expr *SubExpr = ExprArgs[0]; 9999 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10000 } 10001 10002 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10003 Elidable, ExprArgs, HadMultipleCandidates, 10004 IsListInitialization, RequiresZeroInit, 10005 ConstructKind, ParenRange); 10006} 10007 10008/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10009/// including handling of its default argument expressions. 10010ExprResult 10011Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10012 CXXConstructorDecl *Constructor, bool Elidable, 10013 MultiExprArg ExprArgs, 10014 bool HadMultipleCandidates, 10015 bool IsListInitialization, 10016 bool RequiresZeroInit, 10017 unsigned ConstructKind, 10018 SourceRange ParenRange) { 10019 MarkFunctionReferenced(ConstructLoc, Constructor); 10020 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10021 Constructor, Elidable, ExprArgs, 10022 HadMultipleCandidates, 10023 IsListInitialization, RequiresZeroInit, 10024 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10025 ParenRange)); 10026} 10027 10028void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10029 if (VD->isInvalidDecl()) return; 10030 10031 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10032 if (ClassDecl->isInvalidDecl()) return; 10033 if (ClassDecl->hasIrrelevantDestructor()) return; 10034 if (ClassDecl->isDependentContext()) return; 10035 10036 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10037 MarkFunctionReferenced(VD->getLocation(), Destructor); 10038 CheckDestructorAccess(VD->getLocation(), Destructor, 10039 PDiag(diag::err_access_dtor_var) 10040 << VD->getDeclName() 10041 << VD->getType()); 10042 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10043 10044 if (!VD->hasGlobalStorage()) return; 10045 10046 // Emit warning for non-trivial dtor in global scope (a real global, 10047 // class-static, function-static). 10048 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10049 10050 // TODO: this should be re-enabled for static locals by !CXAAtExit 10051 if (!VD->isStaticLocal()) 10052 Diag(VD->getLocation(), diag::warn_global_destructor); 10053} 10054 10055/// \brief Given a constructor and the set of arguments provided for the 10056/// constructor, convert the arguments and add any required default arguments 10057/// to form a proper call to this constructor. 10058/// 10059/// \returns true if an error occurred, false otherwise. 10060bool 10061Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10062 MultiExprArg ArgsPtr, 10063 SourceLocation Loc, 10064 SmallVectorImpl<Expr*> &ConvertedArgs, 10065 bool AllowExplicit, 10066 bool IsListInitialization) { 10067 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10068 unsigned NumArgs = ArgsPtr.size(); 10069 Expr **Args = ArgsPtr.data(); 10070 10071 const FunctionProtoType *Proto 10072 = Constructor->getType()->getAs<FunctionProtoType>(); 10073 assert(Proto && "Constructor without a prototype?"); 10074 unsigned NumArgsInProto = Proto->getNumArgs(); 10075 10076 // If too few arguments are available, we'll fill in the rest with defaults. 10077 if (NumArgs < NumArgsInProto) 10078 ConvertedArgs.reserve(NumArgsInProto); 10079 else 10080 ConvertedArgs.reserve(NumArgs); 10081 10082 VariadicCallType CallType = 10083 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10084 SmallVector<Expr *, 8> AllArgs; 10085 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10086 Proto, 0, Args, NumArgs, AllArgs, 10087 CallType, AllowExplicit, 10088 IsListInitialization); 10089 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10090 10091 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 10092 10093 CheckConstructorCall(Constructor, 10094 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10095 AllArgs.size()), 10096 Proto, Loc); 10097 10098 return Invalid; 10099} 10100 10101static inline bool 10102CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10103 const FunctionDecl *FnDecl) { 10104 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10105 if (isa<NamespaceDecl>(DC)) { 10106 return SemaRef.Diag(FnDecl->getLocation(), 10107 diag::err_operator_new_delete_declared_in_namespace) 10108 << FnDecl->getDeclName(); 10109 } 10110 10111 if (isa<TranslationUnitDecl>(DC) && 10112 FnDecl->getStorageClass() == SC_Static) { 10113 return SemaRef.Diag(FnDecl->getLocation(), 10114 diag::err_operator_new_delete_declared_static) 10115 << FnDecl->getDeclName(); 10116 } 10117 10118 return false; 10119} 10120 10121static inline bool 10122CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10123 CanQualType ExpectedResultType, 10124 CanQualType ExpectedFirstParamType, 10125 unsigned DependentParamTypeDiag, 10126 unsigned InvalidParamTypeDiag) { 10127 QualType ResultType = 10128 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10129 10130 // Check that the result type is not dependent. 10131 if (ResultType->isDependentType()) 10132 return SemaRef.Diag(FnDecl->getLocation(), 10133 diag::err_operator_new_delete_dependent_result_type) 10134 << FnDecl->getDeclName() << ExpectedResultType; 10135 10136 // Check that the result type is what we expect. 10137 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10138 return SemaRef.Diag(FnDecl->getLocation(), 10139 diag::err_operator_new_delete_invalid_result_type) 10140 << FnDecl->getDeclName() << ExpectedResultType; 10141 10142 // A function template must have at least 2 parameters. 10143 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10144 return SemaRef.Diag(FnDecl->getLocation(), 10145 diag::err_operator_new_delete_template_too_few_parameters) 10146 << FnDecl->getDeclName(); 10147 10148 // The function decl must have at least 1 parameter. 10149 if (FnDecl->getNumParams() == 0) 10150 return SemaRef.Diag(FnDecl->getLocation(), 10151 diag::err_operator_new_delete_too_few_parameters) 10152 << FnDecl->getDeclName(); 10153 10154 // Check the first parameter type is not dependent. 10155 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10156 if (FirstParamType->isDependentType()) 10157 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10158 << FnDecl->getDeclName() << ExpectedFirstParamType; 10159 10160 // Check that the first parameter type is what we expect. 10161 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10162 ExpectedFirstParamType) 10163 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10164 << FnDecl->getDeclName() << ExpectedFirstParamType; 10165 10166 return false; 10167} 10168 10169static bool 10170CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10171 // C++ [basic.stc.dynamic.allocation]p1: 10172 // A program is ill-formed if an allocation function is declared in a 10173 // namespace scope other than global scope or declared static in global 10174 // scope. 10175 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10176 return true; 10177 10178 CanQualType SizeTy = 10179 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10180 10181 // C++ [basic.stc.dynamic.allocation]p1: 10182 // The return type shall be void*. The first parameter shall have type 10183 // std::size_t. 10184 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10185 SizeTy, 10186 diag::err_operator_new_dependent_param_type, 10187 diag::err_operator_new_param_type)) 10188 return true; 10189 10190 // C++ [basic.stc.dynamic.allocation]p1: 10191 // The first parameter shall not have an associated default argument. 10192 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10193 return SemaRef.Diag(FnDecl->getLocation(), 10194 diag::err_operator_new_default_arg) 10195 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10196 10197 return false; 10198} 10199 10200static bool 10201CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10202 // C++ [basic.stc.dynamic.deallocation]p1: 10203 // A program is ill-formed if deallocation functions are declared in a 10204 // namespace scope other than global scope or declared static in global 10205 // scope. 10206 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10207 return true; 10208 10209 // C++ [basic.stc.dynamic.deallocation]p2: 10210 // Each deallocation function shall return void and its first parameter 10211 // shall be void*. 10212 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10213 SemaRef.Context.VoidPtrTy, 10214 diag::err_operator_delete_dependent_param_type, 10215 diag::err_operator_delete_param_type)) 10216 return true; 10217 10218 return false; 10219} 10220 10221/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10222/// of this overloaded operator is well-formed. If so, returns false; 10223/// otherwise, emits appropriate diagnostics and returns true. 10224bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10225 assert(FnDecl && FnDecl->isOverloadedOperator() && 10226 "Expected an overloaded operator declaration"); 10227 10228 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10229 10230 // C++ [over.oper]p5: 10231 // The allocation and deallocation functions, operator new, 10232 // operator new[], operator delete and operator delete[], are 10233 // described completely in 3.7.3. The attributes and restrictions 10234 // found in the rest of this subclause do not apply to them unless 10235 // explicitly stated in 3.7.3. 10236 if (Op == OO_Delete || Op == OO_Array_Delete) 10237 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10238 10239 if (Op == OO_New || Op == OO_Array_New) 10240 return CheckOperatorNewDeclaration(*this, FnDecl); 10241 10242 // C++ [over.oper]p6: 10243 // An operator function shall either be a non-static member 10244 // function or be a non-member function and have at least one 10245 // parameter whose type is a class, a reference to a class, an 10246 // enumeration, or a reference to an enumeration. 10247 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10248 if (MethodDecl->isStatic()) 10249 return Diag(FnDecl->getLocation(), 10250 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10251 } else { 10252 bool ClassOrEnumParam = false; 10253 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10254 ParamEnd = FnDecl->param_end(); 10255 Param != ParamEnd; ++Param) { 10256 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10257 if (ParamType->isDependentType() || ParamType->isRecordType() || 10258 ParamType->isEnumeralType()) { 10259 ClassOrEnumParam = true; 10260 break; 10261 } 10262 } 10263 10264 if (!ClassOrEnumParam) 10265 return Diag(FnDecl->getLocation(), 10266 diag::err_operator_overload_needs_class_or_enum) 10267 << FnDecl->getDeclName(); 10268 } 10269 10270 // C++ [over.oper]p8: 10271 // An operator function cannot have default arguments (8.3.6), 10272 // except where explicitly stated below. 10273 // 10274 // Only the function-call operator allows default arguments 10275 // (C++ [over.call]p1). 10276 if (Op != OO_Call) { 10277 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10278 Param != FnDecl->param_end(); ++Param) { 10279 if ((*Param)->hasDefaultArg()) 10280 return Diag((*Param)->getLocation(), 10281 diag::err_operator_overload_default_arg) 10282 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10283 } 10284 } 10285 10286 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10287 { false, false, false } 10288#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10289 , { Unary, Binary, MemberOnly } 10290#include "clang/Basic/OperatorKinds.def" 10291 }; 10292 10293 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10294 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10295 bool MustBeMemberOperator = OperatorUses[Op][2]; 10296 10297 // C++ [over.oper]p8: 10298 // [...] Operator functions cannot have more or fewer parameters 10299 // than the number required for the corresponding operator, as 10300 // described in the rest of this subclause. 10301 unsigned NumParams = FnDecl->getNumParams() 10302 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10303 if (Op != OO_Call && 10304 ((NumParams == 1 && !CanBeUnaryOperator) || 10305 (NumParams == 2 && !CanBeBinaryOperator) || 10306 (NumParams < 1) || (NumParams > 2))) { 10307 // We have the wrong number of parameters. 10308 unsigned ErrorKind; 10309 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10310 ErrorKind = 2; // 2 -> unary or binary. 10311 } else if (CanBeUnaryOperator) { 10312 ErrorKind = 0; // 0 -> unary 10313 } else { 10314 assert(CanBeBinaryOperator && 10315 "All non-call overloaded operators are unary or binary!"); 10316 ErrorKind = 1; // 1 -> binary 10317 } 10318 10319 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10320 << FnDecl->getDeclName() << NumParams << ErrorKind; 10321 } 10322 10323 // Overloaded operators other than operator() cannot be variadic. 10324 if (Op != OO_Call && 10325 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10326 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10327 << FnDecl->getDeclName(); 10328 } 10329 10330 // Some operators must be non-static member functions. 10331 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10332 return Diag(FnDecl->getLocation(), 10333 diag::err_operator_overload_must_be_member) 10334 << FnDecl->getDeclName(); 10335 } 10336 10337 // C++ [over.inc]p1: 10338 // The user-defined function called operator++ implements the 10339 // prefix and postfix ++ operator. If this function is a member 10340 // function with no parameters, or a non-member function with one 10341 // parameter of class or enumeration type, it defines the prefix 10342 // increment operator ++ for objects of that type. If the function 10343 // is a member function with one parameter (which shall be of type 10344 // int) or a non-member function with two parameters (the second 10345 // of which shall be of type int), it defines the postfix 10346 // increment operator ++ for objects of that type. 10347 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10348 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10349 bool ParamIsInt = false; 10350 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10351 ParamIsInt = BT->getKind() == BuiltinType::Int; 10352 10353 if (!ParamIsInt) 10354 return Diag(LastParam->getLocation(), 10355 diag::err_operator_overload_post_incdec_must_be_int) 10356 << LastParam->getType() << (Op == OO_MinusMinus); 10357 } 10358 10359 return false; 10360} 10361 10362/// CheckLiteralOperatorDeclaration - Check whether the declaration 10363/// of this literal operator function is well-formed. If so, returns 10364/// false; otherwise, emits appropriate diagnostics and returns true. 10365bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10366 if (isa<CXXMethodDecl>(FnDecl)) { 10367 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10368 << FnDecl->getDeclName(); 10369 return true; 10370 } 10371 10372 if (FnDecl->isExternC()) { 10373 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10374 return true; 10375 } 10376 10377 bool Valid = false; 10378 10379 // This might be the definition of a literal operator template. 10380 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10381 // This might be a specialization of a literal operator template. 10382 if (!TpDecl) 10383 TpDecl = FnDecl->getPrimaryTemplate(); 10384 10385 // template <char...> type operator "" name() is the only valid template 10386 // signature, and the only valid signature with no parameters. 10387 if (TpDecl) { 10388 if (FnDecl->param_size() == 0) { 10389 // Must have only one template parameter 10390 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10391 if (Params->size() == 1) { 10392 NonTypeTemplateParmDecl *PmDecl = 10393 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10394 10395 // The template parameter must be a char parameter pack. 10396 if (PmDecl && PmDecl->isTemplateParameterPack() && 10397 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10398 Valid = true; 10399 } 10400 } 10401 } else if (FnDecl->param_size()) { 10402 // Check the first parameter 10403 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10404 10405 QualType T = (*Param)->getType().getUnqualifiedType(); 10406 10407 // unsigned long long int, long double, and any character type are allowed 10408 // as the only parameters. 10409 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10410 Context.hasSameType(T, Context.LongDoubleTy) || 10411 Context.hasSameType(T, Context.CharTy) || 10412 Context.hasSameType(T, Context.WCharTy) || 10413 Context.hasSameType(T, Context.Char16Ty) || 10414 Context.hasSameType(T, Context.Char32Ty)) { 10415 if (++Param == FnDecl->param_end()) 10416 Valid = true; 10417 goto FinishedParams; 10418 } 10419 10420 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10421 const PointerType *PT = T->getAs<PointerType>(); 10422 if (!PT) 10423 goto FinishedParams; 10424 T = PT->getPointeeType(); 10425 if (!T.isConstQualified() || T.isVolatileQualified()) 10426 goto FinishedParams; 10427 T = T.getUnqualifiedType(); 10428 10429 // Move on to the second parameter; 10430 ++Param; 10431 10432 // If there is no second parameter, the first must be a const char * 10433 if (Param == FnDecl->param_end()) { 10434 if (Context.hasSameType(T, Context.CharTy)) 10435 Valid = true; 10436 goto FinishedParams; 10437 } 10438 10439 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10440 // are allowed as the first parameter to a two-parameter function 10441 if (!(Context.hasSameType(T, Context.CharTy) || 10442 Context.hasSameType(T, Context.WCharTy) || 10443 Context.hasSameType(T, Context.Char16Ty) || 10444 Context.hasSameType(T, Context.Char32Ty))) 10445 goto FinishedParams; 10446 10447 // The second and final parameter must be an std::size_t 10448 T = (*Param)->getType().getUnqualifiedType(); 10449 if (Context.hasSameType(T, Context.getSizeType()) && 10450 ++Param == FnDecl->param_end()) 10451 Valid = true; 10452 } 10453 10454 // FIXME: This diagnostic is absolutely terrible. 10455FinishedParams: 10456 if (!Valid) { 10457 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10458 << FnDecl->getDeclName(); 10459 return true; 10460 } 10461 10462 // A parameter-declaration-clause containing a default argument is not 10463 // equivalent to any of the permitted forms. 10464 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10465 ParamEnd = FnDecl->param_end(); 10466 Param != ParamEnd; ++Param) { 10467 if ((*Param)->hasDefaultArg()) { 10468 Diag((*Param)->getDefaultArgRange().getBegin(), 10469 diag::err_literal_operator_default_argument) 10470 << (*Param)->getDefaultArgRange(); 10471 break; 10472 } 10473 } 10474 10475 StringRef LiteralName 10476 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10477 if (LiteralName[0] != '_') { 10478 // C++11 [usrlit.suffix]p1: 10479 // Literal suffix identifiers that do not start with an underscore 10480 // are reserved for future standardization. 10481 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10482 } 10483 10484 return false; 10485} 10486 10487/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10488/// linkage specification, including the language and (if present) 10489/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10490/// the location of the language string literal, which is provided 10491/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10492/// the '{' brace. Otherwise, this linkage specification does not 10493/// have any braces. 10494Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10495 SourceLocation LangLoc, 10496 StringRef Lang, 10497 SourceLocation LBraceLoc) { 10498 LinkageSpecDecl::LanguageIDs Language; 10499 if (Lang == "\"C\"") 10500 Language = LinkageSpecDecl::lang_c; 10501 else if (Lang == "\"C++\"") 10502 Language = LinkageSpecDecl::lang_cxx; 10503 else { 10504 Diag(LangLoc, diag::err_bad_language); 10505 return 0; 10506 } 10507 10508 // FIXME: Add all the various semantics of linkage specifications 10509 10510 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10511 ExternLoc, LangLoc, Language, 10512 LBraceLoc.isValid()); 10513 CurContext->addDecl(D); 10514 PushDeclContext(S, D); 10515 return D; 10516} 10517 10518/// ActOnFinishLinkageSpecification - Complete the definition of 10519/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10520/// valid, it's the position of the closing '}' brace in a linkage 10521/// specification that uses braces. 10522Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10523 Decl *LinkageSpec, 10524 SourceLocation RBraceLoc) { 10525 if (LinkageSpec) { 10526 if (RBraceLoc.isValid()) { 10527 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10528 LSDecl->setRBraceLoc(RBraceLoc); 10529 } 10530 PopDeclContext(); 10531 } 10532 return LinkageSpec; 10533} 10534 10535Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10536 AttributeList *AttrList, 10537 SourceLocation SemiLoc) { 10538 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10539 // Attribute declarations appertain to empty declaration so we handle 10540 // them here. 10541 if (AttrList) 10542 ProcessDeclAttributeList(S, ED, AttrList); 10543 10544 CurContext->addDecl(ED); 10545 return ED; 10546} 10547 10548/// \brief Perform semantic analysis for the variable declaration that 10549/// occurs within a C++ catch clause, returning the newly-created 10550/// variable. 10551VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10552 TypeSourceInfo *TInfo, 10553 SourceLocation StartLoc, 10554 SourceLocation Loc, 10555 IdentifierInfo *Name) { 10556 bool Invalid = false; 10557 QualType ExDeclType = TInfo->getType(); 10558 10559 // Arrays and functions decay. 10560 if (ExDeclType->isArrayType()) 10561 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10562 else if (ExDeclType->isFunctionType()) 10563 ExDeclType = Context.getPointerType(ExDeclType); 10564 10565 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10566 // The exception-declaration shall not denote a pointer or reference to an 10567 // incomplete type, other than [cv] void*. 10568 // N2844 forbids rvalue references. 10569 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10570 Diag(Loc, diag::err_catch_rvalue_ref); 10571 Invalid = true; 10572 } 10573 10574 QualType BaseType = ExDeclType; 10575 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10576 unsigned DK = diag::err_catch_incomplete; 10577 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10578 BaseType = Ptr->getPointeeType(); 10579 Mode = 1; 10580 DK = diag::err_catch_incomplete_ptr; 10581 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10582 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10583 BaseType = Ref->getPointeeType(); 10584 Mode = 2; 10585 DK = diag::err_catch_incomplete_ref; 10586 } 10587 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10588 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10589 Invalid = true; 10590 10591 if (!Invalid && !ExDeclType->isDependentType() && 10592 RequireNonAbstractType(Loc, ExDeclType, 10593 diag::err_abstract_type_in_decl, 10594 AbstractVariableType)) 10595 Invalid = true; 10596 10597 // Only the non-fragile NeXT runtime currently supports C++ catches 10598 // of ObjC types, and no runtime supports catching ObjC types by value. 10599 if (!Invalid && getLangOpts().ObjC1) { 10600 QualType T = ExDeclType; 10601 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10602 T = RT->getPointeeType(); 10603 10604 if (T->isObjCObjectType()) { 10605 Diag(Loc, diag::err_objc_object_catch); 10606 Invalid = true; 10607 } else if (T->isObjCObjectPointerType()) { 10608 // FIXME: should this be a test for macosx-fragile specifically? 10609 if (getLangOpts().ObjCRuntime.isFragile()) 10610 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10611 } 10612 } 10613 10614 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10615 ExDeclType, TInfo, SC_None); 10616 ExDecl->setExceptionVariable(true); 10617 10618 // In ARC, infer 'retaining' for variables of retainable type. 10619 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10620 Invalid = true; 10621 10622 if (!Invalid && !ExDeclType->isDependentType()) { 10623 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10624 // Insulate this from anything else we might currently be parsing. 10625 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10626 10627 // C++ [except.handle]p16: 10628 // The object declared in an exception-declaration or, if the 10629 // exception-declaration does not specify a name, a temporary (12.2) is 10630 // copy-initialized (8.5) from the exception object. [...] 10631 // The object is destroyed when the handler exits, after the destruction 10632 // of any automatic objects initialized within the handler. 10633 // 10634 // We just pretend to initialize the object with itself, then make sure 10635 // it can be destroyed later. 10636 QualType initType = ExDeclType; 10637 10638 InitializedEntity entity = 10639 InitializedEntity::InitializeVariable(ExDecl); 10640 InitializationKind initKind = 10641 InitializationKind::CreateCopy(Loc, SourceLocation()); 10642 10643 Expr *opaqueValue = 10644 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10645 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 10646 ExprResult result = sequence.Perform(*this, entity, initKind, 10647 MultiExprArg(&opaqueValue, 1)); 10648 if (result.isInvalid()) 10649 Invalid = true; 10650 else { 10651 // If the constructor used was non-trivial, set this as the 10652 // "initializer". 10653 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10654 if (!construct->getConstructor()->isTrivial()) { 10655 Expr *init = MaybeCreateExprWithCleanups(construct); 10656 ExDecl->setInit(init); 10657 } 10658 10659 // And make sure it's destructable. 10660 FinalizeVarWithDestructor(ExDecl, recordType); 10661 } 10662 } 10663 } 10664 10665 if (Invalid) 10666 ExDecl->setInvalidDecl(); 10667 10668 return ExDecl; 10669} 10670 10671/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10672/// handler. 10673Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10674 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10675 bool Invalid = D.isInvalidType(); 10676 10677 // Check for unexpanded parameter packs. 10678 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10679 UPPC_ExceptionType)) { 10680 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10681 D.getIdentifierLoc()); 10682 Invalid = true; 10683 } 10684 10685 IdentifierInfo *II = D.getIdentifier(); 10686 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10687 LookupOrdinaryName, 10688 ForRedeclaration)) { 10689 // The scope should be freshly made just for us. There is just no way 10690 // it contains any previous declaration. 10691 assert(!S->isDeclScope(PrevDecl)); 10692 if (PrevDecl->isTemplateParameter()) { 10693 // Maybe we will complain about the shadowed template parameter. 10694 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10695 PrevDecl = 0; 10696 } 10697 } 10698 10699 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10700 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10701 << D.getCXXScopeSpec().getRange(); 10702 Invalid = true; 10703 } 10704 10705 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10706 D.getLocStart(), 10707 D.getIdentifierLoc(), 10708 D.getIdentifier()); 10709 if (Invalid) 10710 ExDecl->setInvalidDecl(); 10711 10712 // Add the exception declaration into this scope. 10713 if (II) 10714 PushOnScopeChains(ExDecl, S); 10715 else 10716 CurContext->addDecl(ExDecl); 10717 10718 ProcessDeclAttributes(S, ExDecl, D); 10719 return ExDecl; 10720} 10721 10722Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10723 Expr *AssertExpr, 10724 Expr *AssertMessageExpr, 10725 SourceLocation RParenLoc) { 10726 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10727 10728 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10729 return 0; 10730 10731 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10732 AssertMessage, RParenLoc, false); 10733} 10734 10735Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10736 Expr *AssertExpr, 10737 StringLiteral *AssertMessage, 10738 SourceLocation RParenLoc, 10739 bool Failed) { 10740 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10741 !Failed) { 10742 // In a static_assert-declaration, the constant-expression shall be a 10743 // constant expression that can be contextually converted to bool. 10744 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10745 if (Converted.isInvalid()) 10746 Failed = true; 10747 10748 llvm::APSInt Cond; 10749 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10750 diag::err_static_assert_expression_is_not_constant, 10751 /*AllowFold=*/false).isInvalid()) 10752 Failed = true; 10753 10754 if (!Failed && !Cond) { 10755 SmallString<256> MsgBuffer; 10756 llvm::raw_svector_ostream Msg(MsgBuffer); 10757 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10758 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10759 << Msg.str() << AssertExpr->getSourceRange(); 10760 Failed = true; 10761 } 10762 } 10763 10764 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10765 AssertExpr, AssertMessage, RParenLoc, 10766 Failed); 10767 10768 CurContext->addDecl(Decl); 10769 return Decl; 10770} 10771 10772/// \brief Perform semantic analysis of the given friend type declaration. 10773/// 10774/// \returns A friend declaration that. 10775FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10776 SourceLocation FriendLoc, 10777 TypeSourceInfo *TSInfo) { 10778 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10779 10780 QualType T = TSInfo->getType(); 10781 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10782 10783 // C++03 [class.friend]p2: 10784 // An elaborated-type-specifier shall be used in a friend declaration 10785 // for a class.* 10786 // 10787 // * The class-key of the elaborated-type-specifier is required. 10788 if (!ActiveTemplateInstantiations.empty()) { 10789 // Do not complain about the form of friend template types during 10790 // template instantiation; we will already have complained when the 10791 // template was declared. 10792 } else { 10793 if (!T->isElaboratedTypeSpecifier()) { 10794 // If we evaluated the type to a record type, suggest putting 10795 // a tag in front. 10796 if (const RecordType *RT = T->getAs<RecordType>()) { 10797 RecordDecl *RD = RT->getDecl(); 10798 10799 std::string InsertionText = std::string(" ") + RD->getKindName(); 10800 10801 Diag(TypeRange.getBegin(), 10802 getLangOpts().CPlusPlus11 ? 10803 diag::warn_cxx98_compat_unelaborated_friend_type : 10804 diag::ext_unelaborated_friend_type) 10805 << (unsigned) RD->getTagKind() 10806 << T 10807 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10808 InsertionText); 10809 } else { 10810 Diag(FriendLoc, 10811 getLangOpts().CPlusPlus11 ? 10812 diag::warn_cxx98_compat_nonclass_type_friend : 10813 diag::ext_nonclass_type_friend) 10814 << T 10815 << TypeRange; 10816 } 10817 } else if (T->getAs<EnumType>()) { 10818 Diag(FriendLoc, 10819 getLangOpts().CPlusPlus11 ? 10820 diag::warn_cxx98_compat_enum_friend : 10821 diag::ext_enum_friend) 10822 << T 10823 << TypeRange; 10824 } 10825 10826 // C++11 [class.friend]p3: 10827 // A friend declaration that does not declare a function shall have one 10828 // of the following forms: 10829 // friend elaborated-type-specifier ; 10830 // friend simple-type-specifier ; 10831 // friend typename-specifier ; 10832 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10833 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10834 } 10835 10836 // If the type specifier in a friend declaration designates a (possibly 10837 // cv-qualified) class type, that class is declared as a friend; otherwise, 10838 // the friend declaration is ignored. 10839 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10840} 10841 10842/// Handle a friend tag declaration where the scope specifier was 10843/// templated. 10844Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10845 unsigned TagSpec, SourceLocation TagLoc, 10846 CXXScopeSpec &SS, 10847 IdentifierInfo *Name, 10848 SourceLocation NameLoc, 10849 AttributeList *Attr, 10850 MultiTemplateParamsArg TempParamLists) { 10851 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10852 10853 bool isExplicitSpecialization = false; 10854 bool Invalid = false; 10855 10856 if (TemplateParameterList *TemplateParams 10857 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10858 TempParamLists.data(), 10859 TempParamLists.size(), 10860 /*friend*/ true, 10861 isExplicitSpecialization, 10862 Invalid)) { 10863 if (TemplateParams->size() > 0) { 10864 // This is a declaration of a class template. 10865 if (Invalid) 10866 return 0; 10867 10868 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10869 SS, Name, NameLoc, Attr, 10870 TemplateParams, AS_public, 10871 /*ModulePrivateLoc=*/SourceLocation(), 10872 TempParamLists.size() - 1, 10873 TempParamLists.data()).take(); 10874 } else { 10875 // The "template<>" header is extraneous. 10876 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10877 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10878 isExplicitSpecialization = true; 10879 } 10880 } 10881 10882 if (Invalid) return 0; 10883 10884 bool isAllExplicitSpecializations = true; 10885 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10886 if (TempParamLists[I]->size()) { 10887 isAllExplicitSpecializations = false; 10888 break; 10889 } 10890 } 10891 10892 // FIXME: don't ignore attributes. 10893 10894 // If it's explicit specializations all the way down, just forget 10895 // about the template header and build an appropriate non-templated 10896 // friend. TODO: for source fidelity, remember the headers. 10897 if (isAllExplicitSpecializations) { 10898 if (SS.isEmpty()) { 10899 bool Owned = false; 10900 bool IsDependent = false; 10901 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10902 Attr, AS_public, 10903 /*ModulePrivateLoc=*/SourceLocation(), 10904 MultiTemplateParamsArg(), Owned, IsDependent, 10905 /*ScopedEnumKWLoc=*/SourceLocation(), 10906 /*ScopedEnumUsesClassTag=*/false, 10907 /*UnderlyingType=*/TypeResult()); 10908 } 10909 10910 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10911 ElaboratedTypeKeyword Keyword 10912 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10913 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10914 *Name, NameLoc); 10915 if (T.isNull()) 10916 return 0; 10917 10918 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10919 if (isa<DependentNameType>(T)) { 10920 DependentNameTypeLoc TL = 10921 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10922 TL.setElaboratedKeywordLoc(TagLoc); 10923 TL.setQualifierLoc(QualifierLoc); 10924 TL.setNameLoc(NameLoc); 10925 } else { 10926 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 10927 TL.setElaboratedKeywordLoc(TagLoc); 10928 TL.setQualifierLoc(QualifierLoc); 10929 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 10930 } 10931 10932 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10933 TSI, FriendLoc, TempParamLists); 10934 Friend->setAccess(AS_public); 10935 CurContext->addDecl(Friend); 10936 return Friend; 10937 } 10938 10939 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10940 10941 10942 10943 // Handle the case of a templated-scope friend class. e.g. 10944 // template <class T> class A<T>::B; 10945 // FIXME: we don't support these right now. 10946 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10947 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10948 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10949 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10950 TL.setElaboratedKeywordLoc(TagLoc); 10951 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10952 TL.setNameLoc(NameLoc); 10953 10954 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10955 TSI, FriendLoc, TempParamLists); 10956 Friend->setAccess(AS_public); 10957 Friend->setUnsupportedFriend(true); 10958 CurContext->addDecl(Friend); 10959 return Friend; 10960} 10961 10962 10963/// Handle a friend type declaration. This works in tandem with 10964/// ActOnTag. 10965/// 10966/// Notes on friend class templates: 10967/// 10968/// We generally treat friend class declarations as if they were 10969/// declaring a class. So, for example, the elaborated type specifier 10970/// in a friend declaration is required to obey the restrictions of a 10971/// class-head (i.e. no typedefs in the scope chain), template 10972/// parameters are required to match up with simple template-ids, &c. 10973/// However, unlike when declaring a template specialization, it's 10974/// okay to refer to a template specialization without an empty 10975/// template parameter declaration, e.g. 10976/// friend class A<T>::B<unsigned>; 10977/// We permit this as a special case; if there are any template 10978/// parameters present at all, require proper matching, i.e. 10979/// template <> template \<class T> friend class A<int>::B; 10980Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10981 MultiTemplateParamsArg TempParams) { 10982 SourceLocation Loc = DS.getLocStart(); 10983 10984 assert(DS.isFriendSpecified()); 10985 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10986 10987 // Try to convert the decl specifier to a type. This works for 10988 // friend templates because ActOnTag never produces a ClassTemplateDecl 10989 // for a TUK_Friend. 10990 Declarator TheDeclarator(DS, Declarator::MemberContext); 10991 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10992 QualType T = TSI->getType(); 10993 if (TheDeclarator.isInvalidType()) 10994 return 0; 10995 10996 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10997 return 0; 10998 10999 // This is definitely an error in C++98. It's probably meant to 11000 // be forbidden in C++0x, too, but the specification is just 11001 // poorly written. 11002 // 11003 // The problem is with declarations like the following: 11004 // template <T> friend A<T>::foo; 11005 // where deciding whether a class C is a friend or not now hinges 11006 // on whether there exists an instantiation of A that causes 11007 // 'foo' to equal C. There are restrictions on class-heads 11008 // (which we declare (by fiat) elaborated friend declarations to 11009 // be) that makes this tractable. 11010 // 11011 // FIXME: handle "template <> friend class A<T>;", which 11012 // is possibly well-formed? Who even knows? 11013 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11014 Diag(Loc, diag::err_tagless_friend_type_template) 11015 << DS.getSourceRange(); 11016 return 0; 11017 } 11018 11019 // C++98 [class.friend]p1: A friend of a class is a function 11020 // or class that is not a member of the class . . . 11021 // This is fixed in DR77, which just barely didn't make the C++03 11022 // deadline. It's also a very silly restriction that seriously 11023 // affects inner classes and which nobody else seems to implement; 11024 // thus we never diagnose it, not even in -pedantic. 11025 // 11026 // But note that we could warn about it: it's always useless to 11027 // friend one of your own members (it's not, however, worthless to 11028 // friend a member of an arbitrary specialization of your template). 11029 11030 Decl *D; 11031 if (unsigned NumTempParamLists = TempParams.size()) 11032 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11033 NumTempParamLists, 11034 TempParams.data(), 11035 TSI, 11036 DS.getFriendSpecLoc()); 11037 else 11038 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11039 11040 if (!D) 11041 return 0; 11042 11043 D->setAccess(AS_public); 11044 CurContext->addDecl(D); 11045 11046 return D; 11047} 11048 11049NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11050 MultiTemplateParamsArg TemplateParams) { 11051 const DeclSpec &DS = D.getDeclSpec(); 11052 11053 assert(DS.isFriendSpecified()); 11054 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11055 11056 SourceLocation Loc = D.getIdentifierLoc(); 11057 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11058 11059 // C++ [class.friend]p1 11060 // A friend of a class is a function or class.... 11061 // Note that this sees through typedefs, which is intended. 11062 // It *doesn't* see through dependent types, which is correct 11063 // according to [temp.arg.type]p3: 11064 // If a declaration acquires a function type through a 11065 // type dependent on a template-parameter and this causes 11066 // a declaration that does not use the syntactic form of a 11067 // function declarator to have a function type, the program 11068 // is ill-formed. 11069 if (!TInfo->getType()->isFunctionType()) { 11070 Diag(Loc, diag::err_unexpected_friend); 11071 11072 // It might be worthwhile to try to recover by creating an 11073 // appropriate declaration. 11074 return 0; 11075 } 11076 11077 // C++ [namespace.memdef]p3 11078 // - If a friend declaration in a non-local class first declares a 11079 // class or function, the friend class or function is a member 11080 // of the innermost enclosing namespace. 11081 // - The name of the friend is not found by simple name lookup 11082 // until a matching declaration is provided in that namespace 11083 // scope (either before or after the class declaration granting 11084 // friendship). 11085 // - If a friend function is called, its name may be found by the 11086 // name lookup that considers functions from namespaces and 11087 // classes associated with the types of the function arguments. 11088 // - When looking for a prior declaration of a class or a function 11089 // declared as a friend, scopes outside the innermost enclosing 11090 // namespace scope are not considered. 11091 11092 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11093 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11094 DeclarationName Name = NameInfo.getName(); 11095 assert(Name); 11096 11097 // Check for unexpanded parameter packs. 11098 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11099 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11100 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11101 return 0; 11102 11103 // The context we found the declaration in, or in which we should 11104 // create the declaration. 11105 DeclContext *DC; 11106 Scope *DCScope = S; 11107 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11108 ForRedeclaration); 11109 11110 // FIXME: there are different rules in local classes 11111 11112 // There are four cases here. 11113 // - There's no scope specifier, in which case we just go to the 11114 // appropriate scope and look for a function or function template 11115 // there as appropriate. 11116 // Recover from invalid scope qualifiers as if they just weren't there. 11117 if (SS.isInvalid() || !SS.isSet()) { 11118 // C++0x [namespace.memdef]p3: 11119 // If the name in a friend declaration is neither qualified nor 11120 // a template-id and the declaration is a function or an 11121 // elaborated-type-specifier, the lookup to determine whether 11122 // the entity has been previously declared shall not consider 11123 // any scopes outside the innermost enclosing namespace. 11124 // C++0x [class.friend]p11: 11125 // If a friend declaration appears in a local class and the name 11126 // specified is an unqualified name, a prior declaration is 11127 // looked up without considering scopes that are outside the 11128 // innermost enclosing non-class scope. For a friend function 11129 // declaration, if there is no prior declaration, the program is 11130 // ill-formed. 11131 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 11132 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11133 11134 // Find the appropriate context according to the above. 11135 DC = CurContext; 11136 11137 // Skip class contexts. If someone can cite chapter and verse 11138 // for this behavior, that would be nice --- it's what GCC and 11139 // EDG do, and it seems like a reasonable intent, but the spec 11140 // really only says that checks for unqualified existing 11141 // declarations should stop at the nearest enclosing namespace, 11142 // not that they should only consider the nearest enclosing 11143 // namespace. 11144 while (DC->isRecord()) 11145 DC = DC->getParent(); 11146 11147 DeclContext *LookupDC = DC; 11148 while (LookupDC->isTransparentContext()) 11149 LookupDC = LookupDC->getParent(); 11150 11151 while (true) { 11152 LookupQualifiedName(Previous, LookupDC); 11153 11154 // TODO: decide what we think about using declarations. 11155 if (isLocal) 11156 break; 11157 11158 if (!Previous.empty()) { 11159 DC = LookupDC; 11160 break; 11161 } 11162 11163 if (isTemplateId) { 11164 if (isa<TranslationUnitDecl>(LookupDC)) break; 11165 } else { 11166 if (LookupDC->isFileContext()) break; 11167 } 11168 LookupDC = LookupDC->getParent(); 11169 } 11170 11171 DCScope = getScopeForDeclContext(S, DC); 11172 11173 // C++ [class.friend]p6: 11174 // A function can be defined in a friend declaration of a class if and 11175 // only if the class is a non-local class (9.8), the function name is 11176 // unqualified, and the function has namespace scope. 11177 if (isLocal && D.isFunctionDefinition()) { 11178 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11179 } 11180 11181 // - There's a non-dependent scope specifier, in which case we 11182 // compute it and do a previous lookup there for a function 11183 // or function template. 11184 } else if (!SS.getScopeRep()->isDependent()) { 11185 DC = computeDeclContext(SS); 11186 if (!DC) return 0; 11187 11188 if (RequireCompleteDeclContext(SS, DC)) return 0; 11189 11190 LookupQualifiedName(Previous, DC); 11191 11192 // Ignore things found implicitly in the wrong scope. 11193 // TODO: better diagnostics for this case. Suggesting the right 11194 // qualified scope would be nice... 11195 LookupResult::Filter F = Previous.makeFilter(); 11196 while (F.hasNext()) { 11197 NamedDecl *D = F.next(); 11198 if (!DC->InEnclosingNamespaceSetOf( 11199 D->getDeclContext()->getRedeclContext())) 11200 F.erase(); 11201 } 11202 F.done(); 11203 11204 if (Previous.empty()) { 11205 D.setInvalidType(); 11206 Diag(Loc, diag::err_qualified_friend_not_found) 11207 << Name << TInfo->getType(); 11208 return 0; 11209 } 11210 11211 // C++ [class.friend]p1: A friend of a class is a function or 11212 // class that is not a member of the class . . . 11213 if (DC->Equals(CurContext)) 11214 Diag(DS.getFriendSpecLoc(), 11215 getLangOpts().CPlusPlus11 ? 11216 diag::warn_cxx98_compat_friend_is_member : 11217 diag::err_friend_is_member); 11218 11219 if (D.isFunctionDefinition()) { 11220 // C++ [class.friend]p6: 11221 // A function can be defined in a friend declaration of a class if and 11222 // only if the class is a non-local class (9.8), the function name is 11223 // unqualified, and the function has namespace scope. 11224 SemaDiagnosticBuilder DB 11225 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11226 11227 DB << SS.getScopeRep(); 11228 if (DC->isFileContext()) 11229 DB << FixItHint::CreateRemoval(SS.getRange()); 11230 SS.clear(); 11231 } 11232 11233 // - There's a scope specifier that does not match any template 11234 // parameter lists, in which case we use some arbitrary context, 11235 // create a method or method template, and wait for instantiation. 11236 // - There's a scope specifier that does match some template 11237 // parameter lists, which we don't handle right now. 11238 } else { 11239 if (D.isFunctionDefinition()) { 11240 // C++ [class.friend]p6: 11241 // A function can be defined in a friend declaration of a class if and 11242 // only if the class is a non-local class (9.8), the function name is 11243 // unqualified, and the function has namespace scope. 11244 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11245 << SS.getScopeRep(); 11246 } 11247 11248 DC = CurContext; 11249 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11250 } 11251 11252 if (!DC->isRecord()) { 11253 // This implies that it has to be an operator or function. 11254 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11255 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11256 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11257 Diag(Loc, diag::err_introducing_special_friend) << 11258 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11259 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11260 return 0; 11261 } 11262 } 11263 11264 // FIXME: This is an egregious hack to cope with cases where the scope stack 11265 // does not contain the declaration context, i.e., in an out-of-line 11266 // definition of a class. 11267 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11268 if (!DCScope) { 11269 FakeDCScope.setEntity(DC); 11270 DCScope = &FakeDCScope; 11271 } 11272 11273 bool AddToScope = true; 11274 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11275 TemplateParams, AddToScope); 11276 if (!ND) return 0; 11277 11278 assert(ND->getDeclContext() == DC); 11279 assert(ND->getLexicalDeclContext() == CurContext); 11280 11281 // Add the function declaration to the appropriate lookup tables, 11282 // adjusting the redeclarations list as necessary. We don't 11283 // want to do this yet if the friending class is dependent. 11284 // 11285 // Also update the scope-based lookup if the target context's 11286 // lookup context is in lexical scope. 11287 if (!CurContext->isDependentContext()) { 11288 DC = DC->getRedeclContext(); 11289 DC->makeDeclVisibleInContext(ND); 11290 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11291 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11292 } 11293 11294 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11295 D.getIdentifierLoc(), ND, 11296 DS.getFriendSpecLoc()); 11297 FrD->setAccess(AS_public); 11298 CurContext->addDecl(FrD); 11299 11300 if (ND->isInvalidDecl()) { 11301 FrD->setInvalidDecl(); 11302 } else { 11303 if (DC->isRecord()) CheckFriendAccess(ND); 11304 11305 FunctionDecl *FD; 11306 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11307 FD = FTD->getTemplatedDecl(); 11308 else 11309 FD = cast<FunctionDecl>(ND); 11310 11311 // Mark templated-scope function declarations as unsupported. 11312 if (FD->getNumTemplateParameterLists()) 11313 FrD->setUnsupportedFriend(true); 11314 } 11315 11316 return ND; 11317} 11318 11319void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11320 AdjustDeclIfTemplate(Dcl); 11321 11322 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11323 if (!Fn) { 11324 Diag(DelLoc, diag::err_deleted_non_function); 11325 return; 11326 } 11327 11328 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11329 // Don't consider the implicit declaration we generate for explicit 11330 // specializations. FIXME: Do not generate these implicit declarations. 11331 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11332 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11333 Diag(DelLoc, diag::err_deleted_decl_not_first); 11334 Diag(Prev->getLocation(), diag::note_previous_declaration); 11335 } 11336 // If the declaration wasn't the first, we delete the function anyway for 11337 // recovery. 11338 Fn = Fn->getCanonicalDecl(); 11339 } 11340 11341 if (Fn->isDeleted()) 11342 return; 11343 11344 // See if we're deleting a function which is already known to override a 11345 // non-deleted virtual function. 11346 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11347 bool IssuedDiagnostic = false; 11348 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11349 E = MD->end_overridden_methods(); 11350 I != E; ++I) { 11351 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11352 if (!IssuedDiagnostic) { 11353 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11354 IssuedDiagnostic = true; 11355 } 11356 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11357 } 11358 } 11359 } 11360 11361 Fn->setDeletedAsWritten(); 11362} 11363 11364void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11365 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11366 11367 if (MD) { 11368 if (MD->getParent()->isDependentType()) { 11369 MD->setDefaulted(); 11370 MD->setExplicitlyDefaulted(); 11371 return; 11372 } 11373 11374 CXXSpecialMember Member = getSpecialMember(MD); 11375 if (Member == CXXInvalid) { 11376 Diag(DefaultLoc, diag::err_default_special_members); 11377 return; 11378 } 11379 11380 MD->setDefaulted(); 11381 MD->setExplicitlyDefaulted(); 11382 11383 // If this definition appears within the record, do the checking when 11384 // the record is complete. 11385 const FunctionDecl *Primary = MD; 11386 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11387 // Find the uninstantiated declaration that actually had the '= default' 11388 // on it. 11389 Pattern->isDefined(Primary); 11390 11391 // If the method was defaulted on its first declaration, we will have 11392 // already performed the checking in CheckCompletedCXXClass. Such a 11393 // declaration doesn't trigger an implicit definition. 11394 if (Primary == Primary->getCanonicalDecl()) 11395 return; 11396 11397 CheckExplicitlyDefaultedSpecialMember(MD); 11398 11399 // The exception specification is needed because we are defining the 11400 // function. 11401 ResolveExceptionSpec(DefaultLoc, 11402 MD->getType()->castAs<FunctionProtoType>()); 11403 11404 switch (Member) { 11405 case CXXDefaultConstructor: { 11406 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11407 if (!CD->isInvalidDecl()) 11408 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11409 break; 11410 } 11411 11412 case CXXCopyConstructor: { 11413 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11414 if (!CD->isInvalidDecl()) 11415 DefineImplicitCopyConstructor(DefaultLoc, CD); 11416 break; 11417 } 11418 11419 case CXXCopyAssignment: { 11420 if (!MD->isInvalidDecl()) 11421 DefineImplicitCopyAssignment(DefaultLoc, MD); 11422 break; 11423 } 11424 11425 case CXXDestructor: { 11426 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11427 if (!DD->isInvalidDecl()) 11428 DefineImplicitDestructor(DefaultLoc, DD); 11429 break; 11430 } 11431 11432 case CXXMoveConstructor: { 11433 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11434 if (!CD->isInvalidDecl()) 11435 DefineImplicitMoveConstructor(DefaultLoc, CD); 11436 break; 11437 } 11438 11439 case CXXMoveAssignment: { 11440 if (!MD->isInvalidDecl()) 11441 DefineImplicitMoveAssignment(DefaultLoc, MD); 11442 break; 11443 } 11444 11445 case CXXInvalid: 11446 llvm_unreachable("Invalid special member."); 11447 } 11448 } else { 11449 Diag(DefaultLoc, diag::err_default_special_members); 11450 } 11451} 11452 11453static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11454 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11455 Stmt *SubStmt = *CI; 11456 if (!SubStmt) 11457 continue; 11458 if (isa<ReturnStmt>(SubStmt)) 11459 Self.Diag(SubStmt->getLocStart(), 11460 diag::err_return_in_constructor_handler); 11461 if (!isa<Expr>(SubStmt)) 11462 SearchForReturnInStmt(Self, SubStmt); 11463 } 11464} 11465 11466void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11467 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11468 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11469 SearchForReturnInStmt(*this, Handler); 11470 } 11471} 11472 11473bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11474 const CXXMethodDecl *Old) { 11475 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11476 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11477 11478 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11479 11480 // If the calling conventions match, everything is fine 11481 if (NewCC == OldCC) 11482 return false; 11483 11484 // If either of the calling conventions are set to "default", we need to pick 11485 // something more sensible based on the target. This supports code where the 11486 // one method explicitly sets thiscall, and another has no explicit calling 11487 // convention. 11488 CallingConv Default = 11489 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11490 if (NewCC == CC_Default) 11491 NewCC = Default; 11492 if (OldCC == CC_Default) 11493 OldCC = Default; 11494 11495 // If the calling conventions still don't match, then report the error 11496 if (NewCC != OldCC) { 11497 Diag(New->getLocation(), 11498 diag::err_conflicting_overriding_cc_attributes) 11499 << New->getDeclName() << New->getType() << Old->getType(); 11500 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11501 return true; 11502 } 11503 11504 return false; 11505} 11506 11507bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11508 const CXXMethodDecl *Old) { 11509 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11510 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11511 11512 if (Context.hasSameType(NewTy, OldTy) || 11513 NewTy->isDependentType() || OldTy->isDependentType()) 11514 return false; 11515 11516 // Check if the return types are covariant 11517 QualType NewClassTy, OldClassTy; 11518 11519 /// Both types must be pointers or references to classes. 11520 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11521 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11522 NewClassTy = NewPT->getPointeeType(); 11523 OldClassTy = OldPT->getPointeeType(); 11524 } 11525 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11526 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11527 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11528 NewClassTy = NewRT->getPointeeType(); 11529 OldClassTy = OldRT->getPointeeType(); 11530 } 11531 } 11532 } 11533 11534 // The return types aren't either both pointers or references to a class type. 11535 if (NewClassTy.isNull()) { 11536 Diag(New->getLocation(), 11537 diag::err_different_return_type_for_overriding_virtual_function) 11538 << New->getDeclName() << NewTy << OldTy; 11539 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11540 11541 return true; 11542 } 11543 11544 // C++ [class.virtual]p6: 11545 // If the return type of D::f differs from the return type of B::f, the 11546 // class type in the return type of D::f shall be complete at the point of 11547 // declaration of D::f or shall be the class type D. 11548 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11549 if (!RT->isBeingDefined() && 11550 RequireCompleteType(New->getLocation(), NewClassTy, 11551 diag::err_covariant_return_incomplete, 11552 New->getDeclName())) 11553 return true; 11554 } 11555 11556 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11557 // Check if the new class derives from the old class. 11558 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11559 Diag(New->getLocation(), 11560 diag::err_covariant_return_not_derived) 11561 << New->getDeclName() << NewTy << OldTy; 11562 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11563 return true; 11564 } 11565 11566 // Check if we the conversion from derived to base is valid. 11567 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11568 diag::err_covariant_return_inaccessible_base, 11569 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11570 // FIXME: Should this point to the return type? 11571 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11572 // FIXME: this note won't trigger for delayed access control 11573 // diagnostics, and it's impossible to get an undelayed error 11574 // here from access control during the original parse because 11575 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11576 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11577 return true; 11578 } 11579 } 11580 11581 // The qualifiers of the return types must be the same. 11582 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11583 Diag(New->getLocation(), 11584 diag::err_covariant_return_type_different_qualifications) 11585 << New->getDeclName() << NewTy << OldTy; 11586 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11587 return true; 11588 }; 11589 11590 11591 // The new class type must have the same or less qualifiers as the old type. 11592 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11593 Diag(New->getLocation(), 11594 diag::err_covariant_return_type_class_type_more_qualified) 11595 << New->getDeclName() << NewTy << OldTy; 11596 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11597 return true; 11598 }; 11599 11600 return false; 11601} 11602 11603/// \brief Mark the given method pure. 11604/// 11605/// \param Method the method to be marked pure. 11606/// 11607/// \param InitRange the source range that covers the "0" initializer. 11608bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11609 SourceLocation EndLoc = InitRange.getEnd(); 11610 if (EndLoc.isValid()) 11611 Method->setRangeEnd(EndLoc); 11612 11613 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11614 Method->setPure(); 11615 return false; 11616 } 11617 11618 if (!Method->isInvalidDecl()) 11619 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11620 << Method->getDeclName() << InitRange; 11621 return true; 11622} 11623 11624/// \brief Determine whether the given declaration is a static data member. 11625static bool isStaticDataMember(Decl *D) { 11626 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11627 if (!Var) 11628 return false; 11629 11630 return Var->isStaticDataMember(); 11631} 11632/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11633/// an initializer for the out-of-line declaration 'Dcl'. The scope 11634/// is a fresh scope pushed for just this purpose. 11635/// 11636/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11637/// static data member of class X, names should be looked up in the scope of 11638/// class X. 11639void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11640 // If there is no declaration, there was an error parsing it. 11641 if (D == 0 || D->isInvalidDecl()) return; 11642 11643 // We should only get called for declarations with scope specifiers, like: 11644 // int foo::bar; 11645 assert(D->isOutOfLine()); 11646 EnterDeclaratorContext(S, D->getDeclContext()); 11647 11648 // If we are parsing the initializer for a static data member, push a 11649 // new expression evaluation context that is associated with this static 11650 // data member. 11651 if (isStaticDataMember(D)) 11652 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11653} 11654 11655/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11656/// initializer for the out-of-line declaration 'D'. 11657void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11658 // If there is no declaration, there was an error parsing it. 11659 if (D == 0 || D->isInvalidDecl()) return; 11660 11661 if (isStaticDataMember(D)) 11662 PopExpressionEvaluationContext(); 11663 11664 assert(D->isOutOfLine()); 11665 ExitDeclaratorContext(S); 11666} 11667 11668/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11669/// C++ if/switch/while/for statement. 11670/// e.g: "if (int x = f()) {...}" 11671DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11672 // C++ 6.4p2: 11673 // The declarator shall not specify a function or an array. 11674 // The type-specifier-seq shall not contain typedef and shall not declare a 11675 // new class or enumeration. 11676 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11677 "Parser allowed 'typedef' as storage class of condition decl."); 11678 11679 Decl *Dcl = ActOnDeclarator(S, D); 11680 if (!Dcl) 11681 return true; 11682 11683 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11684 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11685 << D.getSourceRange(); 11686 return true; 11687 } 11688 11689 return Dcl; 11690} 11691 11692void Sema::LoadExternalVTableUses() { 11693 if (!ExternalSource) 11694 return; 11695 11696 SmallVector<ExternalVTableUse, 4> VTables; 11697 ExternalSource->ReadUsedVTables(VTables); 11698 SmallVector<VTableUse, 4> NewUses; 11699 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11700 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11701 = VTablesUsed.find(VTables[I].Record); 11702 // Even if a definition wasn't required before, it may be required now. 11703 if (Pos != VTablesUsed.end()) { 11704 if (!Pos->second && VTables[I].DefinitionRequired) 11705 Pos->second = true; 11706 continue; 11707 } 11708 11709 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11710 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11711 } 11712 11713 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11714} 11715 11716void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11717 bool DefinitionRequired) { 11718 // Ignore any vtable uses in unevaluated operands or for classes that do 11719 // not have a vtable. 11720 if (!Class->isDynamicClass() || Class->isDependentContext() || 11721 CurContext->isDependentContext() || 11722 ExprEvalContexts.back().Context == Unevaluated) 11723 return; 11724 11725 // Try to insert this class into the map. 11726 LoadExternalVTableUses(); 11727 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11728 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11729 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11730 if (!Pos.second) { 11731 // If we already had an entry, check to see if we are promoting this vtable 11732 // to required a definition. If so, we need to reappend to the VTableUses 11733 // list, since we may have already processed the first entry. 11734 if (DefinitionRequired && !Pos.first->second) { 11735 Pos.first->second = true; 11736 } else { 11737 // Otherwise, we can early exit. 11738 return; 11739 } 11740 } 11741 11742 // Local classes need to have their virtual members marked 11743 // immediately. For all other classes, we mark their virtual members 11744 // at the end of the translation unit. 11745 if (Class->isLocalClass()) 11746 MarkVirtualMembersReferenced(Loc, Class); 11747 else 11748 VTableUses.push_back(std::make_pair(Class, Loc)); 11749} 11750 11751bool Sema::DefineUsedVTables() { 11752 LoadExternalVTableUses(); 11753 if (VTableUses.empty()) 11754 return false; 11755 11756 // Note: The VTableUses vector could grow as a result of marking 11757 // the members of a class as "used", so we check the size each 11758 // time through the loop and prefer indices (which are stable) to 11759 // iterators (which are not). 11760 bool DefinedAnything = false; 11761 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11762 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11763 if (!Class) 11764 continue; 11765 11766 SourceLocation Loc = VTableUses[I].second; 11767 11768 bool DefineVTable = true; 11769 11770 // If this class has a key function, but that key function is 11771 // defined in another translation unit, we don't need to emit the 11772 // vtable even though we're using it. 11773 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11774 if (KeyFunction && !KeyFunction->hasBody()) { 11775 switch (KeyFunction->getTemplateSpecializationKind()) { 11776 case TSK_Undeclared: 11777 case TSK_ExplicitSpecialization: 11778 case TSK_ExplicitInstantiationDeclaration: 11779 // The key function is in another translation unit. 11780 DefineVTable = false; 11781 break; 11782 11783 case TSK_ExplicitInstantiationDefinition: 11784 case TSK_ImplicitInstantiation: 11785 // We will be instantiating the key function. 11786 break; 11787 } 11788 } else if (!KeyFunction) { 11789 // If we have a class with no key function that is the subject 11790 // of an explicit instantiation declaration, suppress the 11791 // vtable; it will live with the explicit instantiation 11792 // definition. 11793 bool IsExplicitInstantiationDeclaration 11794 = Class->getTemplateSpecializationKind() 11795 == TSK_ExplicitInstantiationDeclaration; 11796 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11797 REnd = Class->redecls_end(); 11798 R != REnd; ++R) { 11799 TemplateSpecializationKind TSK 11800 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11801 if (TSK == TSK_ExplicitInstantiationDeclaration) 11802 IsExplicitInstantiationDeclaration = true; 11803 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11804 IsExplicitInstantiationDeclaration = false; 11805 break; 11806 } 11807 } 11808 11809 if (IsExplicitInstantiationDeclaration) 11810 DefineVTable = false; 11811 } 11812 11813 // The exception specifications for all virtual members may be needed even 11814 // if we are not providing an authoritative form of the vtable in this TU. 11815 // We may choose to emit it available_externally anyway. 11816 if (!DefineVTable) { 11817 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11818 continue; 11819 } 11820 11821 // Mark all of the virtual members of this class as referenced, so 11822 // that we can build a vtable. Then, tell the AST consumer that a 11823 // vtable for this class is required. 11824 DefinedAnything = true; 11825 MarkVirtualMembersReferenced(Loc, Class); 11826 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11827 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11828 11829 // Optionally warn if we're emitting a weak vtable. 11830 if (Class->hasExternalLinkage() && 11831 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11832 const FunctionDecl *KeyFunctionDef = 0; 11833 if (!KeyFunction || 11834 (KeyFunction->hasBody(KeyFunctionDef) && 11835 KeyFunctionDef->isInlined())) 11836 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11837 TSK_ExplicitInstantiationDefinition 11838 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11839 << Class; 11840 } 11841 } 11842 VTableUses.clear(); 11843 11844 return DefinedAnything; 11845} 11846 11847void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11848 const CXXRecordDecl *RD) { 11849 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11850 E = RD->method_end(); I != E; ++I) 11851 if ((*I)->isVirtual() && !(*I)->isPure()) 11852 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11853} 11854 11855void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11856 const CXXRecordDecl *RD) { 11857 // Mark all functions which will appear in RD's vtable as used. 11858 CXXFinalOverriderMap FinalOverriders; 11859 RD->getFinalOverriders(FinalOverriders); 11860 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11861 E = FinalOverriders.end(); 11862 I != E; ++I) { 11863 for (OverridingMethods::const_iterator OI = I->second.begin(), 11864 OE = I->second.end(); 11865 OI != OE; ++OI) { 11866 assert(OI->second.size() > 0 && "no final overrider"); 11867 CXXMethodDecl *Overrider = OI->second.front().Method; 11868 11869 // C++ [basic.def.odr]p2: 11870 // [...] A virtual member function is used if it is not pure. [...] 11871 if (!Overrider->isPure()) 11872 MarkFunctionReferenced(Loc, Overrider); 11873 } 11874 } 11875 11876 // Only classes that have virtual bases need a VTT. 11877 if (RD->getNumVBases() == 0) 11878 return; 11879 11880 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11881 e = RD->bases_end(); i != e; ++i) { 11882 const CXXRecordDecl *Base = 11883 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11884 if (Base->getNumVBases() == 0) 11885 continue; 11886 MarkVirtualMembersReferenced(Loc, Base); 11887 } 11888} 11889 11890/// SetIvarInitializers - This routine builds initialization ASTs for the 11891/// Objective-C implementation whose ivars need be initialized. 11892void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11893 if (!getLangOpts().CPlusPlus) 11894 return; 11895 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11896 SmallVector<ObjCIvarDecl*, 8> ivars; 11897 CollectIvarsToConstructOrDestruct(OID, ivars); 11898 if (ivars.empty()) 11899 return; 11900 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11901 for (unsigned i = 0; i < ivars.size(); i++) { 11902 FieldDecl *Field = ivars[i]; 11903 if (Field->isInvalidDecl()) 11904 continue; 11905 11906 CXXCtorInitializer *Member; 11907 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11908 InitializationKind InitKind = 11909 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11910 11911 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 11912 ExprResult MemberInit = 11913 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 11914 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11915 // Note, MemberInit could actually come back empty if no initialization 11916 // is required (e.g., because it would call a trivial default constructor) 11917 if (!MemberInit.get() || MemberInit.isInvalid()) 11918 continue; 11919 11920 Member = 11921 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11922 SourceLocation(), 11923 MemberInit.takeAs<Expr>(), 11924 SourceLocation()); 11925 AllToInit.push_back(Member); 11926 11927 // Be sure that the destructor is accessible and is marked as referenced. 11928 if (const RecordType *RecordTy 11929 = Context.getBaseElementType(Field->getType()) 11930 ->getAs<RecordType>()) { 11931 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11932 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11933 MarkFunctionReferenced(Field->getLocation(), Destructor); 11934 CheckDestructorAccess(Field->getLocation(), Destructor, 11935 PDiag(diag::err_access_dtor_ivar) 11936 << Context.getBaseElementType(Field->getType())); 11937 } 11938 } 11939 } 11940 ObjCImplementation->setIvarInitializers(Context, 11941 AllToInit.data(), AllToInit.size()); 11942 } 11943} 11944 11945static 11946void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11947 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11948 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11949 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11950 Sema &S) { 11951 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11952 CE = Current.end(); 11953 if (Ctor->isInvalidDecl()) 11954 return; 11955 11956 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11957 11958 // Target may not be determinable yet, for instance if this is a dependent 11959 // call in an uninstantiated template. 11960 if (Target) { 11961 const FunctionDecl *FNTarget = 0; 11962 (void)Target->hasBody(FNTarget); 11963 Target = const_cast<CXXConstructorDecl*>( 11964 cast_or_null<CXXConstructorDecl>(FNTarget)); 11965 } 11966 11967 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11968 // Avoid dereferencing a null pointer here. 11969 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11970 11971 if (!Current.insert(Canonical)) 11972 return; 11973 11974 // We know that beyond here, we aren't chaining into a cycle. 11975 if (!Target || !Target->isDelegatingConstructor() || 11976 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11977 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11978 Valid.insert(*CI); 11979 Current.clear(); 11980 // We've hit a cycle. 11981 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11982 Current.count(TCanonical)) { 11983 // If we haven't diagnosed this cycle yet, do so now. 11984 if (!Invalid.count(TCanonical)) { 11985 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11986 diag::warn_delegating_ctor_cycle) 11987 << Ctor; 11988 11989 // Don't add a note for a function delegating directly to itself. 11990 if (TCanonical != Canonical) 11991 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11992 11993 CXXConstructorDecl *C = Target; 11994 while (C->getCanonicalDecl() != Canonical) { 11995 const FunctionDecl *FNTarget = 0; 11996 (void)C->getTargetConstructor()->hasBody(FNTarget); 11997 assert(FNTarget && "Ctor cycle through bodiless function"); 11998 11999 C = const_cast<CXXConstructorDecl*>( 12000 cast<CXXConstructorDecl>(FNTarget)); 12001 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12002 } 12003 } 12004 12005 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12006 Invalid.insert(*CI); 12007 Current.clear(); 12008 } else { 12009 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12010 } 12011} 12012 12013 12014void Sema::CheckDelegatingCtorCycles() { 12015 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12016 12017 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12018 CE = Current.end(); 12019 12020 for (DelegatingCtorDeclsType::iterator 12021 I = DelegatingCtorDecls.begin(ExternalSource), 12022 E = DelegatingCtorDecls.end(); 12023 I != E; ++I) 12024 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12025 12026 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 12027 (*CI)->setInvalidDecl(); 12028} 12029 12030namespace { 12031 /// \brief AST visitor that finds references to the 'this' expression. 12032 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12033 Sema &S; 12034 12035 public: 12036 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12037 12038 bool VisitCXXThisExpr(CXXThisExpr *E) { 12039 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12040 << E->isImplicit(); 12041 return false; 12042 } 12043 }; 12044} 12045 12046bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12047 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12048 if (!TSInfo) 12049 return false; 12050 12051 TypeLoc TL = TSInfo->getTypeLoc(); 12052 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12053 if (!ProtoTL) 12054 return false; 12055 12056 // C++11 [expr.prim.general]p3: 12057 // [The expression this] shall not appear before the optional 12058 // cv-qualifier-seq and it shall not appear within the declaration of a 12059 // static member function (although its type and value category are defined 12060 // within a static member function as they are within a non-static member 12061 // function). [ Note: this is because declaration matching does not occur 12062 // until the complete declarator is known. - end note ] 12063 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12064 FindCXXThisExpr Finder(*this); 12065 12066 // If the return type came after the cv-qualifier-seq, check it now. 12067 if (Proto->hasTrailingReturn() && 12068 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12069 return true; 12070 12071 // Check the exception specification. 12072 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12073 return true; 12074 12075 return checkThisInStaticMemberFunctionAttributes(Method); 12076} 12077 12078bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12079 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12080 if (!TSInfo) 12081 return false; 12082 12083 TypeLoc TL = TSInfo->getTypeLoc(); 12084 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12085 if (!ProtoTL) 12086 return false; 12087 12088 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12089 FindCXXThisExpr Finder(*this); 12090 12091 switch (Proto->getExceptionSpecType()) { 12092 case EST_Uninstantiated: 12093 case EST_Unevaluated: 12094 case EST_BasicNoexcept: 12095 case EST_DynamicNone: 12096 case EST_MSAny: 12097 case EST_None: 12098 break; 12099 12100 case EST_ComputedNoexcept: 12101 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12102 return true; 12103 12104 case EST_Dynamic: 12105 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12106 EEnd = Proto->exception_end(); 12107 E != EEnd; ++E) { 12108 if (!Finder.TraverseType(*E)) 12109 return true; 12110 } 12111 break; 12112 } 12113 12114 return false; 12115} 12116 12117bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12118 FindCXXThisExpr Finder(*this); 12119 12120 // Check attributes. 12121 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12122 A != AEnd; ++A) { 12123 // FIXME: This should be emitted by tblgen. 12124 Expr *Arg = 0; 12125 ArrayRef<Expr *> Args; 12126 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12127 Arg = G->getArg(); 12128 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12129 Arg = G->getArg(); 12130 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12131 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12132 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12133 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12134 else if (ExclusiveLockFunctionAttr *ELF 12135 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12136 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12137 else if (SharedLockFunctionAttr *SLF 12138 = dyn_cast<SharedLockFunctionAttr>(*A)) 12139 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12140 else if (ExclusiveTrylockFunctionAttr *ETLF 12141 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12142 Arg = ETLF->getSuccessValue(); 12143 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12144 } else if (SharedTrylockFunctionAttr *STLF 12145 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12146 Arg = STLF->getSuccessValue(); 12147 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12148 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12149 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12150 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12151 Arg = LR->getArg(); 12152 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12153 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12154 else if (ExclusiveLocksRequiredAttr *ELR 12155 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12156 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12157 else if (SharedLocksRequiredAttr *SLR 12158 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12159 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12160 12161 if (Arg && !Finder.TraverseStmt(Arg)) 12162 return true; 12163 12164 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12165 if (!Finder.TraverseStmt(Args[I])) 12166 return true; 12167 } 12168 } 12169 12170 return false; 12171} 12172 12173void 12174Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12175 ArrayRef<ParsedType> DynamicExceptions, 12176 ArrayRef<SourceRange> DynamicExceptionRanges, 12177 Expr *NoexceptExpr, 12178 SmallVectorImpl<QualType> &Exceptions, 12179 FunctionProtoType::ExtProtoInfo &EPI) { 12180 Exceptions.clear(); 12181 EPI.ExceptionSpecType = EST; 12182 if (EST == EST_Dynamic) { 12183 Exceptions.reserve(DynamicExceptions.size()); 12184 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12185 // FIXME: Preserve type source info. 12186 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12187 12188 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12189 collectUnexpandedParameterPacks(ET, Unexpanded); 12190 if (!Unexpanded.empty()) { 12191 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12192 UPPC_ExceptionType, 12193 Unexpanded); 12194 continue; 12195 } 12196 12197 // Check that the type is valid for an exception spec, and 12198 // drop it if not. 12199 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12200 Exceptions.push_back(ET); 12201 } 12202 EPI.NumExceptions = Exceptions.size(); 12203 EPI.Exceptions = Exceptions.data(); 12204 return; 12205 } 12206 12207 if (EST == EST_ComputedNoexcept) { 12208 // If an error occurred, there's no expression here. 12209 if (NoexceptExpr) { 12210 assert((NoexceptExpr->isTypeDependent() || 12211 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12212 Context.BoolTy) && 12213 "Parser should have made sure that the expression is boolean"); 12214 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12215 EPI.ExceptionSpecType = EST_BasicNoexcept; 12216 return; 12217 } 12218 12219 if (!NoexceptExpr->isValueDependent()) 12220 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12221 diag::err_noexcept_needs_constant_expression, 12222 /*AllowFold*/ false).take(); 12223 EPI.NoexceptExpr = NoexceptExpr; 12224 } 12225 return; 12226 } 12227} 12228 12229/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12230Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12231 // Implicitly declared functions (e.g. copy constructors) are 12232 // __host__ __device__ 12233 if (D->isImplicit()) 12234 return CFT_HostDevice; 12235 12236 if (D->hasAttr<CUDAGlobalAttr>()) 12237 return CFT_Global; 12238 12239 if (D->hasAttr<CUDADeviceAttr>()) { 12240 if (D->hasAttr<CUDAHostAttr>()) 12241 return CFT_HostDevice; 12242 else 12243 return CFT_Device; 12244 } 12245 12246 return CFT_Host; 12247} 12248 12249bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12250 CUDAFunctionTarget CalleeTarget) { 12251 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12252 // Callable from the device only." 12253 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12254 return true; 12255 12256 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12257 // Callable from the host only." 12258 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12259 // Callable from the host only." 12260 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12261 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12262 return true; 12263 12264 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12265 return true; 12266 12267 return false; 12268} 12269 12270/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12271/// 12272MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12273 SourceLocation DeclStart, 12274 Declarator &D, Expr *BitWidth, 12275 InClassInitStyle InitStyle, 12276 AccessSpecifier AS, 12277 AttributeList *MSPropertyAttr) { 12278 IdentifierInfo *II = D.getIdentifier(); 12279 if (!II) { 12280 Diag(DeclStart, diag::err_anonymous_property); 12281 return NULL; 12282 } 12283 SourceLocation Loc = D.getIdentifierLoc(); 12284 12285 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12286 QualType T = TInfo->getType(); 12287 if (getLangOpts().CPlusPlus) { 12288 CheckExtraCXXDefaultArguments(D); 12289 12290 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12291 UPPC_DataMemberType)) { 12292 D.setInvalidType(); 12293 T = Context.IntTy; 12294 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12295 } 12296 } 12297 12298 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12299 12300 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12301 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12302 diag::err_invalid_thread) 12303 << DeclSpec::getSpecifierName(TSCS); 12304 12305 // Check to see if this name was declared as a member previously 12306 NamedDecl *PrevDecl = 0; 12307 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12308 LookupName(Previous, S); 12309 switch (Previous.getResultKind()) { 12310 case LookupResult::Found: 12311 case LookupResult::FoundUnresolvedValue: 12312 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12313 break; 12314 12315 case LookupResult::FoundOverloaded: 12316 PrevDecl = Previous.getRepresentativeDecl(); 12317 break; 12318 12319 case LookupResult::NotFound: 12320 case LookupResult::NotFoundInCurrentInstantiation: 12321 case LookupResult::Ambiguous: 12322 break; 12323 } 12324 12325 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12326 // Maybe we will complain about the shadowed template parameter. 12327 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12328 // Just pretend that we didn't see the previous declaration. 12329 PrevDecl = 0; 12330 } 12331 12332 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12333 PrevDecl = 0; 12334 12335 SourceLocation TSSL = D.getLocStart(); 12336 MSPropertyDecl *NewPD; 12337 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12338 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12339 II, T, TInfo, TSSL, 12340 Data.GetterId, Data.SetterId); 12341 ProcessDeclAttributes(TUScope, NewPD, D); 12342 NewPD->setAccess(AS); 12343 12344 if (NewPD->isInvalidDecl()) 12345 Record->setInvalidDecl(); 12346 12347 if (D.getDeclSpec().isModulePrivateSpecified()) 12348 NewPD->setModulePrivate(); 12349 12350 if (NewPD->isInvalidDecl() && PrevDecl) { 12351 // Don't introduce NewFD into scope; there's already something 12352 // with the same name in the same scope. 12353 } else if (II) { 12354 PushOnScopeChains(NewPD, S); 12355 } else 12356 Record->addDecl(NewPD); 12357 12358 return NewPD; 12359} 12360