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