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/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.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/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallString.h" 41 #include <map> 42 #include <set> 43 44 using namespace clang; 45 46 //===----------------------------------------------------------------------===// 47 // CheckDefaultArgumentVisitor 48 //===----------------------------------------------------------------------===// 49 50 namespace { 51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 52 /// the default argument of a parameter to determine whether it 53 /// contains any ill-formed subexpressions. For example, this will 54 /// diagnose the use of local variables or parameters within the 55 /// default argument expression. 56 class CheckDefaultArgumentVisitor 57 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 58 Expr *DefaultArg; 59 Sema *S; 60 61 public: 62 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 63 : DefaultArg(defarg), S(s) {} 64 65 bool VisitExpr(Expr *Node); 66 bool VisitDeclRefExpr(DeclRefExpr *DRE); 67 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 68 bool VisitLambdaExpr(LambdaExpr *Lambda); 69 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 70 }; 71 72 /// VisitExpr - Visit all of the children of this expression. 73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 74 bool IsInvalid = false; 75 for (Stmt::child_range I = Node->children(); I; ++I) 76 IsInvalid |= Visit(*I); 77 return IsInvalid; 78 } 79 80 /// VisitDeclRefExpr - Visit a reference to a declaration, to 81 /// determine whether this declaration can be used in the default 82 /// argument expression. 83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 84 NamedDecl *Decl = DRE->getDecl(); 85 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p9 87 // Default arguments are evaluated each time the function is 88 // called. The order of evaluation of function arguments is 89 // unspecified. Consequently, parameters of a function shall not 90 // be used in default argument expressions, even if they are not 91 // evaluated. Parameters of a function declared before a default 92 // argument expression are in scope and can hide namespace and 93 // class member names. 94 return S->Diag(DRE->getLocStart(), 95 diag::err_param_default_argument_references_param) 96 << Param->getDeclName() << DefaultArg->getSourceRange(); 97 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 98 // C++ [dcl.fct.default]p7 99 // Local variables shall not be used in default argument 100 // expressions. 101 if (VDecl->isLocalVarDecl()) 102 return S->Diag(DRE->getLocStart(), 103 diag::err_param_default_argument_references_local) 104 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 105 } 106 107 return false; 108 } 109 110 /// VisitCXXThisExpr - Visit a C++ "this" expression. 111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 112 // C++ [dcl.fct.default]p8: 113 // The keyword this shall not be used in a default argument of a 114 // member function. 115 return S->Diag(ThisE->getLocStart(), 116 diag::err_param_default_argument_references_this) 117 << ThisE->getSourceRange(); 118 } 119 120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 121 bool Invalid = false; 122 for (PseudoObjectExpr::semantics_iterator 123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 124 Expr *E = *i; 125 126 // Look through bindings. 127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 128 E = OVE->getSourceExpr(); 129 assert(E && "pseudo-object binding without source expression?"); 130 } 131 132 Invalid |= Visit(E); 133 } 134 return Invalid; 135 } 136 137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 138 // C++11 [expr.lambda.prim]p13: 139 // A lambda-expression appearing in a default argument shall not 140 // implicitly or explicitly capture any entity. 141 if (Lambda->capture_begin() == Lambda->capture_end()) 142 return false; 143 144 return S->Diag(Lambda->getLocStart(), 145 diag::err_lambda_capture_default_arg); 146 } 147 } 148 149 void 150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 151 const CXXMethodDecl *Method) { 152 // If we have an MSAny spec already, don't bother. 153 if (!Method || ComputedEST == EST_MSAny) 154 return; 155 156 const FunctionProtoType *Proto 157 = Method->getType()->getAs<FunctionProtoType>(); 158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 159 if (!Proto) 160 return; 161 162 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 163 164 // If this function can throw any exceptions, make a note of that. 165 if (EST == EST_MSAny || EST == EST_None) { 166 ClearExceptions(); 167 ComputedEST = EST; 168 return; 169 } 170 171 // FIXME: If the call to this decl is using any of its default arguments, we 172 // need to search them for potentially-throwing calls. 173 174 // If this function has a basic noexcept, it doesn't affect the outcome. 175 if (EST == EST_BasicNoexcept) 176 return; 177 178 // If we have a throw-all spec at this point, ignore the function. 179 if (ComputedEST == EST_None) 180 return; 181 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 if (EST == EST_DynamicNone) { 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 } 189 190 // Check out noexcept specs. 191 if (EST == EST_ComputedNoexcept) { 192 FunctionProtoType::NoexceptResult NR = 193 Proto->getNoexceptSpec(Self->Context); 194 assert(NR != FunctionProtoType::NR_NoNoexcept && 195 "Must have noexcept result for EST_ComputedNoexcept."); 196 assert(NR != FunctionProtoType::NR_Dependent && 197 "Should not generate implicit declarations for dependent cases, " 198 "and don't know how to handle them anyway."); 199 200 // noexcept(false) -> no spec on the new function 201 if (NR == FunctionProtoType::NR_Throw) { 202 ClearExceptions(); 203 ComputedEST = EST_None; 204 } 205 // noexcept(true) won't change anything either. 206 return; 207 } 208 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E))) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // Check that the default argument is well-formed 321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 322 if (DefaultArgChecker.Visit(DefaultArg)) { 323 Param->setInvalidDecl(); 324 return; 325 } 326 327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 328 } 329 330 /// ActOnParamUnparsedDefaultArgument - We've seen a default 331 /// argument for a function parameter, but we can't parse it yet 332 /// because we're inside a class definition. Note that this default 333 /// argument will be parsed later. 334 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 335 SourceLocation EqualLoc, 336 SourceLocation ArgLoc) { 337 if (!param) 338 return; 339 340 ParmVarDecl *Param = cast<ParmVarDecl>(param); 341 Param->setUnparsedDefaultArg(); 342 UnparsedDefaultArgLocs[Param] = ArgLoc; 343 } 344 345 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 346 /// the default argument for the parameter param failed. 347 void Sema::ActOnParamDefaultArgumentError(Decl *param, 348 SourceLocation EqualLoc) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setInvalidDecl(); 354 UnparsedDefaultArgLocs.erase(Param); 355 Param->setDefaultArg(new(Context) 356 OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue)); 357 } 358 359 /// CheckExtraCXXDefaultArguments - Check for any extra default 360 /// arguments in the declarator, which is not a function declaration 361 /// or definition and therefore is not permitted to have default 362 /// arguments. This routine should be invoked for every declarator 363 /// that is not a function declaration or definition. 364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 384 ++argIdx) { 385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(nullptr); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403 } 404 405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414 } 415 416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417 /// function, once we already know that they have the same 418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419 /// error, false otherwise. 420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 NamedDecl *ND = Old; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->getLexicalDeclContext(); 455 if (!ScopeDC->isFunctionOrMethod()) 456 ScopeDC = New->getDeclContext(); 457 if (S && !isDeclInScope(ND, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 464 if (OldParamHasDfl && NewParamHasDfl) { 465 466 unsigned DiagDefaultParamID = 467 diag::err_param_default_argument_redefinition; 468 469 // MSVC accepts that default parameters be redefined for member functions 470 // of template class. The new default parameter's value is ignored. 471 Invalid = true; 472 if (getLangOpts().MicrosoftExt) { 473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 474 if (MD && MD->getParent()->getDescribedClassTemplate()) { 475 // Merge the old default argument into the new parameter. 476 NewParam->setHasInheritedDefaultArg(); 477 if (OldParam->hasUninstantiatedDefaultArg()) 478 NewParam->setUninstantiatedDefaultArg( 479 OldParam->getUninstantiatedDefaultArg()); 480 else 481 NewParam->setDefaultArg(OldParam->getInit()); 482 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 483 Invalid = false; 484 } 485 } 486 487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 488 // hint here. Alternatively, we could walk the type-source information 489 // for NewParam to find the last source location in the type... but it 490 // isn't worth the effort right now. This is the kind of test case that 491 // is hard to get right: 492 // int f(int); 493 // void g(int (*fp)(int) = f); 494 // void g(int (*fp)(int) = &f); 495 Diag(NewParam->getLocation(), DiagDefaultParamID) 496 << NewParam->getDefaultArgRange(); 497 498 // Look for the function declaration where the default argument was 499 // actually written, which may be a declaration prior to Old. 500 for (FunctionDecl *Older = Old->getPreviousDecl(); 501 Older; Older = Older->getPreviousDecl()) { 502 if (!Older->getParamDecl(p)->hasDefaultArg()) 503 break; 504 505 OldParam = Older->getParamDecl(p); 506 } 507 508 Diag(OldParam->getLocation(), diag::note_previous_definition) 509 << OldParam->getDefaultArgRange(); 510 } else if (OldParamHasDfl) { 511 // Merge the old default argument into the new parameter. 512 // It's important to use getInit() here; getDefaultArg() 513 // strips off any top-level ExprWithCleanups. 514 NewParam->setHasInheritedDefaultArg(); 515 if (OldParam->hasUninstantiatedDefaultArg()) 516 NewParam->setUninstantiatedDefaultArg( 517 OldParam->getUninstantiatedDefaultArg()); 518 else 519 NewParam->setDefaultArg(OldParam->getInit()); 520 } else if (NewParamHasDfl) { 521 if (New->getDescribedFunctionTemplate()) { 522 // Paragraph 4, quoted above, only applies to non-template functions. 523 Diag(NewParam->getLocation(), 524 diag::err_param_default_argument_template_redecl) 525 << NewParam->getDefaultArgRange(); 526 Diag(Old->getLocation(), diag::note_template_prev_declaration) 527 << false; 528 } else if (New->getTemplateSpecializationKind() 529 != TSK_ImplicitInstantiation && 530 New->getTemplateSpecializationKind() != TSK_Undeclared) { 531 // C++ [temp.expr.spec]p21: 532 // Default function arguments shall not be specified in a declaration 533 // or a definition for one of the following explicit specializations: 534 // - the explicit specialization of a function template; 535 // - the explicit specialization of a member function template; 536 // - the explicit specialization of a member function of a class 537 // template where the class template specialization to which the 538 // member function specialization belongs is implicitly 539 // instantiated. 540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 542 << New->getDeclName() 543 << NewParam->getDefaultArgRange(); 544 } else if (New->getDeclContext()->isDependentContext()) { 545 // C++ [dcl.fct.default]p6 (DR217): 546 // Default arguments for a member function of a class template shall 547 // be specified on the initial declaration of the member function 548 // within the class template. 549 // 550 // Reading the tea leaves a bit in DR217 and its reference to DR205 551 // leads me to the conclusion that one cannot add default function 552 // arguments for an out-of-line definition of a member function of a 553 // dependent type. 554 int WhichKind = 2; 555 if (CXXRecordDecl *Record 556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 557 if (Record->getDescribedClassTemplate()) 558 WhichKind = 0; 559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 560 WhichKind = 1; 561 else 562 WhichKind = 2; 563 } 564 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_member_template_redecl) 567 << WhichKind 568 << NewParam->getDefaultArgRange(); 569 } 570 } 571 } 572 573 // DR1344: If a default argument is added outside a class definition and that 574 // default argument makes the function a special member function, the program 575 // is ill-formed. This can only happen for constructors. 576 if (isa<CXXConstructorDecl>(New) && 577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 580 if (NewSM != OldSM) { 581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 582 assert(NewParam->hasDefaultArg()); 583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 584 << NewParam->getDefaultArgRange() << NewSM; 585 Diag(Old->getLocation(), diag::note_previous_declaration); 586 } 587 } 588 589 const FunctionDecl *Def; 590 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 591 // template has a constexpr specifier then all its declarations shall 592 // contain the constexpr specifier. 593 if (New->isConstexpr() != Old->isConstexpr()) { 594 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 595 << New << New->isConstexpr(); 596 Diag(Old->getLocation(), diag::note_previous_declaration); 597 Invalid = true; 598 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 599 // C++11 [dcl.fcn.spec]p4: 600 // If the definition of a function appears in a translation unit before its 601 // first declaration as inline, the program is ill-formed. 602 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 603 Diag(Def->getLocation(), diag::note_previous_definition); 604 Invalid = true; 605 } 606 607 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 608 // argument expression, that declaration shall be a definition and shall be 609 // the only declaration of the function or function template in the 610 // translation unit. 611 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 612 functionDeclHasDefaultArgument(Old)) { 613 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 614 Diag(Old->getLocation(), diag::note_previous_declaration); 615 Invalid = true; 616 } 617 618 if (CheckEquivalentExceptionSpec(Old, New)) 619 Invalid = true; 620 621 return Invalid; 622 } 623 624 /// \brief Merge the exception specifications of two variable declarations. 625 /// 626 /// This is called when there's a redeclaration of a VarDecl. The function 627 /// checks if the redeclaration might have an exception specification and 628 /// validates compatibility and merges the specs if necessary. 629 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 630 // Shortcut if exceptions are disabled. 631 if (!getLangOpts().CXXExceptions) 632 return; 633 634 assert(Context.hasSameType(New->getType(), Old->getType()) && 635 "Should only be called if types are otherwise the same."); 636 637 QualType NewType = New->getType(); 638 QualType OldType = Old->getType(); 639 640 // We're only interested in pointers and references to functions, as well 641 // as pointers to member functions. 642 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 643 NewType = R->getPointeeType(); 644 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 645 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 646 NewType = P->getPointeeType(); 647 OldType = OldType->getAs<PointerType>()->getPointeeType(); 648 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 649 NewType = M->getPointeeType(); 650 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 651 } 652 653 if (!NewType->isFunctionProtoType()) 654 return; 655 656 // There's lots of special cases for functions. For function pointers, system 657 // libraries are hopefully not as broken so that we don't need these 658 // workarounds. 659 if (CheckEquivalentExceptionSpec( 660 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 661 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 662 New->setInvalidDecl(); 663 } 664 } 665 666 /// CheckCXXDefaultArguments - Verify that the default arguments for a 667 /// function declaration are well-formed according to C++ 668 /// [dcl.fct.default]. 669 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 670 unsigned NumParams = FD->getNumParams(); 671 unsigned p; 672 673 // Find first parameter with a default argument 674 for (p = 0; p < NumParams; ++p) { 675 ParmVarDecl *Param = FD->getParamDecl(p); 676 if (Param->hasDefaultArg()) 677 break; 678 } 679 680 // C++ [dcl.fct.default]p4: 681 // In a given function declaration, all parameters 682 // subsequent to a parameter with a default argument shall 683 // have default arguments supplied in this or previous 684 // declarations. A default argument shall not be redefined 685 // by a later declaration (not even to the same value). 686 unsigned LastMissingDefaultArg = 0; 687 for (; p < NumParams; ++p) { 688 ParmVarDecl *Param = FD->getParamDecl(p); 689 if (!Param->hasDefaultArg()) { 690 if (Param->isInvalidDecl()) 691 /* We already complained about this parameter. */; 692 else if (Param->getIdentifier()) 693 Diag(Param->getLocation(), 694 diag::err_param_default_argument_missing_name) 695 << Param->getIdentifier(); 696 else 697 Diag(Param->getLocation(), 698 diag::err_param_default_argument_missing); 699 700 LastMissingDefaultArg = p; 701 } 702 } 703 704 if (LastMissingDefaultArg > 0) { 705 // Some default arguments were missing. Clear out all of the 706 // default arguments up to (and including) the last missing 707 // default argument, so that we leave the function parameters 708 // in a semantically valid state. 709 for (p = 0; p <= LastMissingDefaultArg; ++p) { 710 ParmVarDecl *Param = FD->getParamDecl(p); 711 if (Param->hasDefaultArg()) { 712 Param->setDefaultArg(nullptr); 713 } 714 } 715 } 716 } 717 718 // CheckConstexprParameterTypes - Check whether a function's parameter types 719 // are all literal types. If so, return true. If not, produce a suitable 720 // diagnostic and return false. 721 static bool CheckConstexprParameterTypes(Sema &SemaRef, 722 const FunctionDecl *FD) { 723 unsigned ArgIndex = 0; 724 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 725 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 726 e = FT->param_type_end(); 727 i != e; ++i, ++ArgIndex) { 728 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 729 SourceLocation ParamLoc = PD->getLocation(); 730 if (!(*i)->isDependentType() && 731 SemaRef.RequireLiteralType(ParamLoc, *i, 732 diag::err_constexpr_non_literal_param, 733 ArgIndex+1, PD->getSourceRange(), 734 isa<CXXConstructorDecl>(FD))) 735 return false; 736 } 737 return true; 738 } 739 740 /// \brief Get diagnostic %select index for tag kind for 741 /// record diagnostic message. 742 /// WARNING: Indexes apply to particular diagnostics only! 743 /// 744 /// \returns diagnostic %select index. 745 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 746 switch (Tag) { 747 case TTK_Struct: return 0; 748 case TTK_Interface: return 1; 749 case TTK_Class: return 2; 750 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 751 } 752 } 753 754 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 755 // the requirements of a constexpr function definition or a constexpr 756 // constructor definition. If so, return true. If not, produce appropriate 757 // diagnostics and return false. 758 // 759 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 760 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 762 if (MD && MD->isInstance()) { 763 // C++11 [dcl.constexpr]p4: 764 // The definition of a constexpr constructor shall satisfy the following 765 // constraints: 766 // - the class shall not have any virtual base classes; 767 const CXXRecordDecl *RD = MD->getParent(); 768 if (RD->getNumVBases()) { 769 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 770 << isa<CXXConstructorDecl>(NewFD) 771 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 772 for (const auto &I : RD->vbases()) 773 Diag(I.getLocStart(), 774 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 775 return false; 776 } 777 } 778 779 if (!isa<CXXConstructorDecl>(NewFD)) { 780 // C++11 [dcl.constexpr]p3: 781 // The definition of a constexpr function shall satisfy the following 782 // constraints: 783 // - it shall not be virtual; 784 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 785 if (Method && Method->isVirtual()) { 786 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 787 788 // If it's not obvious why this function is virtual, find an overridden 789 // function which uses the 'virtual' keyword. 790 const CXXMethodDecl *WrittenVirtual = Method; 791 while (!WrittenVirtual->isVirtualAsWritten()) 792 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 793 if (WrittenVirtual != Method) 794 Diag(WrittenVirtual->getLocation(), 795 diag::note_overridden_virtual_function); 796 return false; 797 } 798 799 // - its return type shall be a literal type; 800 QualType RT = NewFD->getReturnType(); 801 if (!RT->isDependentType() && 802 RequireLiteralType(NewFD->getLocation(), RT, 803 diag::err_constexpr_non_literal_return)) 804 return false; 805 } 806 807 // - each of its parameter types shall be a literal type; 808 if (!CheckConstexprParameterTypes(*this, NewFD)) 809 return false; 810 811 return true; 812 } 813 814 /// Check the given declaration statement is legal within a constexpr function 815 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 816 /// 817 /// \return true if the body is OK (maybe only as an extension), false if we 818 /// have diagnosed a problem. 819 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 820 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 821 // C++11 [dcl.constexpr]p3 and p4: 822 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 823 // contain only 824 for (const auto *DclIt : DS->decls()) { 825 switch (DclIt->getKind()) { 826 case Decl::StaticAssert: 827 case Decl::Using: 828 case Decl::UsingShadow: 829 case Decl::UsingDirective: 830 case Decl::UnresolvedUsingTypename: 831 case Decl::UnresolvedUsingValue: 832 // - static_assert-declarations 833 // - using-declarations, 834 // - using-directives, 835 continue; 836 837 case Decl::Typedef: 838 case Decl::TypeAlias: { 839 // - typedef declarations and alias-declarations that do not define 840 // classes or enumerations, 841 const auto *TN = cast<TypedefNameDecl>(DclIt); 842 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 843 // Don't allow variably-modified types in constexpr functions. 844 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 845 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 846 << TL.getSourceRange() << TL.getType() 847 << isa<CXXConstructorDecl>(Dcl); 848 return false; 849 } 850 continue; 851 } 852 853 case Decl::Enum: 854 case Decl::CXXRecord: 855 // C++1y allows types to be defined, not just declared. 856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 857 SemaRef.Diag(DS->getLocStart(), 858 SemaRef.getLangOpts().CPlusPlus1y 859 ? diag::warn_cxx11_compat_constexpr_type_definition 860 : diag::ext_constexpr_type_definition) 861 << isa<CXXConstructorDecl>(Dcl); 862 continue; 863 864 case Decl::EnumConstant: 865 case Decl::IndirectField: 866 case Decl::ParmVar: 867 // These can only appear with other declarations which are banned in 868 // C++11 and permitted in C++1y, so ignore them. 869 continue; 870 871 case Decl::Var: { 872 // C++1y [dcl.constexpr]p3 allows anything except: 873 // a definition of a variable of non-literal type or of static or 874 // thread storage duration or for which no initialization is performed. 875 const auto *VD = cast<VarDecl>(DclIt); 876 if (VD->isThisDeclarationADefinition()) { 877 if (VD->isStaticLocal()) { 878 SemaRef.Diag(VD->getLocation(), 879 diag::err_constexpr_local_var_static) 880 << isa<CXXConstructorDecl>(Dcl) 881 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 882 return false; 883 } 884 if (!VD->getType()->isDependentType() && 885 SemaRef.RequireLiteralType( 886 VD->getLocation(), VD->getType(), 887 diag::err_constexpr_local_var_non_literal_type, 888 isa<CXXConstructorDecl>(Dcl))) 889 return false; 890 if (!VD->getType()->isDependentType() && 891 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 892 SemaRef.Diag(VD->getLocation(), 893 diag::err_constexpr_local_var_no_init) 894 << isa<CXXConstructorDecl>(Dcl); 895 return false; 896 } 897 } 898 SemaRef.Diag(VD->getLocation(), 899 SemaRef.getLangOpts().CPlusPlus1y 900 ? diag::warn_cxx11_compat_constexpr_local_var 901 : diag::ext_constexpr_local_var) 902 << isa<CXXConstructorDecl>(Dcl); 903 continue; 904 } 905 906 case Decl::NamespaceAlias: 907 case Decl::Function: 908 // These are disallowed in C++11 and permitted in C++1y. Allow them 909 // everywhere as an extension. 910 if (!Cxx1yLoc.isValid()) 911 Cxx1yLoc = DS->getLocStart(); 912 continue; 913 914 default: 915 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 916 << isa<CXXConstructorDecl>(Dcl); 917 return false; 918 } 919 } 920 921 return true; 922 } 923 924 /// Check that the given field is initialized within a constexpr constructor. 925 /// 926 /// \param Dcl The constexpr constructor being checked. 927 /// \param Field The field being checked. This may be a member of an anonymous 928 /// struct or union nested within the class being checked. 929 /// \param Inits All declarations, including anonymous struct/union members and 930 /// indirect members, for which any initialization was provided. 931 /// \param Diagnosed Set to true if an error is produced. 932 static void CheckConstexprCtorInitializer(Sema &SemaRef, 933 const FunctionDecl *Dcl, 934 FieldDecl *Field, 935 llvm::SmallSet<Decl*, 16> &Inits, 936 bool &Diagnosed) { 937 if (Field->isInvalidDecl()) 938 return; 939 940 if (Field->isUnnamedBitfield()) 941 return; 942 943 // Anonymous unions with no variant members and empty anonymous structs do not 944 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 945 // indirect fields don't need initializing. 946 if (Field->isAnonymousStructOrUnion() && 947 (Field->getType()->isUnionType() 948 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 949 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 950 return; 951 952 if (!Inits.count(Field)) { 953 if (!Diagnosed) { 954 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 955 Diagnosed = true; 956 } 957 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 958 } else if (Field->isAnonymousStructOrUnion()) { 959 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 960 for (auto *I : RD->fields()) 961 // If an anonymous union contains an anonymous struct of which any member 962 // is initialized, all members must be initialized. 963 if (!RD->isUnion() || Inits.count(I)) 964 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 965 } 966 } 967 968 /// Check the provided statement is allowed in a constexpr function 969 /// definition. 970 static bool 971 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 972 SmallVectorImpl<SourceLocation> &ReturnStmts, 973 SourceLocation &Cxx1yLoc) { 974 // - its function-body shall be [...] a compound-statement that contains only 975 switch (S->getStmtClass()) { 976 case Stmt::NullStmtClass: 977 // - null statements, 978 return true; 979 980 case Stmt::DeclStmtClass: 981 // - static_assert-declarations 982 // - using-declarations, 983 // - using-directives, 984 // - typedef declarations and alias-declarations that do not define 985 // classes or enumerations, 986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 987 return false; 988 return true; 989 990 case Stmt::ReturnStmtClass: 991 // - and exactly one return statement; 992 if (isa<CXXConstructorDecl>(Dcl)) { 993 // C++1y allows return statements in constexpr constructors. 994 if (!Cxx1yLoc.isValid()) 995 Cxx1yLoc = S->getLocStart(); 996 return true; 997 } 998 999 ReturnStmts.push_back(S->getLocStart()); 1000 return true; 1001 1002 case Stmt::CompoundStmtClass: { 1003 // C++1y allows compound-statements. 1004 if (!Cxx1yLoc.isValid()) 1005 Cxx1yLoc = S->getLocStart(); 1006 1007 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1008 for (auto *BodyIt : CompStmt->body()) { 1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1010 Cxx1yLoc)) 1011 return false; 1012 } 1013 return true; 1014 } 1015 1016 case Stmt::AttributedStmtClass: 1017 if (!Cxx1yLoc.isValid()) 1018 Cxx1yLoc = S->getLocStart(); 1019 return true; 1020 1021 case Stmt::IfStmtClass: { 1022 // C++1y allows if-statements. 1023 if (!Cxx1yLoc.isValid()) 1024 Cxx1yLoc = S->getLocStart(); 1025 1026 IfStmt *If = cast<IfStmt>(S); 1027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1028 Cxx1yLoc)) 1029 return false; 1030 if (If->getElse() && 1031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1032 Cxx1yLoc)) 1033 return false; 1034 return true; 1035 } 1036 1037 case Stmt::WhileStmtClass: 1038 case Stmt::DoStmtClass: 1039 case Stmt::ForStmtClass: 1040 case Stmt::CXXForRangeStmtClass: 1041 case Stmt::ContinueStmtClass: 1042 // C++1y allows all of these. We don't allow them as extensions in C++11, 1043 // because they don't make sense without variable mutation. 1044 if (!SemaRef.getLangOpts().CPlusPlus1y) 1045 break; 1046 if (!Cxx1yLoc.isValid()) 1047 Cxx1yLoc = S->getLocStart(); 1048 for (Stmt::child_range Children = S->children(); Children; ++Children) 1049 if (*Children && 1050 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1051 Cxx1yLoc)) 1052 return false; 1053 return true; 1054 1055 case Stmt::SwitchStmtClass: 1056 case Stmt::CaseStmtClass: 1057 case Stmt::DefaultStmtClass: 1058 case Stmt::BreakStmtClass: 1059 // C++1y allows switch-statements, and since they don't need variable 1060 // mutation, we can reasonably allow them in C++11 as an extension. 1061 if (!Cxx1yLoc.isValid()) 1062 Cxx1yLoc = S->getLocStart(); 1063 for (Stmt::child_range Children = S->children(); Children; ++Children) 1064 if (*Children && 1065 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1066 Cxx1yLoc)) 1067 return false; 1068 return true; 1069 1070 default: 1071 if (!isa<Expr>(S)) 1072 break; 1073 1074 // C++1y allows expression-statements. 1075 if (!Cxx1yLoc.isValid()) 1076 Cxx1yLoc = S->getLocStart(); 1077 return true; 1078 } 1079 1080 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1081 << isa<CXXConstructorDecl>(Dcl); 1082 return false; 1083 } 1084 1085 /// Check the body for the given constexpr function declaration only contains 1086 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1087 /// 1088 /// \return true if the body is OK, false if we have diagnosed a problem. 1089 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1090 if (isa<CXXTryStmt>(Body)) { 1091 // C++11 [dcl.constexpr]p3: 1092 // The definition of a constexpr function shall satisfy the following 1093 // constraints: [...] 1094 // - its function-body shall be = delete, = default, or a 1095 // compound-statement 1096 // 1097 // C++11 [dcl.constexpr]p4: 1098 // In the definition of a constexpr constructor, [...] 1099 // - its function-body shall not be a function-try-block; 1100 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1101 << isa<CXXConstructorDecl>(Dcl); 1102 return false; 1103 } 1104 1105 SmallVector<SourceLocation, 4> ReturnStmts; 1106 1107 // - its function-body shall be [...] a compound-statement that contains only 1108 // [... list of cases ...] 1109 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1110 SourceLocation Cxx1yLoc; 1111 for (auto *BodyIt : CompBody->body()) { 1112 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1113 return false; 1114 } 1115 1116 if (Cxx1yLoc.isValid()) 1117 Diag(Cxx1yLoc, 1118 getLangOpts().CPlusPlus1y 1119 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1120 : diag::ext_constexpr_body_invalid_stmt) 1121 << isa<CXXConstructorDecl>(Dcl); 1122 1123 if (const CXXConstructorDecl *Constructor 1124 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1125 const CXXRecordDecl *RD = Constructor->getParent(); 1126 // DR1359: 1127 // - every non-variant non-static data member and base class sub-object 1128 // shall be initialized; 1129 // DR1460: 1130 // - if the class is a union having variant members, exactly one of them 1131 // shall be initialized; 1132 if (RD->isUnion()) { 1133 if (Constructor->getNumCtorInitializers() == 0 && 1134 RD->hasVariantMembers()) { 1135 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1136 return false; 1137 } 1138 } else if (!Constructor->isDependentContext() && 1139 !Constructor->isDelegatingConstructor()) { 1140 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1141 1142 // Skip detailed checking if we have enough initializers, and we would 1143 // allow at most one initializer per member. 1144 bool AnyAnonStructUnionMembers = false; 1145 unsigned Fields = 0; 1146 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1147 E = RD->field_end(); I != E; ++I, ++Fields) { 1148 if (I->isAnonymousStructOrUnion()) { 1149 AnyAnonStructUnionMembers = true; 1150 break; 1151 } 1152 } 1153 // DR1460: 1154 // - if the class is a union-like class, but is not a union, for each of 1155 // its anonymous union members having variant members, exactly one of 1156 // them shall be initialized; 1157 if (AnyAnonStructUnionMembers || 1158 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1159 // Check initialization of non-static data members. Base classes are 1160 // always initialized so do not need to be checked. Dependent bases 1161 // might not have initializers in the member initializer list. 1162 llvm::SmallSet<Decl*, 16> Inits; 1163 for (const auto *I: Constructor->inits()) { 1164 if (FieldDecl *FD = I->getMember()) 1165 Inits.insert(FD); 1166 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1167 Inits.insert(ID->chain_begin(), ID->chain_end()); 1168 } 1169 1170 bool Diagnosed = false; 1171 for (auto *I : RD->fields()) 1172 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1173 if (Diagnosed) 1174 return false; 1175 } 1176 } 1177 } else { 1178 if (ReturnStmts.empty()) { 1179 // C++1y doesn't require constexpr functions to contain a 'return' 1180 // statement. We still do, unless the return type might be void, because 1181 // otherwise if there's no return statement, the function cannot 1182 // be used in a core constant expression. 1183 bool OK = getLangOpts().CPlusPlus1y && 1184 (Dcl->getReturnType()->isVoidType() || 1185 Dcl->getReturnType()->isDependentType()); 1186 Diag(Dcl->getLocation(), 1187 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1188 : diag::err_constexpr_body_no_return); 1189 return OK; 1190 } 1191 if (ReturnStmts.size() > 1) { 1192 Diag(ReturnStmts.back(), 1193 getLangOpts().CPlusPlus1y 1194 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1195 : diag::ext_constexpr_body_multiple_return); 1196 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1197 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1198 } 1199 } 1200 1201 // C++11 [dcl.constexpr]p5: 1202 // if no function argument values exist such that the function invocation 1203 // substitution would produce a constant expression, the program is 1204 // ill-formed; no diagnostic required. 1205 // C++11 [dcl.constexpr]p3: 1206 // - every constructor call and implicit conversion used in initializing the 1207 // return value shall be one of those allowed in a constant expression. 1208 // C++11 [dcl.constexpr]p4: 1209 // - every constructor involved in initializing non-static data members and 1210 // base class sub-objects shall be a constexpr constructor. 1211 SmallVector<PartialDiagnosticAt, 8> Diags; 1212 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1213 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1214 << isa<CXXConstructorDecl>(Dcl); 1215 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1216 Diag(Diags[I].first, Diags[I].second); 1217 // Don't return false here: we allow this for compatibility in 1218 // system headers. 1219 } 1220 1221 return true; 1222 } 1223 1224 /// isCurrentClassName - Determine whether the identifier II is the 1225 /// name of the class type currently being defined. In the case of 1226 /// nested classes, this will only return true if II is the name of 1227 /// the innermost class. 1228 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1229 const CXXScopeSpec *SS) { 1230 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1231 1232 CXXRecordDecl *CurDecl; 1233 if (SS && SS->isSet() && !SS->isInvalid()) { 1234 DeclContext *DC = computeDeclContext(*SS, true); 1235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1236 } else 1237 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1238 1239 if (CurDecl && CurDecl->getIdentifier()) 1240 return &II == CurDecl->getIdentifier(); 1241 return false; 1242 } 1243 1244 /// \brief Determine whether the identifier II is a typo for the name of 1245 /// the class type currently being defined. If so, update it to the identifier 1246 /// that should have been used. 1247 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1248 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1249 1250 if (!getLangOpts().SpellChecking) 1251 return false; 1252 1253 CXXRecordDecl *CurDecl; 1254 if (SS && SS->isSet() && !SS->isInvalid()) { 1255 DeclContext *DC = computeDeclContext(*SS, true); 1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1257 } else 1258 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1259 1260 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1261 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1262 < II->getLength()) { 1263 II = CurDecl->getIdentifier(); 1264 return true; 1265 } 1266 1267 return false; 1268 } 1269 1270 /// \brief Determine whether the given class is a base class of the given 1271 /// class, including looking at dependent bases. 1272 static bool findCircularInheritance(const CXXRecordDecl *Class, 1273 const CXXRecordDecl *Current) { 1274 SmallVector<const CXXRecordDecl*, 8> Queue; 1275 1276 Class = Class->getCanonicalDecl(); 1277 while (true) { 1278 for (const auto &I : Current->bases()) { 1279 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1280 if (!Base) 1281 continue; 1282 1283 Base = Base->getDefinition(); 1284 if (!Base) 1285 continue; 1286 1287 if (Base->getCanonicalDecl() == Class) 1288 return true; 1289 1290 Queue.push_back(Base); 1291 } 1292 1293 if (Queue.empty()) 1294 return false; 1295 1296 Current = Queue.pop_back_val(); 1297 } 1298 1299 return false; 1300 } 1301 1302 /// \brief Perform propagation of DLL attributes from a derived class to a 1303 /// templated base class for MS compatibility. 1304 static void propagateDLLAttrToBaseClassTemplate( 1305 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1306 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1307 if (getDLLAttr( 1308 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1309 // If the base class template has a DLL attribute, don't try to change it. 1310 return; 1311 } 1312 1313 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1314 // If the base class is not already specialized, we can do the propagation. 1315 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1316 NewAttr->setInherited(true); 1317 BaseTemplateSpec->addAttr(NewAttr); 1318 return; 1319 } 1320 1321 bool DifferentAttribute = false; 1322 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1323 if (!SpecializationAttr->isInherited()) { 1324 // The template has previously been specialized or instantiated with an 1325 // explicit attribute. We should not try to change it. 1326 return; 1327 } 1328 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1329 // The specialization already has the right attribute. 1330 return; 1331 } 1332 DifferentAttribute = true; 1333 } 1334 1335 // The template was previously instantiated or explicitly specialized without 1336 // a dll attribute, or the template was previously instantiated with a 1337 // different inherited attribute. It's too late for us to change the 1338 // attribute, so warn that this is unsupported. 1339 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1340 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1341 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1342 if (BaseTemplateSpec->isExplicitSpecialization()) { 1343 S.Diag(BaseTemplateSpec->getLocation(), 1344 diag::note_template_class_explicit_specialization_was_here) 1345 << BaseTemplateSpec; 1346 } else { 1347 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1348 diag::note_template_class_instantiation_was_here) 1349 << BaseTemplateSpec; 1350 } 1351 } 1352 1353 /// \brief Check the validity of a C++ base class specifier. 1354 /// 1355 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1356 /// and returns NULL otherwise. 1357 CXXBaseSpecifier * 1358 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1359 SourceRange SpecifierRange, 1360 bool Virtual, AccessSpecifier Access, 1361 TypeSourceInfo *TInfo, 1362 SourceLocation EllipsisLoc) { 1363 QualType BaseType = TInfo->getType(); 1364 1365 // C++ [class.union]p1: 1366 // A union shall not have base classes. 1367 if (Class->isUnion()) { 1368 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1369 << SpecifierRange; 1370 return nullptr; 1371 } 1372 1373 if (EllipsisLoc.isValid() && 1374 !TInfo->getType()->containsUnexpandedParameterPack()) { 1375 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1376 << TInfo->getTypeLoc().getSourceRange(); 1377 EllipsisLoc = SourceLocation(); 1378 } 1379 1380 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1381 1382 if (BaseType->isDependentType()) { 1383 // Make sure that we don't have circular inheritance among our dependent 1384 // bases. For non-dependent bases, the check for completeness below handles 1385 // this. 1386 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1387 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1388 ((BaseDecl = BaseDecl->getDefinition()) && 1389 findCircularInheritance(Class, BaseDecl))) { 1390 Diag(BaseLoc, diag::err_circular_inheritance) 1391 << BaseType << Context.getTypeDeclType(Class); 1392 1393 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1394 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1395 << BaseType; 1396 1397 return nullptr; 1398 } 1399 } 1400 1401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1402 Class->getTagKind() == TTK_Class, 1403 Access, TInfo, EllipsisLoc); 1404 } 1405 1406 // Base specifiers must be record types. 1407 if (!BaseType->isRecordType()) { 1408 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1409 return nullptr; 1410 } 1411 1412 // C++ [class.union]p1: 1413 // A union shall not be used as a base class. 1414 if (BaseType->isUnionType()) { 1415 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1416 return nullptr; 1417 } 1418 1419 // For the MS ABI, propagate DLL attributes to base class templates. 1420 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1421 if (Attr *ClassAttr = getDLLAttr(Class)) { 1422 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1423 BaseType->getAsCXXRecordDecl())) { 1424 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1425 BaseTemplate, BaseLoc); 1426 } 1427 } 1428 } 1429 1430 // C++ [class.derived]p2: 1431 // The class-name in a base-specifier shall not be an incompletely 1432 // defined class. 1433 if (RequireCompleteType(BaseLoc, BaseType, 1434 diag::err_incomplete_base_class, SpecifierRange)) { 1435 Class->setInvalidDecl(); 1436 return nullptr; 1437 } 1438 1439 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1440 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1441 assert(BaseDecl && "Record type has no declaration"); 1442 BaseDecl = BaseDecl->getDefinition(); 1443 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1444 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1445 assert(CXXBaseDecl && "Base type is not a C++ type"); 1446 1447 // A class which contains a flexible array member is not suitable for use as a 1448 // base class: 1449 // - If the layout determines that a base comes before another base, 1450 // the flexible array member would index into the subsequent base. 1451 // - If the layout determines that base comes before the derived class, 1452 // the flexible array member would index into the derived class. 1453 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1454 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1455 << CXXBaseDecl->getDeclName(); 1456 return nullptr; 1457 } 1458 1459 // C++ [class]p3: 1460 // If a class is marked final and it appears as a base-type-specifier in 1461 // base-clause, the program is ill-formed. 1462 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1463 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1464 << CXXBaseDecl->getDeclName() 1465 << FA->isSpelledAsSealed(); 1466 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1467 << CXXBaseDecl->getDeclName() << FA->getRange(); 1468 return nullptr; 1469 } 1470 1471 if (BaseDecl->isInvalidDecl()) 1472 Class->setInvalidDecl(); 1473 1474 // Create the base specifier. 1475 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1476 Class->getTagKind() == TTK_Class, 1477 Access, TInfo, EllipsisLoc); 1478 } 1479 1480 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1481 /// one entry in the base class list of a class specifier, for 1482 /// example: 1483 /// class foo : public bar, virtual private baz { 1484 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1485 BaseResult 1486 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1487 ParsedAttributes &Attributes, 1488 bool Virtual, AccessSpecifier Access, 1489 ParsedType basetype, SourceLocation BaseLoc, 1490 SourceLocation EllipsisLoc) { 1491 if (!classdecl) 1492 return true; 1493 1494 AdjustDeclIfTemplate(classdecl); 1495 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1496 if (!Class) 1497 return true; 1498 1499 // We haven't yet attached the base specifiers. 1500 Class->setIsParsingBaseSpecifiers(); 1501 1502 // We do not support any C++11 attributes on base-specifiers yet. 1503 // Diagnose any attributes we see. 1504 if (!Attributes.empty()) { 1505 for (AttributeList *Attr = Attributes.getList(); Attr; 1506 Attr = Attr->getNext()) { 1507 if (Attr->isInvalid() || 1508 Attr->getKind() == AttributeList::IgnoredAttribute) 1509 continue; 1510 Diag(Attr->getLoc(), 1511 Attr->getKind() == AttributeList::UnknownAttribute 1512 ? diag::warn_unknown_attribute_ignored 1513 : diag::err_base_specifier_attribute) 1514 << Attr->getName(); 1515 } 1516 } 1517 1518 TypeSourceInfo *TInfo = nullptr; 1519 GetTypeFromParser(basetype, &TInfo); 1520 1521 if (EllipsisLoc.isInvalid() && 1522 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1523 UPPC_BaseType)) 1524 return true; 1525 1526 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1527 Virtual, Access, TInfo, 1528 EllipsisLoc)) 1529 return BaseSpec; 1530 else 1531 Class->setInvalidDecl(); 1532 1533 return true; 1534 } 1535 1536 /// \brief Performs the actual work of attaching the given base class 1537 /// specifiers to a C++ class. 1538 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1539 unsigned NumBases) { 1540 if (NumBases == 0) 1541 return false; 1542 1543 // Used to keep track of which base types we have already seen, so 1544 // that we can properly diagnose redundant direct base types. Note 1545 // that the key is always the unqualified canonical type of the base 1546 // class. 1547 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1548 1549 // Copy non-redundant base specifiers into permanent storage. 1550 unsigned NumGoodBases = 0; 1551 bool Invalid = false; 1552 for (unsigned idx = 0; idx < NumBases; ++idx) { 1553 QualType NewBaseType 1554 = Context.getCanonicalType(Bases[idx]->getType()); 1555 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1556 1557 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1558 if (KnownBase) { 1559 // C++ [class.mi]p3: 1560 // A class shall not be specified as a direct base class of a 1561 // derived class more than once. 1562 Diag(Bases[idx]->getLocStart(), 1563 diag::err_duplicate_base_class) 1564 << KnownBase->getType() 1565 << Bases[idx]->getSourceRange(); 1566 1567 // Delete the duplicate base class specifier; we're going to 1568 // overwrite its pointer later. 1569 Context.Deallocate(Bases[idx]); 1570 1571 Invalid = true; 1572 } else { 1573 // Okay, add this new base class. 1574 KnownBase = Bases[idx]; 1575 Bases[NumGoodBases++] = Bases[idx]; 1576 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1577 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1578 if (Class->isInterface() && 1579 (!RD->isInterface() || 1580 KnownBase->getAccessSpecifier() != AS_public)) { 1581 // The Microsoft extension __interface does not permit bases that 1582 // are not themselves public interfaces. 1583 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1584 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1585 << RD->getSourceRange(); 1586 Invalid = true; 1587 } 1588 if (RD->hasAttr<WeakAttr>()) 1589 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1590 } 1591 } 1592 } 1593 1594 // Attach the remaining base class specifiers to the derived class. 1595 Class->setBases(Bases, NumGoodBases); 1596 1597 // Delete the remaining (good) base class specifiers, since their 1598 // data has been copied into the CXXRecordDecl. 1599 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1600 Context.Deallocate(Bases[idx]); 1601 1602 return Invalid; 1603 } 1604 1605 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1606 /// class, after checking whether there are any duplicate base 1607 /// classes. 1608 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1609 unsigned NumBases) { 1610 if (!ClassDecl || !Bases || !NumBases) 1611 return; 1612 1613 AdjustDeclIfTemplate(ClassDecl); 1614 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1615 } 1616 1617 /// \brief Determine whether the type \p Derived is a C++ class that is 1618 /// derived from the type \p Base. 1619 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1620 if (!getLangOpts().CPlusPlus) 1621 return false; 1622 1623 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1624 if (!DerivedRD) 1625 return false; 1626 1627 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1628 if (!BaseRD) 1629 return false; 1630 1631 // If either the base or the derived type is invalid, don't try to 1632 // check whether one is derived from the other. 1633 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1634 return false; 1635 1636 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1637 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1638 } 1639 1640 /// \brief Determine whether the type \p Derived is a C++ class that is 1641 /// derived from the type \p Base. 1642 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1643 if (!getLangOpts().CPlusPlus) 1644 return false; 1645 1646 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1647 if (!DerivedRD) 1648 return false; 1649 1650 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1651 if (!BaseRD) 1652 return false; 1653 1654 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1655 } 1656 1657 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1658 CXXCastPath &BasePathArray) { 1659 assert(BasePathArray.empty() && "Base path array must be empty!"); 1660 assert(Paths.isRecordingPaths() && "Must record paths!"); 1661 1662 const CXXBasePath &Path = Paths.front(); 1663 1664 // We first go backward and check if we have a virtual base. 1665 // FIXME: It would be better if CXXBasePath had the base specifier for 1666 // the nearest virtual base. 1667 unsigned Start = 0; 1668 for (unsigned I = Path.size(); I != 0; --I) { 1669 if (Path[I - 1].Base->isVirtual()) { 1670 Start = I - 1; 1671 break; 1672 } 1673 } 1674 1675 // Now add all bases. 1676 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1677 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1678 } 1679 1680 /// \brief Determine whether the given base path includes a virtual 1681 /// base class. 1682 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1683 for (CXXCastPath::const_iterator B = BasePath.begin(), 1684 BEnd = BasePath.end(); 1685 B != BEnd; ++B) 1686 if ((*B)->isVirtual()) 1687 return true; 1688 1689 return false; 1690 } 1691 1692 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1693 /// conversion (where Derived and Base are class types) is 1694 /// well-formed, meaning that the conversion is unambiguous (and 1695 /// that all of the base classes are accessible). Returns true 1696 /// and emits a diagnostic if the code is ill-formed, returns false 1697 /// otherwise. Loc is the location where this routine should point to 1698 /// if there is an error, and Range is the source range to highlight 1699 /// if there is an error. 1700 bool 1701 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1702 unsigned InaccessibleBaseID, 1703 unsigned AmbigiousBaseConvID, 1704 SourceLocation Loc, SourceRange Range, 1705 DeclarationName Name, 1706 CXXCastPath *BasePath) { 1707 // First, determine whether the path from Derived to Base is 1708 // ambiguous. This is slightly more expensive than checking whether 1709 // the Derived to Base conversion exists, because here we need to 1710 // explore multiple paths to determine if there is an ambiguity. 1711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1712 /*DetectVirtual=*/false); 1713 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1714 assert(DerivationOkay && 1715 "Can only be used with a derived-to-base conversion"); 1716 (void)DerivationOkay; 1717 1718 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1719 if (InaccessibleBaseID) { 1720 // Check that the base class can be accessed. 1721 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1722 InaccessibleBaseID)) { 1723 case AR_inaccessible: 1724 return true; 1725 case AR_accessible: 1726 case AR_dependent: 1727 case AR_delayed: 1728 break; 1729 } 1730 } 1731 1732 // Build a base path if necessary. 1733 if (BasePath) 1734 BuildBasePathArray(Paths, *BasePath); 1735 return false; 1736 } 1737 1738 if (AmbigiousBaseConvID) { 1739 // We know that the derived-to-base conversion is ambiguous, and 1740 // we're going to produce a diagnostic. Perform the derived-to-base 1741 // search just one more time to compute all of the possible paths so 1742 // that we can print them out. This is more expensive than any of 1743 // the previous derived-to-base checks we've done, but at this point 1744 // performance isn't as much of an issue. 1745 Paths.clear(); 1746 Paths.setRecordingPaths(true); 1747 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1748 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1749 (void)StillOkay; 1750 1751 // Build up a textual representation of the ambiguous paths, e.g., 1752 // D -> B -> A, that will be used to illustrate the ambiguous 1753 // conversions in the diagnostic. We only print one of the paths 1754 // to each base class subobject. 1755 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1756 1757 Diag(Loc, AmbigiousBaseConvID) 1758 << Derived << Base << PathDisplayStr << Range << Name; 1759 } 1760 return true; 1761 } 1762 1763 bool 1764 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1765 SourceLocation Loc, SourceRange Range, 1766 CXXCastPath *BasePath, 1767 bool IgnoreAccess) { 1768 return CheckDerivedToBaseConversion(Derived, Base, 1769 IgnoreAccess ? 0 1770 : diag::err_upcast_to_inaccessible_base, 1771 diag::err_ambiguous_derived_to_base_conv, 1772 Loc, Range, DeclarationName(), 1773 BasePath); 1774 } 1775 1776 1777 /// @brief Builds a string representing ambiguous paths from a 1778 /// specific derived class to different subobjects of the same base 1779 /// class. 1780 /// 1781 /// This function builds a string that can be used in error messages 1782 /// to show the different paths that one can take through the 1783 /// inheritance hierarchy to go from the derived class to different 1784 /// subobjects of a base class. The result looks something like this: 1785 /// @code 1786 /// struct D -> struct B -> struct A 1787 /// struct D -> struct C -> struct A 1788 /// @endcode 1789 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1790 std::string PathDisplayStr; 1791 std::set<unsigned> DisplayedPaths; 1792 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1793 Path != Paths.end(); ++Path) { 1794 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1795 // We haven't displayed a path to this particular base 1796 // class subobject yet. 1797 PathDisplayStr += "\n "; 1798 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1799 for (CXXBasePath::const_iterator Element = Path->begin(); 1800 Element != Path->end(); ++Element) 1801 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1802 } 1803 } 1804 1805 return PathDisplayStr; 1806 } 1807 1808 //===----------------------------------------------------------------------===// 1809 // C++ class member Handling 1810 //===----------------------------------------------------------------------===// 1811 1812 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1813 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1814 SourceLocation ASLoc, 1815 SourceLocation ColonLoc, 1816 AttributeList *Attrs) { 1817 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1818 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1819 ASLoc, ColonLoc); 1820 CurContext->addHiddenDecl(ASDecl); 1821 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1822 } 1823 1824 /// CheckOverrideControl - Check C++11 override control semantics. 1825 void Sema::CheckOverrideControl(NamedDecl *D) { 1826 if (D->isInvalidDecl()) 1827 return; 1828 1829 // We only care about "override" and "final" declarations. 1830 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1831 return; 1832 1833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1834 1835 // We can't check dependent instance methods. 1836 if (MD && MD->isInstance() && 1837 (MD->getParent()->hasAnyDependentBases() || 1838 MD->getType()->isDependentType())) 1839 return; 1840 1841 if (MD && !MD->isVirtual()) { 1842 // If we have a non-virtual method, check if if hides a virtual method. 1843 // (In that case, it's most likely the method has the wrong type.) 1844 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1845 FindHiddenVirtualMethods(MD, OverloadedMethods); 1846 1847 if (!OverloadedMethods.empty()) { 1848 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1849 Diag(OA->getLocation(), 1850 diag::override_keyword_hides_virtual_member_function) 1851 << "override" << (OverloadedMethods.size() > 1); 1852 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1853 Diag(FA->getLocation(), 1854 diag::override_keyword_hides_virtual_member_function) 1855 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1856 << (OverloadedMethods.size() > 1); 1857 } 1858 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1859 MD->setInvalidDecl(); 1860 return; 1861 } 1862 // Fall through into the general case diagnostic. 1863 // FIXME: We might want to attempt typo correction here. 1864 } 1865 1866 if (!MD || !MD->isVirtual()) { 1867 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1868 Diag(OA->getLocation(), 1869 diag::override_keyword_only_allowed_on_virtual_member_functions) 1870 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1871 D->dropAttr<OverrideAttr>(); 1872 } 1873 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1874 Diag(FA->getLocation(), 1875 diag::override_keyword_only_allowed_on_virtual_member_functions) 1876 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1877 << FixItHint::CreateRemoval(FA->getLocation()); 1878 D->dropAttr<FinalAttr>(); 1879 } 1880 return; 1881 } 1882 1883 // C++11 [class.virtual]p5: 1884 // If a virtual function is marked with the virt-specifier override and 1885 // does not override a member function of a base class, the program is 1886 // ill-formed. 1887 bool HasOverriddenMethods = 1888 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1889 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1890 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1891 << MD->getDeclName(); 1892 } 1893 1894 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1895 /// function overrides a virtual member function marked 'final', according to 1896 /// C++11 [class.virtual]p4. 1897 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1898 const CXXMethodDecl *Old) { 1899 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1900 if (!FA) 1901 return false; 1902 1903 Diag(New->getLocation(), diag::err_final_function_overridden) 1904 << New->getDeclName() 1905 << FA->isSpelledAsSealed(); 1906 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1907 return true; 1908 } 1909 1910 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1911 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1912 // FIXME: Destruction of ObjC lifetime types has side-effects. 1913 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1914 return !RD->isCompleteDefinition() || 1915 !RD->hasTrivialDefaultConstructor() || 1916 !RD->hasTrivialDestructor(); 1917 return false; 1918 } 1919 1920 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1921 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1922 if (it->isDeclspecPropertyAttribute()) 1923 return it; 1924 return nullptr; 1925 } 1926 1927 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1928 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1929 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1930 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1931 /// present (but parsing it has been deferred). 1932 NamedDecl * 1933 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1934 MultiTemplateParamsArg TemplateParameterLists, 1935 Expr *BW, const VirtSpecifiers &VS, 1936 InClassInitStyle InitStyle) { 1937 const DeclSpec &DS = D.getDeclSpec(); 1938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1939 DeclarationName Name = NameInfo.getName(); 1940 SourceLocation Loc = NameInfo.getLoc(); 1941 1942 // For anonymous bitfields, the location should point to the type. 1943 if (Loc.isInvalid()) 1944 Loc = D.getLocStart(); 1945 1946 Expr *BitWidth = static_cast<Expr*>(BW); 1947 1948 assert(isa<CXXRecordDecl>(CurContext)); 1949 assert(!DS.isFriendSpecified()); 1950 1951 bool isFunc = D.isDeclarationOfFunction(); 1952 1953 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1954 // The Microsoft extension __interface only permits public member functions 1955 // and prohibits constructors, destructors, operators, non-public member 1956 // functions, static methods and data members. 1957 unsigned InvalidDecl; 1958 bool ShowDeclName = true; 1959 if (!isFunc) 1960 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1961 else if (AS != AS_public) 1962 InvalidDecl = 2; 1963 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1964 InvalidDecl = 3; 1965 else switch (Name.getNameKind()) { 1966 case DeclarationName::CXXConstructorName: 1967 InvalidDecl = 4; 1968 ShowDeclName = false; 1969 break; 1970 1971 case DeclarationName::CXXDestructorName: 1972 InvalidDecl = 5; 1973 ShowDeclName = false; 1974 break; 1975 1976 case DeclarationName::CXXOperatorName: 1977 case DeclarationName::CXXConversionFunctionName: 1978 InvalidDecl = 6; 1979 break; 1980 1981 default: 1982 InvalidDecl = 0; 1983 break; 1984 } 1985 1986 if (InvalidDecl) { 1987 if (ShowDeclName) 1988 Diag(Loc, diag::err_invalid_member_in_interface) 1989 << (InvalidDecl-1) << Name; 1990 else 1991 Diag(Loc, diag::err_invalid_member_in_interface) 1992 << (InvalidDecl-1) << ""; 1993 return nullptr; 1994 } 1995 } 1996 1997 // C++ 9.2p6: A member shall not be declared to have automatic storage 1998 // duration (auto, register) or with the extern storage-class-specifier. 1999 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2000 // data members and cannot be applied to names declared const or static, 2001 // and cannot be applied to reference members. 2002 switch (DS.getStorageClassSpec()) { 2003 case DeclSpec::SCS_unspecified: 2004 case DeclSpec::SCS_typedef: 2005 case DeclSpec::SCS_static: 2006 break; 2007 case DeclSpec::SCS_mutable: 2008 if (isFunc) { 2009 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2010 2011 // FIXME: It would be nicer if the keyword was ignored only for this 2012 // declarator. Otherwise we could get follow-up errors. 2013 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2014 } 2015 break; 2016 default: 2017 Diag(DS.getStorageClassSpecLoc(), 2018 diag::err_storageclass_invalid_for_member); 2019 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2020 break; 2021 } 2022 2023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2025 !isFunc); 2026 2027 if (DS.isConstexprSpecified() && isInstField) { 2028 SemaDiagnosticBuilder B = 2029 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2030 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2031 if (InitStyle == ICIS_NoInit) { 2032 B << 0 << 0; 2033 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2034 B << FixItHint::CreateRemoval(ConstexprLoc); 2035 else { 2036 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2037 D.getMutableDeclSpec().ClearConstexprSpec(); 2038 const char *PrevSpec; 2039 unsigned DiagID; 2040 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2041 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2042 (void)Failed; 2043 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2044 } 2045 } else { 2046 B << 1; 2047 const char *PrevSpec; 2048 unsigned DiagID; 2049 if (D.getMutableDeclSpec().SetStorageClassSpec( 2050 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2051 Context.getPrintingPolicy())) { 2052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2053 "This is the only DeclSpec that should fail to be applied"); 2054 B << 1; 2055 } else { 2056 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2057 isInstField = false; 2058 } 2059 } 2060 } 2061 2062 NamedDecl *Member; 2063 if (isInstField) { 2064 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2065 2066 // Data members must have identifiers for names. 2067 if (!Name.isIdentifier()) { 2068 Diag(Loc, diag::err_bad_variable_name) 2069 << Name; 2070 return nullptr; 2071 } 2072 2073 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2074 2075 // Member field could not be with "template" keyword. 2076 // So TemplateParameterLists should be empty in this case. 2077 if (TemplateParameterLists.size()) { 2078 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2079 if (TemplateParams->size()) { 2080 // There is no such thing as a member field template. 2081 Diag(D.getIdentifierLoc(), diag::err_template_member) 2082 << II 2083 << SourceRange(TemplateParams->getTemplateLoc(), 2084 TemplateParams->getRAngleLoc()); 2085 } else { 2086 // There is an extraneous 'template<>' for this member. 2087 Diag(TemplateParams->getTemplateLoc(), 2088 diag::err_template_member_noparams) 2089 << II 2090 << SourceRange(TemplateParams->getTemplateLoc(), 2091 TemplateParams->getRAngleLoc()); 2092 } 2093 return nullptr; 2094 } 2095 2096 if (SS.isSet() && !SS.isInvalid()) { 2097 // The user provided a superfluous scope specifier inside a class 2098 // definition: 2099 // 2100 // class X { 2101 // int X::member; 2102 // }; 2103 if (DeclContext *DC = computeDeclContext(SS, false)) 2104 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2105 else 2106 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2107 << Name << SS.getRange(); 2108 2109 SS.clear(); 2110 } 2111 2112 AttributeList *MSPropertyAttr = 2113 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2114 if (MSPropertyAttr) { 2115 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2116 BitWidth, InitStyle, AS, MSPropertyAttr); 2117 if (!Member) 2118 return nullptr; 2119 isInstField = false; 2120 } else { 2121 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2122 BitWidth, InitStyle, AS); 2123 assert(Member && "HandleField never returns null"); 2124 } 2125 } else { 2126 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2127 2128 Member = HandleDeclarator(S, D, TemplateParameterLists); 2129 if (!Member) 2130 return nullptr; 2131 2132 // Non-instance-fields can't have a bitfield. 2133 if (BitWidth) { 2134 if (Member->isInvalidDecl()) { 2135 // don't emit another diagnostic. 2136 } else if (isa<VarDecl>(Member)) { 2137 // C++ 9.6p3: A bit-field shall not be a static member. 2138 // "static member 'A' cannot be a bit-field" 2139 Diag(Loc, diag::err_static_not_bitfield) 2140 << Name << BitWidth->getSourceRange(); 2141 } else if (isa<TypedefDecl>(Member)) { 2142 // "typedef member 'x' cannot be a bit-field" 2143 Diag(Loc, diag::err_typedef_not_bitfield) 2144 << Name << BitWidth->getSourceRange(); 2145 } else { 2146 // A function typedef ("typedef int f(); f a;"). 2147 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2148 Diag(Loc, diag::err_not_integral_type_bitfield) 2149 << Name << cast<ValueDecl>(Member)->getType() 2150 << BitWidth->getSourceRange(); 2151 } 2152 2153 BitWidth = nullptr; 2154 Member->setInvalidDecl(); 2155 } 2156 2157 Member->setAccess(AS); 2158 2159 // If we have declared a member function template or static data member 2160 // template, set the access of the templated declaration as well. 2161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2162 FunTmpl->getTemplatedDecl()->setAccess(AS); 2163 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2164 VarTmpl->getTemplatedDecl()->setAccess(AS); 2165 } 2166 2167 if (VS.isOverrideSpecified()) 2168 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2169 if (VS.isFinalSpecified()) 2170 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2171 VS.isFinalSpelledSealed())); 2172 2173 if (VS.getLastLocation().isValid()) { 2174 // Update the end location of a method that has a virt-specifiers. 2175 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2176 MD->setRangeEnd(VS.getLastLocation()); 2177 } 2178 2179 CheckOverrideControl(Member); 2180 2181 assert((Name || isInstField) && "No identifier for non-field ?"); 2182 2183 if (isInstField) { 2184 FieldDecl *FD = cast<FieldDecl>(Member); 2185 FieldCollector->Add(FD); 2186 2187 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2188 // Remember all explicit private FieldDecls that have a name, no side 2189 // effects and are not part of a dependent type declaration. 2190 if (!FD->isImplicit() && FD->getDeclName() && 2191 FD->getAccess() == AS_private && 2192 !FD->hasAttr<UnusedAttr>() && 2193 !FD->getParent()->isDependentContext() && 2194 !InitializationHasSideEffects(*FD)) 2195 UnusedPrivateFields.insert(FD); 2196 } 2197 } 2198 2199 return Member; 2200 } 2201 2202 namespace { 2203 class UninitializedFieldVisitor 2204 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2205 Sema &S; 2206 // List of Decls to generate a warning on. Also remove Decls that become 2207 // initialized. 2208 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2209 // If non-null, add a note to the warning pointing back to the constructor. 2210 const CXXConstructorDecl *Constructor; 2211 public: 2212 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2213 UninitializedFieldVisitor(Sema &S, 2214 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2215 const CXXConstructorDecl *Constructor) 2216 : Inherited(S.Context), S(S), Decls(Decls), 2217 Constructor(Constructor) { } 2218 2219 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2220 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2221 return; 2222 2223 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2224 // or union. 2225 MemberExpr *FieldME = ME; 2226 2227 Expr *Base = ME; 2228 while (isa<MemberExpr>(Base)) { 2229 ME = cast<MemberExpr>(Base); 2230 2231 if (isa<VarDecl>(ME->getMemberDecl())) 2232 return; 2233 2234 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2235 if (!FD->isAnonymousStructOrUnion()) 2236 FieldME = ME; 2237 2238 Base = ME->getBase(); 2239 } 2240 2241 if (!isa<CXXThisExpr>(Base)) 2242 return; 2243 2244 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2245 2246 if (!Decls.count(FoundVD)) 2247 return; 2248 2249 const bool IsReference = FoundVD->getType()->isReferenceType(); 2250 2251 // Prevent double warnings on use of unbounded references. 2252 if (IsReference != CheckReferenceOnly) 2253 return; 2254 2255 unsigned diag = IsReference 2256 ? diag::warn_reference_field_is_uninit 2257 : diag::warn_field_is_uninit; 2258 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2259 if (Constructor) 2260 S.Diag(Constructor->getLocation(), 2261 diag::note_uninit_in_this_constructor) 2262 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2263 2264 } 2265 2266 void HandleValue(Expr *E) { 2267 E = E->IgnoreParens(); 2268 2269 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2270 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2271 return; 2272 } 2273 2274 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2275 HandleValue(CO->getTrueExpr()); 2276 HandleValue(CO->getFalseExpr()); 2277 return; 2278 } 2279 2280 if (BinaryConditionalOperator *BCO = 2281 dyn_cast<BinaryConditionalOperator>(E)) { 2282 HandleValue(BCO->getCommon()); 2283 HandleValue(BCO->getFalseExpr()); 2284 return; 2285 } 2286 2287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2288 switch (BO->getOpcode()) { 2289 default: 2290 return; 2291 case(BO_PtrMemD): 2292 case(BO_PtrMemI): 2293 HandleValue(BO->getLHS()); 2294 return; 2295 case(BO_Comma): 2296 HandleValue(BO->getRHS()); 2297 return; 2298 } 2299 } 2300 } 2301 2302 void VisitMemberExpr(MemberExpr *ME) { 2303 // All uses of unbounded reference fields will warn. 2304 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2305 2306 Inherited::VisitMemberExpr(ME); 2307 } 2308 2309 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2310 if (E->getCastKind() == CK_LValueToRValue) 2311 HandleValue(E->getSubExpr()); 2312 2313 Inherited::VisitImplicitCastExpr(E); 2314 } 2315 2316 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2317 if (E->getConstructor()->isCopyConstructor()) 2318 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2319 if (ICE->getCastKind() == CK_NoOp) 2320 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2321 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2322 2323 Inherited::VisitCXXConstructExpr(E); 2324 } 2325 2326 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2327 Expr *Callee = E->getCallee(); 2328 if (isa<MemberExpr>(Callee)) 2329 HandleValue(Callee); 2330 2331 Inherited::VisitCXXMemberCallExpr(E); 2332 } 2333 2334 void VisitBinaryOperator(BinaryOperator *E) { 2335 // If a field assignment is detected, remove the field from the 2336 // uninitiailized field set. 2337 if (E->getOpcode() == BO_Assign) 2338 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2339 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2340 if (!FD->getType()->isReferenceType()) 2341 Decls.erase(FD); 2342 2343 Inherited::VisitBinaryOperator(E); 2344 } 2345 }; 2346 static void CheckInitExprContainsUninitializedFields( 2347 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2348 const CXXConstructorDecl *Constructor) { 2349 if (Decls.size() == 0) 2350 return; 2351 2352 if (!E) 2353 return; 2354 2355 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2356 E = Default->getExpr(); 2357 if (!E) 2358 return; 2359 // In class initializers will point to the constructor. 2360 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2361 } else { 2362 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E); 2363 } 2364 } 2365 2366 // Diagnose value-uses of fields to initialize themselves, e.g. 2367 // foo(foo) 2368 // where foo is not also a parameter to the constructor. 2369 // Also diagnose across field uninitialized use such as 2370 // x(y), y(x) 2371 // TODO: implement -Wuninitialized and fold this into that framework. 2372 static void DiagnoseUninitializedFields( 2373 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2374 2375 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2376 Constructor->getLocation())) { 2377 return; 2378 } 2379 2380 if (Constructor->isInvalidDecl()) 2381 return; 2382 2383 const CXXRecordDecl *RD = Constructor->getParent(); 2384 2385 // Holds fields that are uninitialized. 2386 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2387 2388 // At the beginning, all fields are uninitialized. 2389 for (auto *I : RD->decls()) { 2390 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2391 UninitializedFields.insert(FD); 2392 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2393 UninitializedFields.insert(IFD->getAnonField()); 2394 } 2395 } 2396 2397 for (const auto *FieldInit : Constructor->inits()) { 2398 Expr *InitExpr = FieldInit->getInit(); 2399 2400 CheckInitExprContainsUninitializedFields( 2401 SemaRef, InitExpr, UninitializedFields, Constructor); 2402 2403 if (FieldDecl *Field = FieldInit->getAnyMember()) 2404 UninitializedFields.erase(Field); 2405 } 2406 } 2407 } // namespace 2408 2409 /// \brief Enter a new C++ default initializer scope. After calling this, the 2410 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2411 /// parsing or instantiating the initializer failed. 2412 void Sema::ActOnStartCXXInClassMemberInitializer() { 2413 // Create a synthetic function scope to represent the call to the constructor 2414 // that notionally surrounds a use of this initializer. 2415 PushFunctionScope(); 2416 } 2417 2418 /// \brief This is invoked after parsing an in-class initializer for a 2419 /// non-static C++ class member, and after instantiating an in-class initializer 2420 /// in a class template. Such actions are deferred until the class is complete. 2421 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2422 SourceLocation InitLoc, 2423 Expr *InitExpr) { 2424 // Pop the notional constructor scope we created earlier. 2425 PopFunctionScopeInfo(nullptr, D); 2426 2427 FieldDecl *FD = cast<FieldDecl>(D); 2428 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2429 "must set init style when field is created"); 2430 2431 if (!InitExpr) { 2432 FD->setInvalidDecl(); 2433 FD->removeInClassInitializer(); 2434 return; 2435 } 2436 2437 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2438 FD->setInvalidDecl(); 2439 FD->removeInClassInitializer(); 2440 return; 2441 } 2442 2443 ExprResult Init = InitExpr; 2444 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2445 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2446 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2447 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2448 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2449 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2450 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2451 if (Init.isInvalid()) { 2452 FD->setInvalidDecl(); 2453 return; 2454 } 2455 } 2456 2457 // C++11 [class.base.init]p7: 2458 // The initialization of each base and member constitutes a 2459 // full-expression. 2460 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2461 if (Init.isInvalid()) { 2462 FD->setInvalidDecl(); 2463 return; 2464 } 2465 2466 InitExpr = Init.get(); 2467 2468 FD->setInClassInitializer(InitExpr); 2469 } 2470 2471 /// \brief Find the direct and/or virtual base specifiers that 2472 /// correspond to the given base type, for use in base initialization 2473 /// within a constructor. 2474 static bool FindBaseInitializer(Sema &SemaRef, 2475 CXXRecordDecl *ClassDecl, 2476 QualType BaseType, 2477 const CXXBaseSpecifier *&DirectBaseSpec, 2478 const CXXBaseSpecifier *&VirtualBaseSpec) { 2479 // First, check for a direct base class. 2480 DirectBaseSpec = nullptr; 2481 for (const auto &Base : ClassDecl->bases()) { 2482 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2483 // We found a direct base of this type. That's what we're 2484 // initializing. 2485 DirectBaseSpec = &Base; 2486 break; 2487 } 2488 } 2489 2490 // Check for a virtual base class. 2491 // FIXME: We might be able to short-circuit this if we know in advance that 2492 // there are no virtual bases. 2493 VirtualBaseSpec = nullptr; 2494 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2495 // We haven't found a base yet; search the class hierarchy for a 2496 // virtual base class. 2497 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2498 /*DetectVirtual=*/false); 2499 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2500 BaseType, Paths)) { 2501 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2502 Path != Paths.end(); ++Path) { 2503 if (Path->back().Base->isVirtual()) { 2504 VirtualBaseSpec = Path->back().Base; 2505 break; 2506 } 2507 } 2508 } 2509 } 2510 2511 return DirectBaseSpec || VirtualBaseSpec; 2512 } 2513 2514 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2515 MemInitResult 2516 Sema::ActOnMemInitializer(Decl *ConstructorD, 2517 Scope *S, 2518 CXXScopeSpec &SS, 2519 IdentifierInfo *MemberOrBase, 2520 ParsedType TemplateTypeTy, 2521 const DeclSpec &DS, 2522 SourceLocation IdLoc, 2523 Expr *InitList, 2524 SourceLocation EllipsisLoc) { 2525 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2526 DS, IdLoc, InitList, 2527 EllipsisLoc); 2528 } 2529 2530 /// \brief Handle a C++ member initializer using parentheses syntax. 2531 MemInitResult 2532 Sema::ActOnMemInitializer(Decl *ConstructorD, 2533 Scope *S, 2534 CXXScopeSpec &SS, 2535 IdentifierInfo *MemberOrBase, 2536 ParsedType TemplateTypeTy, 2537 const DeclSpec &DS, 2538 SourceLocation IdLoc, 2539 SourceLocation LParenLoc, 2540 ArrayRef<Expr *> Args, 2541 SourceLocation RParenLoc, 2542 SourceLocation EllipsisLoc) { 2543 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2544 Args, RParenLoc); 2545 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2546 DS, IdLoc, List, EllipsisLoc); 2547 } 2548 2549 namespace { 2550 2551 // Callback to only accept typo corrections that can be a valid C++ member 2552 // intializer: either a non-static field member or a base class. 2553 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2554 public: 2555 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2556 : ClassDecl(ClassDecl) {} 2557 2558 bool ValidateCandidate(const TypoCorrection &candidate) override { 2559 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2560 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2561 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2562 return isa<TypeDecl>(ND); 2563 } 2564 return false; 2565 } 2566 2567 private: 2568 CXXRecordDecl *ClassDecl; 2569 }; 2570 2571 } 2572 2573 /// \brief Handle a C++ member initializer. 2574 MemInitResult 2575 Sema::BuildMemInitializer(Decl *ConstructorD, 2576 Scope *S, 2577 CXXScopeSpec &SS, 2578 IdentifierInfo *MemberOrBase, 2579 ParsedType TemplateTypeTy, 2580 const DeclSpec &DS, 2581 SourceLocation IdLoc, 2582 Expr *Init, 2583 SourceLocation EllipsisLoc) { 2584 if (!ConstructorD) 2585 return true; 2586 2587 AdjustDeclIfTemplate(ConstructorD); 2588 2589 CXXConstructorDecl *Constructor 2590 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2591 if (!Constructor) { 2592 // The user wrote a constructor initializer on a function that is 2593 // not a C++ constructor. Ignore the error for now, because we may 2594 // have more member initializers coming; we'll diagnose it just 2595 // once in ActOnMemInitializers. 2596 return true; 2597 } 2598 2599 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2600 2601 // C++ [class.base.init]p2: 2602 // Names in a mem-initializer-id are looked up in the scope of the 2603 // constructor's class and, if not found in that scope, are looked 2604 // up in the scope containing the constructor's definition. 2605 // [Note: if the constructor's class contains a member with the 2606 // same name as a direct or virtual base class of the class, a 2607 // mem-initializer-id naming the member or base class and composed 2608 // of a single identifier refers to the class member. A 2609 // mem-initializer-id for the hidden base class may be specified 2610 // using a qualified name. ] 2611 if (!SS.getScopeRep() && !TemplateTypeTy) { 2612 // Look for a member, first. 2613 DeclContext::lookup_result Result 2614 = ClassDecl->lookup(MemberOrBase); 2615 if (!Result.empty()) { 2616 ValueDecl *Member; 2617 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2618 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2619 if (EllipsisLoc.isValid()) 2620 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2621 << MemberOrBase 2622 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2623 2624 return BuildMemberInitializer(Member, Init, IdLoc); 2625 } 2626 } 2627 } 2628 // It didn't name a member, so see if it names a class. 2629 QualType BaseType; 2630 TypeSourceInfo *TInfo = nullptr; 2631 2632 if (TemplateTypeTy) { 2633 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2634 } else if (DS.getTypeSpecType() == TST_decltype) { 2635 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2636 } else { 2637 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2638 LookupParsedName(R, S, &SS); 2639 2640 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2641 if (!TyD) { 2642 if (R.isAmbiguous()) return true; 2643 2644 // We don't want access-control diagnostics here. 2645 R.suppressDiagnostics(); 2646 2647 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2648 bool NotUnknownSpecialization = false; 2649 DeclContext *DC = computeDeclContext(SS, false); 2650 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2651 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2652 2653 if (!NotUnknownSpecialization) { 2654 // When the scope specifier can refer to a member of an unknown 2655 // specialization, we take it as a type name. 2656 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2657 SS.getWithLocInContext(Context), 2658 *MemberOrBase, IdLoc); 2659 if (BaseType.isNull()) 2660 return true; 2661 2662 R.clear(); 2663 R.setLookupName(MemberOrBase); 2664 } 2665 } 2666 2667 // If no results were found, try to correct typos. 2668 TypoCorrection Corr; 2669 MemInitializerValidatorCCC Validator(ClassDecl); 2670 if (R.empty() && BaseType.isNull() && 2671 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2672 Validator, CTK_ErrorRecovery, ClassDecl))) { 2673 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2674 // We have found a non-static data member with a similar 2675 // name to what was typed; complain and initialize that 2676 // member. 2677 diagnoseTypo(Corr, 2678 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2679 << MemberOrBase << true); 2680 return BuildMemberInitializer(Member, Init, IdLoc); 2681 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2682 const CXXBaseSpecifier *DirectBaseSpec; 2683 const CXXBaseSpecifier *VirtualBaseSpec; 2684 if (FindBaseInitializer(*this, ClassDecl, 2685 Context.getTypeDeclType(Type), 2686 DirectBaseSpec, VirtualBaseSpec)) { 2687 // We have found a direct or virtual base class with a 2688 // similar name to what was typed; complain and initialize 2689 // that base class. 2690 diagnoseTypo(Corr, 2691 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2692 << MemberOrBase << false, 2693 PDiag() /*Suppress note, we provide our own.*/); 2694 2695 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2696 : VirtualBaseSpec; 2697 Diag(BaseSpec->getLocStart(), 2698 diag::note_base_class_specified_here) 2699 << BaseSpec->getType() 2700 << BaseSpec->getSourceRange(); 2701 2702 TyD = Type; 2703 } 2704 } 2705 } 2706 2707 if (!TyD && BaseType.isNull()) { 2708 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2709 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2710 return true; 2711 } 2712 } 2713 2714 if (BaseType.isNull()) { 2715 BaseType = Context.getTypeDeclType(TyD); 2716 if (SS.isSet()) 2717 // FIXME: preserve source range information 2718 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2719 BaseType); 2720 } 2721 } 2722 2723 if (!TInfo) 2724 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2725 2726 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2727 } 2728 2729 /// Checks a member initializer expression for cases where reference (or 2730 /// pointer) members are bound to by-value parameters (or their addresses). 2731 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2732 Expr *Init, 2733 SourceLocation IdLoc) { 2734 QualType MemberTy = Member->getType(); 2735 2736 // We only handle pointers and references currently. 2737 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2738 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2739 return; 2740 2741 const bool IsPointer = MemberTy->isPointerType(); 2742 if (IsPointer) { 2743 if (const UnaryOperator *Op 2744 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2745 // The only case we're worried about with pointers requires taking the 2746 // address. 2747 if (Op->getOpcode() != UO_AddrOf) 2748 return; 2749 2750 Init = Op->getSubExpr(); 2751 } else { 2752 // We only handle address-of expression initializers for pointers. 2753 return; 2754 } 2755 } 2756 2757 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2758 // We only warn when referring to a non-reference parameter declaration. 2759 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2760 if (!Parameter || Parameter->getType()->isReferenceType()) 2761 return; 2762 2763 S.Diag(Init->getExprLoc(), 2764 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2765 : diag::warn_bind_ref_member_to_parameter) 2766 << Member << Parameter << Init->getSourceRange(); 2767 } else { 2768 // Other initializers are fine. 2769 return; 2770 } 2771 2772 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2773 << (unsigned)IsPointer; 2774 } 2775 2776 MemInitResult 2777 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2778 SourceLocation IdLoc) { 2779 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2780 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2781 assert((DirectMember || IndirectMember) && 2782 "Member must be a FieldDecl or IndirectFieldDecl"); 2783 2784 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2785 return true; 2786 2787 if (Member->isInvalidDecl()) 2788 return true; 2789 2790 MultiExprArg Args; 2791 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2792 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2793 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2794 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2795 } else { 2796 // Template instantiation doesn't reconstruct ParenListExprs for us. 2797 Args = Init; 2798 } 2799 2800 SourceRange InitRange = Init->getSourceRange(); 2801 2802 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2803 // Can't check initialization for a member of dependent type or when 2804 // any of the arguments are type-dependent expressions. 2805 DiscardCleanupsInEvaluationContext(); 2806 } else { 2807 bool InitList = false; 2808 if (isa<InitListExpr>(Init)) { 2809 InitList = true; 2810 Args = Init; 2811 } 2812 2813 // Initialize the member. 2814 InitializedEntity MemberEntity = 2815 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 2816 : InitializedEntity::InitializeMember(IndirectMember, 2817 nullptr); 2818 InitializationKind Kind = 2819 InitList ? InitializationKind::CreateDirectList(IdLoc) 2820 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2821 InitRange.getEnd()); 2822 2823 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2824 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 2825 nullptr); 2826 if (MemberInit.isInvalid()) 2827 return true; 2828 2829 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2830 2831 // C++11 [class.base.init]p7: 2832 // The initialization of each base and member constitutes a 2833 // full-expression. 2834 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2835 if (MemberInit.isInvalid()) 2836 return true; 2837 2838 Init = MemberInit.get(); 2839 } 2840 2841 if (DirectMember) { 2842 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2843 InitRange.getBegin(), Init, 2844 InitRange.getEnd()); 2845 } else { 2846 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2847 InitRange.getBegin(), Init, 2848 InitRange.getEnd()); 2849 } 2850 } 2851 2852 MemInitResult 2853 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2854 CXXRecordDecl *ClassDecl) { 2855 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2856 if (!LangOpts.CPlusPlus11) 2857 return Diag(NameLoc, diag::err_delegating_ctor) 2858 << TInfo->getTypeLoc().getLocalSourceRange(); 2859 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2860 2861 bool InitList = true; 2862 MultiExprArg Args = Init; 2863 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2864 InitList = false; 2865 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2866 } 2867 2868 SourceRange InitRange = Init->getSourceRange(); 2869 // Initialize the object. 2870 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2871 QualType(ClassDecl->getTypeForDecl(), 0)); 2872 InitializationKind Kind = 2873 InitList ? InitializationKind::CreateDirectList(NameLoc) 2874 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2875 InitRange.getEnd()); 2876 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2877 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2878 Args, nullptr); 2879 if (DelegationInit.isInvalid()) 2880 return true; 2881 2882 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2883 "Delegating constructor with no target?"); 2884 2885 // C++11 [class.base.init]p7: 2886 // The initialization of each base and member constitutes a 2887 // full-expression. 2888 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2889 InitRange.getBegin()); 2890 if (DelegationInit.isInvalid()) 2891 return true; 2892 2893 // If we are in a dependent context, template instantiation will 2894 // perform this type-checking again. Just save the arguments that we 2895 // received in a ParenListExpr. 2896 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2897 // of the information that we have about the base 2898 // initializer. However, deconstructing the ASTs is a dicey process, 2899 // and this approach is far more likely to get the corner cases right. 2900 if (CurContext->isDependentContext()) 2901 DelegationInit = Init; 2902 2903 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2904 DelegationInit.getAs<Expr>(), 2905 InitRange.getEnd()); 2906 } 2907 2908 MemInitResult 2909 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2910 Expr *Init, CXXRecordDecl *ClassDecl, 2911 SourceLocation EllipsisLoc) { 2912 SourceLocation BaseLoc 2913 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2914 2915 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2916 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2917 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2918 2919 // C++ [class.base.init]p2: 2920 // [...] Unless the mem-initializer-id names a nonstatic data 2921 // member of the constructor's class or a direct or virtual base 2922 // of that class, the mem-initializer is ill-formed. A 2923 // mem-initializer-list can initialize a base class using any 2924 // name that denotes that base class type. 2925 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2926 2927 SourceRange InitRange = Init->getSourceRange(); 2928 if (EllipsisLoc.isValid()) { 2929 // This is a pack expansion. 2930 if (!BaseType->containsUnexpandedParameterPack()) { 2931 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2932 << SourceRange(BaseLoc, InitRange.getEnd()); 2933 2934 EllipsisLoc = SourceLocation(); 2935 } 2936 } else { 2937 // Check for any unexpanded parameter packs. 2938 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2939 return true; 2940 2941 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2942 return true; 2943 } 2944 2945 // Check for direct and virtual base classes. 2946 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 2947 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 2948 if (!Dependent) { 2949 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2950 BaseType)) 2951 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2952 2953 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2954 VirtualBaseSpec); 2955 2956 // C++ [base.class.init]p2: 2957 // Unless the mem-initializer-id names a nonstatic data member of the 2958 // constructor's class or a direct or virtual base of that class, the 2959 // mem-initializer is ill-formed. 2960 if (!DirectBaseSpec && !VirtualBaseSpec) { 2961 // If the class has any dependent bases, then it's possible that 2962 // one of those types will resolve to the same type as 2963 // BaseType. Therefore, just treat this as a dependent base 2964 // class initialization. FIXME: Should we try to check the 2965 // initialization anyway? It seems odd. 2966 if (ClassDecl->hasAnyDependentBases()) 2967 Dependent = true; 2968 else 2969 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2970 << BaseType << Context.getTypeDeclType(ClassDecl) 2971 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2972 } 2973 } 2974 2975 if (Dependent) { 2976 DiscardCleanupsInEvaluationContext(); 2977 2978 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2979 /*IsVirtual=*/false, 2980 InitRange.getBegin(), Init, 2981 InitRange.getEnd(), EllipsisLoc); 2982 } 2983 2984 // C++ [base.class.init]p2: 2985 // If a mem-initializer-id is ambiguous because it designates both 2986 // a direct non-virtual base class and an inherited virtual base 2987 // class, the mem-initializer is ill-formed. 2988 if (DirectBaseSpec && VirtualBaseSpec) 2989 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2990 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2991 2992 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2993 if (!BaseSpec) 2994 BaseSpec = VirtualBaseSpec; 2995 2996 // Initialize the base. 2997 bool InitList = true; 2998 MultiExprArg Args = Init; 2999 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3000 InitList = false; 3001 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3002 } 3003 3004 InitializedEntity BaseEntity = 3005 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3006 InitializationKind Kind = 3007 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3008 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3009 InitRange.getEnd()); 3010 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3011 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3012 if (BaseInit.isInvalid()) 3013 return true; 3014 3015 // C++11 [class.base.init]p7: 3016 // The initialization of each base and member constitutes a 3017 // full-expression. 3018 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3019 if (BaseInit.isInvalid()) 3020 return true; 3021 3022 // If we are in a dependent context, template instantiation will 3023 // perform this type-checking again. Just save the arguments that we 3024 // received in a ParenListExpr. 3025 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3026 // of the information that we have about the base 3027 // initializer. However, deconstructing the ASTs is a dicey process, 3028 // and this approach is far more likely to get the corner cases right. 3029 if (CurContext->isDependentContext()) 3030 BaseInit = Init; 3031 3032 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3033 BaseSpec->isVirtual(), 3034 InitRange.getBegin(), 3035 BaseInit.getAs<Expr>(), 3036 InitRange.getEnd(), EllipsisLoc); 3037 } 3038 3039 // Create a static_cast\<T&&>(expr). 3040 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3041 if (T.isNull()) T = E->getType(); 3042 QualType TargetType = SemaRef.BuildReferenceType( 3043 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3044 SourceLocation ExprLoc = E->getLocStart(); 3045 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3046 TargetType, ExprLoc); 3047 3048 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3049 SourceRange(ExprLoc, ExprLoc), 3050 E->getSourceRange()).get(); 3051 } 3052 3053 /// ImplicitInitializerKind - How an implicit base or member initializer should 3054 /// initialize its base or member. 3055 enum ImplicitInitializerKind { 3056 IIK_Default, 3057 IIK_Copy, 3058 IIK_Move, 3059 IIK_Inherit 3060 }; 3061 3062 static bool 3063 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3064 ImplicitInitializerKind ImplicitInitKind, 3065 CXXBaseSpecifier *BaseSpec, 3066 bool IsInheritedVirtualBase, 3067 CXXCtorInitializer *&CXXBaseInit) { 3068 InitializedEntity InitEntity 3069 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3070 IsInheritedVirtualBase); 3071 3072 ExprResult BaseInit; 3073 3074 switch (ImplicitInitKind) { 3075 case IIK_Inherit: { 3076 const CXXRecordDecl *Inherited = 3077 Constructor->getInheritedConstructor()->getParent(); 3078 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3079 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3080 // C++11 [class.inhctor]p8: 3081 // Each expression in the expression-list is of the form 3082 // static_cast<T&&>(p), where p is the name of the corresponding 3083 // constructor parameter and T is the declared type of p. 3084 SmallVector<Expr*, 16> Args; 3085 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3086 ParmVarDecl *PD = Constructor->getParamDecl(I); 3087 ExprResult ArgExpr = 3088 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3089 VK_LValue, SourceLocation()); 3090 if (ArgExpr.isInvalid()) 3091 return true; 3092 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3093 } 3094 3095 InitializationKind InitKind = InitializationKind::CreateDirect( 3096 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3097 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3098 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3099 break; 3100 } 3101 } 3102 // Fall through. 3103 case IIK_Default: { 3104 InitializationKind InitKind 3105 = InitializationKind::CreateDefault(Constructor->getLocation()); 3106 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3107 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3108 break; 3109 } 3110 3111 case IIK_Move: 3112 case IIK_Copy: { 3113 bool Moving = ImplicitInitKind == IIK_Move; 3114 ParmVarDecl *Param = Constructor->getParamDecl(0); 3115 QualType ParamType = Param->getType().getNonReferenceType(); 3116 3117 Expr *CopyCtorArg = 3118 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3119 SourceLocation(), Param, false, 3120 Constructor->getLocation(), ParamType, 3121 VK_LValue, nullptr); 3122 3123 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3124 3125 // Cast to the base class to avoid ambiguities. 3126 QualType ArgTy = 3127 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3128 ParamType.getQualifiers()); 3129 3130 if (Moving) { 3131 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3132 } 3133 3134 CXXCastPath BasePath; 3135 BasePath.push_back(BaseSpec); 3136 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3137 CK_UncheckedDerivedToBase, 3138 Moving ? VK_XValue : VK_LValue, 3139 &BasePath).get(); 3140 3141 InitializationKind InitKind 3142 = InitializationKind::CreateDirect(Constructor->getLocation(), 3143 SourceLocation(), SourceLocation()); 3144 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3145 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3146 break; 3147 } 3148 } 3149 3150 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3151 if (BaseInit.isInvalid()) 3152 return true; 3153 3154 CXXBaseInit = 3155 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3156 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3157 SourceLocation()), 3158 BaseSpec->isVirtual(), 3159 SourceLocation(), 3160 BaseInit.getAs<Expr>(), 3161 SourceLocation(), 3162 SourceLocation()); 3163 3164 return false; 3165 } 3166 3167 static bool RefersToRValueRef(Expr *MemRef) { 3168 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3169 return Referenced->getType()->isRValueReferenceType(); 3170 } 3171 3172 static bool 3173 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3174 ImplicitInitializerKind ImplicitInitKind, 3175 FieldDecl *Field, IndirectFieldDecl *Indirect, 3176 CXXCtorInitializer *&CXXMemberInit) { 3177 if (Field->isInvalidDecl()) 3178 return true; 3179 3180 SourceLocation Loc = Constructor->getLocation(); 3181 3182 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3183 bool Moving = ImplicitInitKind == IIK_Move; 3184 ParmVarDecl *Param = Constructor->getParamDecl(0); 3185 QualType ParamType = Param->getType().getNonReferenceType(); 3186 3187 // Suppress copying zero-width bitfields. 3188 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3189 return false; 3190 3191 Expr *MemberExprBase = 3192 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3193 SourceLocation(), Param, false, 3194 Loc, ParamType, VK_LValue, nullptr); 3195 3196 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3197 3198 if (Moving) { 3199 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3200 } 3201 3202 // Build a reference to this field within the parameter. 3203 CXXScopeSpec SS; 3204 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3205 Sema::LookupMemberName); 3206 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3207 : cast<ValueDecl>(Field), AS_public); 3208 MemberLookup.resolveKind(); 3209 ExprResult CtorArg 3210 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3211 ParamType, Loc, 3212 /*IsArrow=*/false, 3213 SS, 3214 /*TemplateKWLoc=*/SourceLocation(), 3215 /*FirstQualifierInScope=*/nullptr, 3216 MemberLookup, 3217 /*TemplateArgs=*/nullptr); 3218 if (CtorArg.isInvalid()) 3219 return true; 3220 3221 // C++11 [class.copy]p15: 3222 // - if a member m has rvalue reference type T&&, it is direct-initialized 3223 // with static_cast<T&&>(x.m); 3224 if (RefersToRValueRef(CtorArg.get())) { 3225 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3226 } 3227 3228 // When the field we are copying is an array, create index variables for 3229 // each dimension of the array. We use these index variables to subscript 3230 // the source array, and other clients (e.g., CodeGen) will perform the 3231 // necessary iteration with these index variables. 3232 SmallVector<VarDecl *, 4> IndexVariables; 3233 QualType BaseType = Field->getType(); 3234 QualType SizeType = SemaRef.Context.getSizeType(); 3235 bool InitializingArray = false; 3236 while (const ConstantArrayType *Array 3237 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3238 InitializingArray = true; 3239 // Create the iteration variable for this array index. 3240 IdentifierInfo *IterationVarName = nullptr; 3241 { 3242 SmallString<8> Str; 3243 llvm::raw_svector_ostream OS(Str); 3244 OS << "__i" << IndexVariables.size(); 3245 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3246 } 3247 VarDecl *IterationVar 3248 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3249 IterationVarName, SizeType, 3250 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3251 SC_None); 3252 IndexVariables.push_back(IterationVar); 3253 3254 // Create a reference to the iteration variable. 3255 ExprResult IterationVarRef 3256 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3257 assert(!IterationVarRef.isInvalid() && 3258 "Reference to invented variable cannot fail!"); 3259 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3260 assert(!IterationVarRef.isInvalid() && 3261 "Conversion of invented variable cannot fail!"); 3262 3263 // Subscript the array with this iteration variable. 3264 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3265 IterationVarRef.get(), 3266 Loc); 3267 if (CtorArg.isInvalid()) 3268 return true; 3269 3270 BaseType = Array->getElementType(); 3271 } 3272 3273 // The array subscript expression is an lvalue, which is wrong for moving. 3274 if (Moving && InitializingArray) 3275 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3276 3277 // Construct the entity that we will be initializing. For an array, this 3278 // will be first element in the array, which may require several levels 3279 // of array-subscript entities. 3280 SmallVector<InitializedEntity, 4> Entities; 3281 Entities.reserve(1 + IndexVariables.size()); 3282 if (Indirect) 3283 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3284 else 3285 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3286 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3287 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3288 0, 3289 Entities.back())); 3290 3291 // Direct-initialize to use the copy constructor. 3292 InitializationKind InitKind = 3293 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3294 3295 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3296 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3297 3298 ExprResult MemberInit 3299 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3300 MultiExprArg(&CtorArgE, 1)); 3301 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3302 if (MemberInit.isInvalid()) 3303 return true; 3304 3305 if (Indirect) { 3306 assert(IndexVariables.size() == 0 && 3307 "Indirect field improperly initialized"); 3308 CXXMemberInit 3309 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3310 Loc, Loc, 3311 MemberInit.getAs<Expr>(), 3312 Loc); 3313 } else 3314 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3315 Loc, MemberInit.getAs<Expr>(), 3316 Loc, 3317 IndexVariables.data(), 3318 IndexVariables.size()); 3319 return false; 3320 } 3321 3322 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3323 "Unhandled implicit init kind!"); 3324 3325 QualType FieldBaseElementType = 3326 SemaRef.Context.getBaseElementType(Field->getType()); 3327 3328 if (FieldBaseElementType->isRecordType()) { 3329 InitializedEntity InitEntity 3330 = Indirect? InitializedEntity::InitializeMember(Indirect) 3331 : InitializedEntity::InitializeMember(Field); 3332 InitializationKind InitKind = 3333 InitializationKind::CreateDefault(Loc); 3334 3335 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3336 ExprResult MemberInit = 3337 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3338 3339 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3340 if (MemberInit.isInvalid()) 3341 return true; 3342 3343 if (Indirect) 3344 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3345 Indirect, Loc, 3346 Loc, 3347 MemberInit.get(), 3348 Loc); 3349 else 3350 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3351 Field, Loc, Loc, 3352 MemberInit.get(), 3353 Loc); 3354 return false; 3355 } 3356 3357 if (!Field->getParent()->isUnion()) { 3358 if (FieldBaseElementType->isReferenceType()) { 3359 SemaRef.Diag(Constructor->getLocation(), 3360 diag::err_uninitialized_member_in_ctor) 3361 << (int)Constructor->isImplicit() 3362 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3363 << 0 << Field->getDeclName(); 3364 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3365 return true; 3366 } 3367 3368 if (FieldBaseElementType.isConstQualified()) { 3369 SemaRef.Diag(Constructor->getLocation(), 3370 diag::err_uninitialized_member_in_ctor) 3371 << (int)Constructor->isImplicit() 3372 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3373 << 1 << Field->getDeclName(); 3374 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3375 return true; 3376 } 3377 } 3378 3379 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3380 FieldBaseElementType->isObjCRetainableType() && 3381 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3382 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3383 // ARC: 3384 // Default-initialize Objective-C pointers to NULL. 3385 CXXMemberInit 3386 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3387 Loc, Loc, 3388 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3389 Loc); 3390 return false; 3391 } 3392 3393 // Nothing to initialize. 3394 CXXMemberInit = nullptr; 3395 return false; 3396 } 3397 3398 namespace { 3399 struct BaseAndFieldInfo { 3400 Sema &S; 3401 CXXConstructorDecl *Ctor; 3402 bool AnyErrorsInInits; 3403 ImplicitInitializerKind IIK; 3404 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3405 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3406 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3407 3408 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3409 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3410 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3411 if (Generated && Ctor->isCopyConstructor()) 3412 IIK = IIK_Copy; 3413 else if (Generated && Ctor->isMoveConstructor()) 3414 IIK = IIK_Move; 3415 else if (Ctor->getInheritedConstructor()) 3416 IIK = IIK_Inherit; 3417 else 3418 IIK = IIK_Default; 3419 } 3420 3421 bool isImplicitCopyOrMove() const { 3422 switch (IIK) { 3423 case IIK_Copy: 3424 case IIK_Move: 3425 return true; 3426 3427 case IIK_Default: 3428 case IIK_Inherit: 3429 return false; 3430 } 3431 3432 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3433 } 3434 3435 bool addFieldInitializer(CXXCtorInitializer *Init) { 3436 AllToInit.push_back(Init); 3437 3438 // Check whether this initializer makes the field "used". 3439 if (Init->getInit()->HasSideEffects(S.Context)) 3440 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3441 3442 return false; 3443 } 3444 3445 bool isInactiveUnionMember(FieldDecl *Field) { 3446 RecordDecl *Record = Field->getParent(); 3447 if (!Record->isUnion()) 3448 return false; 3449 3450 if (FieldDecl *Active = 3451 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3452 return Active != Field->getCanonicalDecl(); 3453 3454 // In an implicit copy or move constructor, ignore any in-class initializer. 3455 if (isImplicitCopyOrMove()) 3456 return true; 3457 3458 // If there's no explicit initialization, the field is active only if it 3459 // has an in-class initializer... 3460 if (Field->hasInClassInitializer()) 3461 return false; 3462 // ... or it's an anonymous struct or union whose class has an in-class 3463 // initializer. 3464 if (!Field->isAnonymousStructOrUnion()) 3465 return true; 3466 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3467 return !FieldRD->hasInClassInitializer(); 3468 } 3469 3470 /// \brief Determine whether the given field is, or is within, a union member 3471 /// that is inactive (because there was an initializer given for a different 3472 /// member of the union, or because the union was not initialized at all). 3473 bool isWithinInactiveUnionMember(FieldDecl *Field, 3474 IndirectFieldDecl *Indirect) { 3475 if (!Indirect) 3476 return isInactiveUnionMember(Field); 3477 3478 for (auto *C : Indirect->chain()) { 3479 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3480 if (Field && isInactiveUnionMember(Field)) 3481 return true; 3482 } 3483 return false; 3484 } 3485 }; 3486 } 3487 3488 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3489 /// array type. 3490 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3491 if (T->isIncompleteArrayType()) 3492 return true; 3493 3494 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3495 if (!ArrayT->getSize()) 3496 return true; 3497 3498 T = ArrayT->getElementType(); 3499 } 3500 3501 return false; 3502 } 3503 3504 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3505 FieldDecl *Field, 3506 IndirectFieldDecl *Indirect = nullptr) { 3507 if (Field->isInvalidDecl()) 3508 return false; 3509 3510 // Overwhelmingly common case: we have a direct initializer for this field. 3511 if (CXXCtorInitializer *Init = 3512 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3513 return Info.addFieldInitializer(Init); 3514 3515 // C++11 [class.base.init]p8: 3516 // if the entity is a non-static data member that has a 3517 // brace-or-equal-initializer and either 3518 // -- the constructor's class is a union and no other variant member of that 3519 // union is designated by a mem-initializer-id or 3520 // -- the constructor's class is not a union, and, if the entity is a member 3521 // of an anonymous union, no other member of that union is designated by 3522 // a mem-initializer-id, 3523 // the entity is initialized as specified in [dcl.init]. 3524 // 3525 // We also apply the same rules to handle anonymous structs within anonymous 3526 // unions. 3527 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3528 return false; 3529 3530 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3531 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3532 Info.Ctor->getLocation(), Field); 3533 CXXCtorInitializer *Init; 3534 if (Indirect) 3535 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3536 SourceLocation(), 3537 SourceLocation(), DIE, 3538 SourceLocation()); 3539 else 3540 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3541 SourceLocation(), 3542 SourceLocation(), DIE, 3543 SourceLocation()); 3544 return Info.addFieldInitializer(Init); 3545 } 3546 3547 // Don't initialize incomplete or zero-length arrays. 3548 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3549 return false; 3550 3551 // Don't try to build an implicit initializer if there were semantic 3552 // errors in any of the initializers (and therefore we might be 3553 // missing some that the user actually wrote). 3554 if (Info.AnyErrorsInInits) 3555 return false; 3556 3557 CXXCtorInitializer *Init = nullptr; 3558 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3559 Indirect, Init)) 3560 return true; 3561 3562 if (!Init) 3563 return false; 3564 3565 return Info.addFieldInitializer(Init); 3566 } 3567 3568 bool 3569 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3570 CXXCtorInitializer *Initializer) { 3571 assert(Initializer->isDelegatingInitializer()); 3572 Constructor->setNumCtorInitializers(1); 3573 CXXCtorInitializer **initializer = 3574 new (Context) CXXCtorInitializer*[1]; 3575 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3576 Constructor->setCtorInitializers(initializer); 3577 3578 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3579 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3580 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3581 } 3582 3583 DelegatingCtorDecls.push_back(Constructor); 3584 3585 return false; 3586 } 3587 3588 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3589 ArrayRef<CXXCtorInitializer *> Initializers) { 3590 if (Constructor->isDependentContext()) { 3591 // Just store the initializers as written, they will be checked during 3592 // instantiation. 3593 if (!Initializers.empty()) { 3594 Constructor->setNumCtorInitializers(Initializers.size()); 3595 CXXCtorInitializer **baseOrMemberInitializers = 3596 new (Context) CXXCtorInitializer*[Initializers.size()]; 3597 memcpy(baseOrMemberInitializers, Initializers.data(), 3598 Initializers.size() * sizeof(CXXCtorInitializer*)); 3599 Constructor->setCtorInitializers(baseOrMemberInitializers); 3600 } 3601 3602 // Let template instantiation know whether we had errors. 3603 if (AnyErrors) 3604 Constructor->setInvalidDecl(); 3605 3606 return false; 3607 } 3608 3609 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3610 3611 // We need to build the initializer AST according to order of construction 3612 // and not what user specified in the Initializers list. 3613 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3614 if (!ClassDecl) 3615 return true; 3616 3617 bool HadError = false; 3618 3619 for (unsigned i = 0; i < Initializers.size(); i++) { 3620 CXXCtorInitializer *Member = Initializers[i]; 3621 3622 if (Member->isBaseInitializer()) 3623 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3624 else { 3625 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3626 3627 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3628 for (auto *C : F->chain()) { 3629 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3630 if (FD && FD->getParent()->isUnion()) 3631 Info.ActiveUnionMember.insert(std::make_pair( 3632 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3633 } 3634 } else if (FieldDecl *FD = Member->getMember()) { 3635 if (FD->getParent()->isUnion()) 3636 Info.ActiveUnionMember.insert(std::make_pair( 3637 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3638 } 3639 } 3640 } 3641 3642 // Keep track of the direct virtual bases. 3643 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3644 for (auto &I : ClassDecl->bases()) { 3645 if (I.isVirtual()) 3646 DirectVBases.insert(&I); 3647 } 3648 3649 // Push virtual bases before others. 3650 for (auto &VBase : ClassDecl->vbases()) { 3651 if (CXXCtorInitializer *Value 3652 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3653 // [class.base.init]p7, per DR257: 3654 // A mem-initializer where the mem-initializer-id names a virtual base 3655 // class is ignored during execution of a constructor of any class that 3656 // is not the most derived class. 3657 if (ClassDecl->isAbstract()) { 3658 // FIXME: Provide a fixit to remove the base specifier. This requires 3659 // tracking the location of the associated comma for a base specifier. 3660 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3661 << VBase.getType() << ClassDecl; 3662 DiagnoseAbstractType(ClassDecl); 3663 } 3664 3665 Info.AllToInit.push_back(Value); 3666 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3667 // [class.base.init]p8, per DR257: 3668 // If a given [...] base class is not named by a mem-initializer-id 3669 // [...] and the entity is not a virtual base class of an abstract 3670 // class, then [...] the entity is default-initialized. 3671 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3672 CXXCtorInitializer *CXXBaseInit; 3673 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3674 &VBase, IsInheritedVirtualBase, 3675 CXXBaseInit)) { 3676 HadError = true; 3677 continue; 3678 } 3679 3680 Info.AllToInit.push_back(CXXBaseInit); 3681 } 3682 } 3683 3684 // Non-virtual bases. 3685 for (auto &Base : ClassDecl->bases()) { 3686 // Virtuals are in the virtual base list and already constructed. 3687 if (Base.isVirtual()) 3688 continue; 3689 3690 if (CXXCtorInitializer *Value 3691 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3692 Info.AllToInit.push_back(Value); 3693 } else if (!AnyErrors) { 3694 CXXCtorInitializer *CXXBaseInit; 3695 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3696 &Base, /*IsInheritedVirtualBase=*/false, 3697 CXXBaseInit)) { 3698 HadError = true; 3699 continue; 3700 } 3701 3702 Info.AllToInit.push_back(CXXBaseInit); 3703 } 3704 } 3705 3706 // Fields. 3707 for (auto *Mem : ClassDecl->decls()) { 3708 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3709 // C++ [class.bit]p2: 3710 // A declaration for a bit-field that omits the identifier declares an 3711 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3712 // initialized. 3713 if (F->isUnnamedBitfield()) 3714 continue; 3715 3716 // If we're not generating the implicit copy/move constructor, then we'll 3717 // handle anonymous struct/union fields based on their individual 3718 // indirect fields. 3719 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3720 continue; 3721 3722 if (CollectFieldInitializer(*this, Info, F)) 3723 HadError = true; 3724 continue; 3725 } 3726 3727 // Beyond this point, we only consider default initialization. 3728 if (Info.isImplicitCopyOrMove()) 3729 continue; 3730 3731 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3732 if (F->getType()->isIncompleteArrayType()) { 3733 assert(ClassDecl->hasFlexibleArrayMember() && 3734 "Incomplete array type is not valid"); 3735 continue; 3736 } 3737 3738 // Initialize each field of an anonymous struct individually. 3739 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3740 HadError = true; 3741 3742 continue; 3743 } 3744 } 3745 3746 unsigned NumInitializers = Info.AllToInit.size(); 3747 if (NumInitializers > 0) { 3748 Constructor->setNumCtorInitializers(NumInitializers); 3749 CXXCtorInitializer **baseOrMemberInitializers = 3750 new (Context) CXXCtorInitializer*[NumInitializers]; 3751 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3752 NumInitializers * sizeof(CXXCtorInitializer*)); 3753 Constructor->setCtorInitializers(baseOrMemberInitializers); 3754 3755 // Constructors implicitly reference the base and member 3756 // destructors. 3757 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3758 Constructor->getParent()); 3759 } 3760 3761 return HadError; 3762 } 3763 3764 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3765 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3766 const RecordDecl *RD = RT->getDecl(); 3767 if (RD->isAnonymousStructOrUnion()) { 3768 for (auto *Field : RD->fields()) 3769 PopulateKeysForFields(Field, IdealInits); 3770 return; 3771 } 3772 } 3773 IdealInits.push_back(Field->getCanonicalDecl()); 3774 } 3775 3776 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3777 return Context.getCanonicalType(BaseType).getTypePtr(); 3778 } 3779 3780 static const void *GetKeyForMember(ASTContext &Context, 3781 CXXCtorInitializer *Member) { 3782 if (!Member->isAnyMemberInitializer()) 3783 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3784 3785 return Member->getAnyMember()->getCanonicalDecl(); 3786 } 3787 3788 static void DiagnoseBaseOrMemInitializerOrder( 3789 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3790 ArrayRef<CXXCtorInitializer *> Inits) { 3791 if (Constructor->getDeclContext()->isDependentContext()) 3792 return; 3793 3794 // Don't check initializers order unless the warning is enabled at the 3795 // location of at least one initializer. 3796 bool ShouldCheckOrder = false; 3797 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3798 CXXCtorInitializer *Init = Inits[InitIndex]; 3799 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 3800 Init->getSourceLocation())) { 3801 ShouldCheckOrder = true; 3802 break; 3803 } 3804 } 3805 if (!ShouldCheckOrder) 3806 return; 3807 3808 // Build the list of bases and members in the order that they'll 3809 // actually be initialized. The explicit initializers should be in 3810 // this same order but may be missing things. 3811 SmallVector<const void*, 32> IdealInitKeys; 3812 3813 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3814 3815 // 1. Virtual bases. 3816 for (const auto &VBase : ClassDecl->vbases()) 3817 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3818 3819 // 2. Non-virtual bases. 3820 for (const auto &Base : ClassDecl->bases()) { 3821 if (Base.isVirtual()) 3822 continue; 3823 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3824 } 3825 3826 // 3. Direct fields. 3827 for (auto *Field : ClassDecl->fields()) { 3828 if (Field->isUnnamedBitfield()) 3829 continue; 3830 3831 PopulateKeysForFields(Field, IdealInitKeys); 3832 } 3833 3834 unsigned NumIdealInits = IdealInitKeys.size(); 3835 unsigned IdealIndex = 0; 3836 3837 CXXCtorInitializer *PrevInit = nullptr; 3838 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3839 CXXCtorInitializer *Init = Inits[InitIndex]; 3840 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3841 3842 // Scan forward to try to find this initializer in the idealized 3843 // initializers list. 3844 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3845 if (InitKey == IdealInitKeys[IdealIndex]) 3846 break; 3847 3848 // If we didn't find this initializer, it must be because we 3849 // scanned past it on a previous iteration. That can only 3850 // happen if we're out of order; emit a warning. 3851 if (IdealIndex == NumIdealInits && PrevInit) { 3852 Sema::SemaDiagnosticBuilder D = 3853 SemaRef.Diag(PrevInit->getSourceLocation(), 3854 diag::warn_initializer_out_of_order); 3855 3856 if (PrevInit->isAnyMemberInitializer()) 3857 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3858 else 3859 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3860 3861 if (Init->isAnyMemberInitializer()) 3862 D << 0 << Init->getAnyMember()->getDeclName(); 3863 else 3864 D << 1 << Init->getTypeSourceInfo()->getType(); 3865 3866 // Move back to the initializer's location in the ideal list. 3867 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3868 if (InitKey == IdealInitKeys[IdealIndex]) 3869 break; 3870 3871 assert(IdealIndex != NumIdealInits && 3872 "initializer not found in initializer list"); 3873 } 3874 3875 PrevInit = Init; 3876 } 3877 } 3878 3879 namespace { 3880 bool CheckRedundantInit(Sema &S, 3881 CXXCtorInitializer *Init, 3882 CXXCtorInitializer *&PrevInit) { 3883 if (!PrevInit) { 3884 PrevInit = Init; 3885 return false; 3886 } 3887 3888 if (FieldDecl *Field = Init->getAnyMember()) 3889 S.Diag(Init->getSourceLocation(), 3890 diag::err_multiple_mem_initialization) 3891 << Field->getDeclName() 3892 << Init->getSourceRange(); 3893 else { 3894 const Type *BaseClass = Init->getBaseClass(); 3895 assert(BaseClass && "neither field nor base"); 3896 S.Diag(Init->getSourceLocation(), 3897 diag::err_multiple_base_initialization) 3898 << QualType(BaseClass, 0) 3899 << Init->getSourceRange(); 3900 } 3901 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3902 << 0 << PrevInit->getSourceRange(); 3903 3904 return true; 3905 } 3906 3907 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3908 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3909 3910 bool CheckRedundantUnionInit(Sema &S, 3911 CXXCtorInitializer *Init, 3912 RedundantUnionMap &Unions) { 3913 FieldDecl *Field = Init->getAnyMember(); 3914 RecordDecl *Parent = Field->getParent(); 3915 NamedDecl *Child = Field; 3916 3917 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3918 if (Parent->isUnion()) { 3919 UnionEntry &En = Unions[Parent]; 3920 if (En.first && En.first != Child) { 3921 S.Diag(Init->getSourceLocation(), 3922 diag::err_multiple_mem_union_initialization) 3923 << Field->getDeclName() 3924 << Init->getSourceRange(); 3925 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3926 << 0 << En.second->getSourceRange(); 3927 return true; 3928 } 3929 if (!En.first) { 3930 En.first = Child; 3931 En.second = Init; 3932 } 3933 if (!Parent->isAnonymousStructOrUnion()) 3934 return false; 3935 } 3936 3937 Child = Parent; 3938 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3939 } 3940 3941 return false; 3942 } 3943 } 3944 3945 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3946 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3947 SourceLocation ColonLoc, 3948 ArrayRef<CXXCtorInitializer*> MemInits, 3949 bool AnyErrors) { 3950 if (!ConstructorDecl) 3951 return; 3952 3953 AdjustDeclIfTemplate(ConstructorDecl); 3954 3955 CXXConstructorDecl *Constructor 3956 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3957 3958 if (!Constructor) { 3959 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3960 return; 3961 } 3962 3963 // Mapping for the duplicate initializers check. 3964 // For member initializers, this is keyed with a FieldDecl*. 3965 // For base initializers, this is keyed with a Type*. 3966 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3967 3968 // Mapping for the inconsistent anonymous-union initializers check. 3969 RedundantUnionMap MemberUnions; 3970 3971 bool HadError = false; 3972 for (unsigned i = 0; i < MemInits.size(); i++) { 3973 CXXCtorInitializer *Init = MemInits[i]; 3974 3975 // Set the source order index. 3976 Init->setSourceOrder(i); 3977 3978 if (Init->isAnyMemberInitializer()) { 3979 const void *Key = GetKeyForMember(Context, Init); 3980 if (CheckRedundantInit(*this, Init, Members[Key]) || 3981 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3982 HadError = true; 3983 } else if (Init->isBaseInitializer()) { 3984 const void *Key = GetKeyForMember(Context, Init); 3985 if (CheckRedundantInit(*this, Init, Members[Key])) 3986 HadError = true; 3987 } else { 3988 assert(Init->isDelegatingInitializer()); 3989 // This must be the only initializer 3990 if (MemInits.size() != 1) { 3991 Diag(Init->getSourceLocation(), 3992 diag::err_delegating_initializer_alone) 3993 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3994 // We will treat this as being the only initializer. 3995 } 3996 SetDelegatingInitializer(Constructor, MemInits[i]); 3997 // Return immediately as the initializer is set. 3998 return; 3999 } 4000 } 4001 4002 if (HadError) 4003 return; 4004 4005 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4006 4007 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4008 4009 DiagnoseUninitializedFields(*this, Constructor); 4010 } 4011 4012 void 4013 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4014 CXXRecordDecl *ClassDecl) { 4015 // Ignore dependent contexts. Also ignore unions, since their members never 4016 // have destructors implicitly called. 4017 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4018 return; 4019 4020 // FIXME: all the access-control diagnostics are positioned on the 4021 // field/base declaration. That's probably good; that said, the 4022 // user might reasonably want to know why the destructor is being 4023 // emitted, and we currently don't say. 4024 4025 // Non-static data members. 4026 for (auto *Field : ClassDecl->fields()) { 4027 if (Field->isInvalidDecl()) 4028 continue; 4029 4030 // Don't destroy incomplete or zero-length arrays. 4031 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4032 continue; 4033 4034 QualType FieldType = Context.getBaseElementType(Field->getType()); 4035 4036 const RecordType* RT = FieldType->getAs<RecordType>(); 4037 if (!RT) 4038 continue; 4039 4040 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4041 if (FieldClassDecl->isInvalidDecl()) 4042 continue; 4043 if (FieldClassDecl->hasIrrelevantDestructor()) 4044 continue; 4045 // The destructor for an implicit anonymous union member is never invoked. 4046 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4047 continue; 4048 4049 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4050 assert(Dtor && "No dtor found for FieldClassDecl!"); 4051 CheckDestructorAccess(Field->getLocation(), Dtor, 4052 PDiag(diag::err_access_dtor_field) 4053 << Field->getDeclName() 4054 << FieldType); 4055 4056 MarkFunctionReferenced(Location, Dtor); 4057 DiagnoseUseOfDecl(Dtor, Location); 4058 } 4059 4060 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4061 4062 // Bases. 4063 for (const auto &Base : ClassDecl->bases()) { 4064 // Bases are always records in a well-formed non-dependent class. 4065 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4066 4067 // Remember direct virtual bases. 4068 if (Base.isVirtual()) 4069 DirectVirtualBases.insert(RT); 4070 4071 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4072 // If our base class is invalid, we probably can't get its dtor anyway. 4073 if (BaseClassDecl->isInvalidDecl()) 4074 continue; 4075 if (BaseClassDecl->hasIrrelevantDestructor()) 4076 continue; 4077 4078 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4079 assert(Dtor && "No dtor found for BaseClassDecl!"); 4080 4081 // FIXME: caret should be on the start of the class name 4082 CheckDestructorAccess(Base.getLocStart(), Dtor, 4083 PDiag(diag::err_access_dtor_base) 4084 << Base.getType() 4085 << Base.getSourceRange(), 4086 Context.getTypeDeclType(ClassDecl)); 4087 4088 MarkFunctionReferenced(Location, Dtor); 4089 DiagnoseUseOfDecl(Dtor, Location); 4090 } 4091 4092 // Virtual bases. 4093 for (const auto &VBase : ClassDecl->vbases()) { 4094 // Bases are always records in a well-formed non-dependent class. 4095 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4096 4097 // Ignore direct virtual bases. 4098 if (DirectVirtualBases.count(RT)) 4099 continue; 4100 4101 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4102 // If our base class is invalid, we probably can't get its dtor anyway. 4103 if (BaseClassDecl->isInvalidDecl()) 4104 continue; 4105 if (BaseClassDecl->hasIrrelevantDestructor()) 4106 continue; 4107 4108 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4109 assert(Dtor && "No dtor found for BaseClassDecl!"); 4110 if (CheckDestructorAccess( 4111 ClassDecl->getLocation(), Dtor, 4112 PDiag(diag::err_access_dtor_vbase) 4113 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4114 Context.getTypeDeclType(ClassDecl)) == 4115 AR_accessible) { 4116 CheckDerivedToBaseConversion( 4117 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4118 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4119 SourceRange(), DeclarationName(), nullptr); 4120 } 4121 4122 MarkFunctionReferenced(Location, Dtor); 4123 DiagnoseUseOfDecl(Dtor, Location); 4124 } 4125 } 4126 4127 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4128 if (!CDtorDecl) 4129 return; 4130 4131 if (CXXConstructorDecl *Constructor 4132 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4133 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4134 DiagnoseUninitializedFields(*this, Constructor); 4135 } 4136 } 4137 4138 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4139 unsigned DiagID, AbstractDiagSelID SelID) { 4140 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4141 unsigned DiagID; 4142 AbstractDiagSelID SelID; 4143 4144 public: 4145 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4146 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4147 4148 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4149 if (Suppressed) return; 4150 if (SelID == -1) 4151 S.Diag(Loc, DiagID) << T; 4152 else 4153 S.Diag(Loc, DiagID) << SelID << T; 4154 } 4155 } Diagnoser(DiagID, SelID); 4156 4157 return RequireNonAbstractType(Loc, T, Diagnoser); 4158 } 4159 4160 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4161 TypeDiagnoser &Diagnoser) { 4162 if (!getLangOpts().CPlusPlus) 4163 return false; 4164 4165 if (const ArrayType *AT = Context.getAsArrayType(T)) 4166 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4167 4168 if (const PointerType *PT = T->getAs<PointerType>()) { 4169 // Find the innermost pointer type. 4170 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4171 PT = T; 4172 4173 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4174 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4175 } 4176 4177 const RecordType *RT = T->getAs<RecordType>(); 4178 if (!RT) 4179 return false; 4180 4181 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4182 4183 // We can't answer whether something is abstract until it has a 4184 // definition. If it's currently being defined, we'll walk back 4185 // over all the declarations when we have a full definition. 4186 const CXXRecordDecl *Def = RD->getDefinition(); 4187 if (!Def || Def->isBeingDefined()) 4188 return false; 4189 4190 if (!RD->isAbstract()) 4191 return false; 4192 4193 Diagnoser.diagnose(*this, Loc, T); 4194 DiagnoseAbstractType(RD); 4195 4196 return true; 4197 } 4198 4199 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4200 // Check if we've already emitted the list of pure virtual functions 4201 // for this class. 4202 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4203 return; 4204 4205 // If the diagnostic is suppressed, don't emit the notes. We're only 4206 // going to emit them once, so try to attach them to a diagnostic we're 4207 // actually going to show. 4208 if (Diags.isLastDiagnosticIgnored()) 4209 return; 4210 4211 CXXFinalOverriderMap FinalOverriders; 4212 RD->getFinalOverriders(FinalOverriders); 4213 4214 // Keep a set of seen pure methods so we won't diagnose the same method 4215 // more than once. 4216 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4217 4218 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4219 MEnd = FinalOverriders.end(); 4220 M != MEnd; 4221 ++M) { 4222 for (OverridingMethods::iterator SO = M->second.begin(), 4223 SOEnd = M->second.end(); 4224 SO != SOEnd; ++SO) { 4225 // C++ [class.abstract]p4: 4226 // A class is abstract if it contains or inherits at least one 4227 // pure virtual function for which the final overrider is pure 4228 // virtual. 4229 4230 // 4231 if (SO->second.size() != 1) 4232 continue; 4233 4234 if (!SO->second.front().Method->isPure()) 4235 continue; 4236 4237 if (!SeenPureMethods.insert(SO->second.front().Method)) 4238 continue; 4239 4240 Diag(SO->second.front().Method->getLocation(), 4241 diag::note_pure_virtual_function) 4242 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4243 } 4244 } 4245 4246 if (!PureVirtualClassDiagSet) 4247 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4248 PureVirtualClassDiagSet->insert(RD); 4249 } 4250 4251 namespace { 4252 struct AbstractUsageInfo { 4253 Sema &S; 4254 CXXRecordDecl *Record; 4255 CanQualType AbstractType; 4256 bool Invalid; 4257 4258 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4259 : S(S), Record(Record), 4260 AbstractType(S.Context.getCanonicalType( 4261 S.Context.getTypeDeclType(Record))), 4262 Invalid(false) {} 4263 4264 void DiagnoseAbstractType() { 4265 if (Invalid) return; 4266 S.DiagnoseAbstractType(Record); 4267 Invalid = true; 4268 } 4269 4270 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4271 }; 4272 4273 struct CheckAbstractUsage { 4274 AbstractUsageInfo &Info; 4275 const NamedDecl *Ctx; 4276 4277 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4278 : Info(Info), Ctx(Ctx) {} 4279 4280 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4281 switch (TL.getTypeLocClass()) { 4282 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4283 #define TYPELOC(CLASS, PARENT) \ 4284 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4285 #include "clang/AST/TypeLocNodes.def" 4286 } 4287 } 4288 4289 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4290 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4291 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4292 if (!TL.getParam(I)) 4293 continue; 4294 4295 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4296 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4297 } 4298 } 4299 4300 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4301 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4302 } 4303 4304 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4305 // Visit the type parameters from a permissive context. 4306 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4307 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4308 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4309 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4310 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4311 // TODO: other template argument types? 4312 } 4313 } 4314 4315 // Visit pointee types from a permissive context. 4316 #define CheckPolymorphic(Type) \ 4317 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4318 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4319 } 4320 CheckPolymorphic(PointerTypeLoc) 4321 CheckPolymorphic(ReferenceTypeLoc) 4322 CheckPolymorphic(MemberPointerTypeLoc) 4323 CheckPolymorphic(BlockPointerTypeLoc) 4324 CheckPolymorphic(AtomicTypeLoc) 4325 4326 /// Handle all the types we haven't given a more specific 4327 /// implementation for above. 4328 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4329 // Every other kind of type that we haven't called out already 4330 // that has an inner type is either (1) sugar or (2) contains that 4331 // inner type in some way as a subobject. 4332 if (TypeLoc Next = TL.getNextTypeLoc()) 4333 return Visit(Next, Sel); 4334 4335 // If there's no inner type and we're in a permissive context, 4336 // don't diagnose. 4337 if (Sel == Sema::AbstractNone) return; 4338 4339 // Check whether the type matches the abstract type. 4340 QualType T = TL.getType(); 4341 if (T->isArrayType()) { 4342 Sel = Sema::AbstractArrayType; 4343 T = Info.S.Context.getBaseElementType(T); 4344 } 4345 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4346 if (CT != Info.AbstractType) return; 4347 4348 // It matched; do some magic. 4349 if (Sel == Sema::AbstractArrayType) { 4350 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4351 << T << TL.getSourceRange(); 4352 } else { 4353 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4354 << Sel << T << TL.getSourceRange(); 4355 } 4356 Info.DiagnoseAbstractType(); 4357 } 4358 }; 4359 4360 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4361 Sema::AbstractDiagSelID Sel) { 4362 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4363 } 4364 4365 } 4366 4367 /// Check for invalid uses of an abstract type in a method declaration. 4368 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4369 CXXMethodDecl *MD) { 4370 // No need to do the check on definitions, which require that 4371 // the return/param types be complete. 4372 if (MD->doesThisDeclarationHaveABody()) 4373 return; 4374 4375 // For safety's sake, just ignore it if we don't have type source 4376 // information. This should never happen for non-implicit methods, 4377 // but... 4378 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4379 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4380 } 4381 4382 /// Check for invalid uses of an abstract type within a class definition. 4383 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4384 CXXRecordDecl *RD) { 4385 for (auto *D : RD->decls()) { 4386 if (D->isImplicit()) continue; 4387 4388 // Methods and method templates. 4389 if (isa<CXXMethodDecl>(D)) { 4390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4391 } else if (isa<FunctionTemplateDecl>(D)) { 4392 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4393 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4394 4395 // Fields and static variables. 4396 } else if (isa<FieldDecl>(D)) { 4397 FieldDecl *FD = cast<FieldDecl>(D); 4398 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4399 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4400 } else if (isa<VarDecl>(D)) { 4401 VarDecl *VD = cast<VarDecl>(D); 4402 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4403 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4404 4405 // Nested classes and class templates. 4406 } else if (isa<CXXRecordDecl>(D)) { 4407 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4408 } else if (isa<ClassTemplateDecl>(D)) { 4409 CheckAbstractClassUsage(Info, 4410 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4411 } 4412 } 4413 } 4414 4415 /// \brief Check class-level dllimport/dllexport attribute. 4416 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4417 Attr *ClassAttr = getDLLAttr(Class); 4418 if (!ClassAttr) 4419 return; 4420 4421 bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4422 4423 // Force declaration of implicit members so they can inherit the attribute. 4424 S.ForceDeclarationOfImplicitMembers(Class); 4425 4426 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4427 // seem to be true in practice? 4428 4429 for (Decl *Member : Class->decls()) { 4430 VarDecl *VD = dyn_cast<VarDecl>(Member); 4431 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4432 4433 // Only methods and static fields inherit the attributes. 4434 if (!VD && !MD) 4435 continue; 4436 4437 // Don't process deleted methods. 4438 if (MD && MD->isDeleted()) 4439 continue; 4440 4441 if (MD && MD->isMoveAssignmentOperator() && !ClassExported && 4442 MD->isInlined()) { 4443 // Current MSVC versions don't export the move assignment operators, so 4444 // don't attempt to import them if we have a definition. 4445 continue; 4446 } 4447 4448 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) { 4449 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4450 !MemberAttr->isInherited() && !ClassAttr->isInherited()) { 4451 S.Diag(MemberAttr->getLocation(), 4452 diag::err_attribute_dll_member_of_dll_class) 4453 << MemberAttr << ClassAttr; 4454 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4455 Member->setInvalidDecl(); 4456 continue; 4457 } 4458 } else { 4459 auto *NewAttr = 4460 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4461 NewAttr->setInherited(true); 4462 Member->addAttr(NewAttr); 4463 } 4464 4465 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) { 4466 if (ClassExported) { 4467 if (MD->isUserProvided()) { 4468 // Instantiate non-default methods. 4469 S.MarkFunctionReferenced(Class->getLocation(), MD); 4470 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4471 MD->isCopyAssignmentOperator() || 4472 MD->isMoveAssignmentOperator()) { 4473 // Instantiate non-trivial or explicitly defaulted methods, and the 4474 // copy assignment / move assignment operators. 4475 S.MarkFunctionReferenced(Class->getLocation(), MD); 4476 // Resolve its exception specification; CodeGen needs it. 4477 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4478 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4479 S.ActOnFinishInlineMethodDef(MD); 4480 } 4481 } 4482 } 4483 } 4484 } 4485 4486 /// \brief Perform semantic checks on a class definition that has been 4487 /// completing, introducing implicitly-declared members, checking for 4488 /// abstract types, etc. 4489 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4490 if (!Record) 4491 return; 4492 4493 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4494 AbstractUsageInfo Info(*this, Record); 4495 CheckAbstractClassUsage(Info, Record); 4496 } 4497 4498 // If this is not an aggregate type and has no user-declared constructor, 4499 // complain about any non-static data members of reference or const scalar 4500 // type, since they will never get initializers. 4501 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4502 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4503 !Record->isLambda()) { 4504 bool Complained = false; 4505 for (const auto *F : Record->fields()) { 4506 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4507 continue; 4508 4509 if (F->getType()->isReferenceType() || 4510 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4511 if (!Complained) { 4512 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4513 << Record->getTagKind() << Record; 4514 Complained = true; 4515 } 4516 4517 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4518 << F->getType()->isReferenceType() 4519 << F->getDeclName(); 4520 } 4521 } 4522 } 4523 4524 if (Record->isDynamicClass() && !Record->isDependentType()) 4525 DynamicClasses.push_back(Record); 4526 4527 if (Record->getIdentifier()) { 4528 // C++ [class.mem]p13: 4529 // If T is the name of a class, then each of the following shall have a 4530 // name different from T: 4531 // - every member of every anonymous union that is a member of class T. 4532 // 4533 // C++ [class.mem]p14: 4534 // In addition, if class T has a user-declared constructor (12.1), every 4535 // non-static data member of class T shall have a name different from T. 4536 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4537 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4538 ++I) { 4539 NamedDecl *D = *I; 4540 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4541 isa<IndirectFieldDecl>(D)) { 4542 Diag(D->getLocation(), diag::err_member_name_of_class) 4543 << D->getDeclName(); 4544 break; 4545 } 4546 } 4547 } 4548 4549 // Warn if the class has virtual methods but non-virtual public destructor. 4550 if (Record->isPolymorphic() && !Record->isDependentType()) { 4551 CXXDestructorDecl *dtor = Record->getDestructor(); 4552 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4553 !Record->hasAttr<FinalAttr>()) 4554 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4555 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4556 } 4557 4558 if (Record->isAbstract()) { 4559 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4560 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4561 << FA->isSpelledAsSealed(); 4562 DiagnoseAbstractType(Record); 4563 } 4564 } 4565 4566 if (!Record->isDependentType()) { 4567 for (auto *M : Record->methods()) { 4568 // See if a method overloads virtual methods in a base 4569 // class without overriding any. 4570 if (!M->isStatic()) 4571 DiagnoseHiddenVirtualMethods(M); 4572 4573 // Check whether the explicitly-defaulted special members are valid. 4574 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4575 CheckExplicitlyDefaultedSpecialMember(M); 4576 4577 // For an explicitly defaulted or deleted special member, we defer 4578 // determining triviality until the class is complete. That time is now! 4579 if (!M->isImplicit() && !M->isUserProvided()) { 4580 CXXSpecialMember CSM = getSpecialMember(M); 4581 if (CSM != CXXInvalid) { 4582 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4583 4584 // Inform the class that we've finished declaring this member. 4585 Record->finishedDefaultedOrDeletedMember(M); 4586 } 4587 } 4588 } 4589 } 4590 4591 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4592 // function that is not a constructor declares that member function to be 4593 // const. [...] The class of which that function is a member shall be 4594 // a literal type. 4595 // 4596 // If the class has virtual bases, any constexpr members will already have 4597 // been diagnosed by the checks performed on the member declaration, so 4598 // suppress this (less useful) diagnostic. 4599 // 4600 // We delay this until we know whether an explicitly-defaulted (or deleted) 4601 // destructor for the class is trivial. 4602 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4603 !Record->isLiteral() && !Record->getNumVBases()) { 4604 for (const auto *M : Record->methods()) { 4605 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4606 switch (Record->getTemplateSpecializationKind()) { 4607 case TSK_ImplicitInstantiation: 4608 case TSK_ExplicitInstantiationDeclaration: 4609 case TSK_ExplicitInstantiationDefinition: 4610 // If a template instantiates to a non-literal type, but its members 4611 // instantiate to constexpr functions, the template is technically 4612 // ill-formed, but we allow it for sanity. 4613 continue; 4614 4615 case TSK_Undeclared: 4616 case TSK_ExplicitSpecialization: 4617 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4618 diag::err_constexpr_method_non_literal); 4619 break; 4620 } 4621 4622 // Only produce one error per class. 4623 break; 4624 } 4625 } 4626 } 4627 4628 // ms_struct is a request to use the same ABI rules as MSVC. Check 4629 // whether this class uses any C++ features that are implemented 4630 // completely differently in MSVC, and if so, emit a diagnostic. 4631 // That diagnostic defaults to an error, but we allow projects to 4632 // map it down to a warning (or ignore it). It's a fairly common 4633 // practice among users of the ms_struct pragma to mass-annotate 4634 // headers, sweeping up a bunch of types that the project doesn't 4635 // really rely on MSVC-compatible layout for. We must therefore 4636 // support "ms_struct except for C++ stuff" as a secondary ABI. 4637 if (Record->isMsStruct(Context) && 4638 (Record->isPolymorphic() || Record->getNumBases())) { 4639 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4640 } 4641 4642 // Declare inheriting constructors. We do this eagerly here because: 4643 // - The standard requires an eager diagnostic for conflicting inheriting 4644 // constructors from different classes. 4645 // - The lazy declaration of the other implicit constructors is so as to not 4646 // waste space and performance on classes that are not meant to be 4647 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4648 // have inheriting constructors. 4649 DeclareInheritingConstructors(Record); 4650 4651 checkDLLAttribute(*this, Record); 4652 } 4653 4654 /// Look up the special member function that would be called by a special 4655 /// member function for a subobject of class type. 4656 /// 4657 /// \param Class The class type of the subobject. 4658 /// \param CSM The kind of special member function. 4659 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4660 /// \param ConstRHS True if this is a copy operation with a const object 4661 /// on its RHS, that is, if the argument to the outer special member 4662 /// function is 'const' and this is not a field marked 'mutable'. 4663 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4664 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4665 unsigned FieldQuals, bool ConstRHS) { 4666 unsigned LHSQuals = 0; 4667 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4668 LHSQuals = FieldQuals; 4669 4670 unsigned RHSQuals = FieldQuals; 4671 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4672 RHSQuals = 0; 4673 else if (ConstRHS) 4674 RHSQuals |= Qualifiers::Const; 4675 4676 return S.LookupSpecialMember(Class, CSM, 4677 RHSQuals & Qualifiers::Const, 4678 RHSQuals & Qualifiers::Volatile, 4679 false, 4680 LHSQuals & Qualifiers::Const, 4681 LHSQuals & Qualifiers::Volatile); 4682 } 4683 4684 /// Is the special member function which would be selected to perform the 4685 /// specified operation on the specified class type a constexpr constructor? 4686 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4687 Sema::CXXSpecialMember CSM, 4688 unsigned Quals, bool ConstRHS) { 4689 Sema::SpecialMemberOverloadResult *SMOR = 4690 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4691 if (!SMOR || !SMOR->getMethod()) 4692 // A constructor we wouldn't select can't be "involved in initializing" 4693 // anything. 4694 return true; 4695 return SMOR->getMethod()->isConstexpr(); 4696 } 4697 4698 /// Determine whether the specified special member function would be constexpr 4699 /// if it were implicitly defined. 4700 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4701 Sema::CXXSpecialMember CSM, 4702 bool ConstArg) { 4703 if (!S.getLangOpts().CPlusPlus11) 4704 return false; 4705 4706 // C++11 [dcl.constexpr]p4: 4707 // In the definition of a constexpr constructor [...] 4708 bool Ctor = true; 4709 switch (CSM) { 4710 case Sema::CXXDefaultConstructor: 4711 // Since default constructor lookup is essentially trivial (and cannot 4712 // involve, for instance, template instantiation), we compute whether a 4713 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4714 // 4715 // This is important for performance; we need to know whether the default 4716 // constructor is constexpr to determine whether the type is a literal type. 4717 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4718 4719 case Sema::CXXCopyConstructor: 4720 case Sema::CXXMoveConstructor: 4721 // For copy or move constructors, we need to perform overload resolution. 4722 break; 4723 4724 case Sema::CXXCopyAssignment: 4725 case Sema::CXXMoveAssignment: 4726 if (!S.getLangOpts().CPlusPlus1y) 4727 return false; 4728 // In C++1y, we need to perform overload resolution. 4729 Ctor = false; 4730 break; 4731 4732 case Sema::CXXDestructor: 4733 case Sema::CXXInvalid: 4734 return false; 4735 } 4736 4737 // -- if the class is a non-empty union, or for each non-empty anonymous 4738 // union member of a non-union class, exactly one non-static data member 4739 // shall be initialized; [DR1359] 4740 // 4741 // If we squint, this is guaranteed, since exactly one non-static data member 4742 // will be initialized (if the constructor isn't deleted), we just don't know 4743 // which one. 4744 if (Ctor && ClassDecl->isUnion()) 4745 return true; 4746 4747 // -- the class shall not have any virtual base classes; 4748 if (Ctor && ClassDecl->getNumVBases()) 4749 return false; 4750 4751 // C++1y [class.copy]p26: 4752 // -- [the class] is a literal type, and 4753 if (!Ctor && !ClassDecl->isLiteral()) 4754 return false; 4755 4756 // -- every constructor involved in initializing [...] base class 4757 // sub-objects shall be a constexpr constructor; 4758 // -- the assignment operator selected to copy/move each direct base 4759 // class is a constexpr function, and 4760 for (const auto &B : ClassDecl->bases()) { 4761 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4762 if (!BaseType) continue; 4763 4764 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4765 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4766 return false; 4767 } 4768 4769 // -- every constructor involved in initializing non-static data members 4770 // [...] shall be a constexpr constructor; 4771 // -- every non-static data member and base class sub-object shall be 4772 // initialized 4773 // -- for each non-static data member of X that is of class type (or array 4774 // thereof), the assignment operator selected to copy/move that member is 4775 // a constexpr function 4776 for (const auto *F : ClassDecl->fields()) { 4777 if (F->isInvalidDecl()) 4778 continue; 4779 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4780 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4781 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4782 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4783 BaseType.getCVRQualifiers(), 4784 ConstArg && !F->isMutable())) 4785 return false; 4786 } 4787 } 4788 4789 // All OK, it's constexpr! 4790 return true; 4791 } 4792 4793 static Sema::ImplicitExceptionSpecification 4794 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4795 switch (S.getSpecialMember(MD)) { 4796 case Sema::CXXDefaultConstructor: 4797 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4798 case Sema::CXXCopyConstructor: 4799 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4800 case Sema::CXXCopyAssignment: 4801 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4802 case Sema::CXXMoveConstructor: 4803 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4804 case Sema::CXXMoveAssignment: 4805 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4806 case Sema::CXXDestructor: 4807 return S.ComputeDefaultedDtorExceptionSpec(MD); 4808 case Sema::CXXInvalid: 4809 break; 4810 } 4811 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4812 "only special members have implicit exception specs"); 4813 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4814 } 4815 4816 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4817 CXXMethodDecl *MD) { 4818 FunctionProtoType::ExtProtoInfo EPI; 4819 4820 // Build an exception specification pointing back at this member. 4821 EPI.ExceptionSpec.Type = EST_Unevaluated; 4822 EPI.ExceptionSpec.SourceDecl = MD; 4823 4824 // Set the calling convention to the default for C++ instance methods. 4825 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4826 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4827 /*IsCXXMethod=*/true)); 4828 return EPI; 4829 } 4830 4831 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4832 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4833 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4834 return; 4835 4836 // Evaluate the exception specification. 4837 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 4838 4839 // Update the type of the special member to use it. 4840 UpdateExceptionSpec(MD, ESI); 4841 4842 // A user-provided destructor can be defined outside the class. When that 4843 // happens, be sure to update the exception specification on both 4844 // declarations. 4845 const FunctionProtoType *CanonicalFPT = 4846 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4847 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4848 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 4849 } 4850 4851 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4852 CXXRecordDecl *RD = MD->getParent(); 4853 CXXSpecialMember CSM = getSpecialMember(MD); 4854 4855 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4856 "not an explicitly-defaulted special member"); 4857 4858 // Whether this was the first-declared instance of the constructor. 4859 // This affects whether we implicitly add an exception spec and constexpr. 4860 bool First = MD == MD->getCanonicalDecl(); 4861 4862 bool HadError = false; 4863 4864 // C++11 [dcl.fct.def.default]p1: 4865 // A function that is explicitly defaulted shall 4866 // -- be a special member function (checked elsewhere), 4867 // -- have the same type (except for ref-qualifiers, and except that a 4868 // copy operation can take a non-const reference) as an implicit 4869 // declaration, and 4870 // -- not have default arguments. 4871 unsigned ExpectedParams = 1; 4872 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4873 ExpectedParams = 0; 4874 if (MD->getNumParams() != ExpectedParams) { 4875 // This also checks for default arguments: a copy or move constructor with a 4876 // default argument is classified as a default constructor, and assignment 4877 // operations and destructors can't have default arguments. 4878 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4879 << CSM << MD->getSourceRange(); 4880 HadError = true; 4881 } else if (MD->isVariadic()) { 4882 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4883 << CSM << MD->getSourceRange(); 4884 HadError = true; 4885 } 4886 4887 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4888 4889 bool CanHaveConstParam = false; 4890 if (CSM == CXXCopyConstructor) 4891 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4892 else if (CSM == CXXCopyAssignment) 4893 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4894 4895 QualType ReturnType = Context.VoidTy; 4896 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4897 // Check for return type matching. 4898 ReturnType = Type->getReturnType(); 4899 QualType ExpectedReturnType = 4900 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4901 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4902 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4903 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4904 HadError = true; 4905 } 4906 4907 // A defaulted special member cannot have cv-qualifiers. 4908 if (Type->getTypeQuals()) { 4909 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4910 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4911 HadError = true; 4912 } 4913 } 4914 4915 // Check for parameter type matching. 4916 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4917 bool HasConstParam = false; 4918 if (ExpectedParams && ArgType->isReferenceType()) { 4919 // Argument must be reference to possibly-const T. 4920 QualType ReferentType = ArgType->getPointeeType(); 4921 HasConstParam = ReferentType.isConstQualified(); 4922 4923 if (ReferentType.isVolatileQualified()) { 4924 Diag(MD->getLocation(), 4925 diag::err_defaulted_special_member_volatile_param) << CSM; 4926 HadError = true; 4927 } 4928 4929 if (HasConstParam && !CanHaveConstParam) { 4930 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4931 Diag(MD->getLocation(), 4932 diag::err_defaulted_special_member_copy_const_param) 4933 << (CSM == CXXCopyAssignment); 4934 // FIXME: Explain why this special member can't be const. 4935 } else { 4936 Diag(MD->getLocation(), 4937 diag::err_defaulted_special_member_move_const_param) 4938 << (CSM == CXXMoveAssignment); 4939 } 4940 HadError = true; 4941 } 4942 } else if (ExpectedParams) { 4943 // A copy assignment operator can take its argument by value, but a 4944 // defaulted one cannot. 4945 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4946 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4947 HadError = true; 4948 } 4949 4950 // C++11 [dcl.fct.def.default]p2: 4951 // An explicitly-defaulted function may be declared constexpr only if it 4952 // would have been implicitly declared as constexpr, 4953 // Do not apply this rule to members of class templates, since core issue 1358 4954 // makes such functions always instantiate to constexpr functions. For 4955 // functions which cannot be constexpr (for non-constructors in C++11 and for 4956 // destructors in C++1y), this is checked elsewhere. 4957 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4958 HasConstParam); 4959 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4960 : isa<CXXConstructorDecl>(MD)) && 4961 MD->isConstexpr() && !Constexpr && 4962 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4963 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4964 // FIXME: Explain why the special member can't be constexpr. 4965 HadError = true; 4966 } 4967 4968 // and may have an explicit exception-specification only if it is compatible 4969 // with the exception-specification on the implicit declaration. 4970 if (Type->hasExceptionSpec()) { 4971 // Delay the check if this is the first declaration of the special member, 4972 // since we may not have parsed some necessary in-class initializers yet. 4973 if (First) { 4974 // If the exception specification needs to be instantiated, do so now, 4975 // before we clobber it with an EST_Unevaluated specification below. 4976 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4977 InstantiateExceptionSpec(MD->getLocStart(), MD); 4978 Type = MD->getType()->getAs<FunctionProtoType>(); 4979 } 4980 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4981 } else 4982 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4983 } 4984 4985 // If a function is explicitly defaulted on its first declaration, 4986 if (First) { 4987 // -- it is implicitly considered to be constexpr if the implicit 4988 // definition would be, 4989 MD->setConstexpr(Constexpr); 4990 4991 // -- it is implicitly considered to have the same exception-specification 4992 // as if it had been implicitly declared, 4993 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4994 EPI.ExceptionSpec.Type = EST_Unevaluated; 4995 EPI.ExceptionSpec.SourceDecl = MD; 4996 MD->setType(Context.getFunctionType(ReturnType, 4997 ArrayRef<QualType>(&ArgType, 4998 ExpectedParams), 4999 EPI)); 5000 } 5001 5002 if (ShouldDeleteSpecialMember(MD, CSM)) { 5003 if (First) { 5004 SetDeclDeleted(MD, MD->getLocation()); 5005 } else { 5006 // C++11 [dcl.fct.def.default]p4: 5007 // [For a] user-provided explicitly-defaulted function [...] if such a 5008 // function is implicitly defined as deleted, the program is ill-formed. 5009 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5010 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5011 HadError = true; 5012 } 5013 } 5014 5015 if (HadError) 5016 MD->setInvalidDecl(); 5017 } 5018 5019 /// Check whether the exception specification provided for an 5020 /// explicitly-defaulted special member matches the exception specification 5021 /// that would have been generated for an implicit special member, per 5022 /// C++11 [dcl.fct.def.default]p2. 5023 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5024 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5025 // Compute the implicit exception specification. 5026 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5027 /*IsCXXMethod=*/true); 5028 FunctionProtoType::ExtProtoInfo EPI(CC); 5029 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5030 .getExceptionSpec(); 5031 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5032 Context.getFunctionType(Context.VoidTy, None, EPI)); 5033 5034 // Ensure that it matches. 5035 CheckEquivalentExceptionSpec( 5036 PDiag(diag::err_incorrect_defaulted_exception_spec) 5037 << getSpecialMember(MD), PDiag(), 5038 ImplicitType, SourceLocation(), 5039 SpecifiedType, MD->getLocation()); 5040 } 5041 5042 void Sema::CheckDelayedMemberExceptionSpecs() { 5043 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 5044 2> Checks; 5045 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 5046 5047 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 5048 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5049 5050 // Perform any deferred checking of exception specifications for virtual 5051 // destructors. 5052 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 5053 const CXXDestructorDecl *Dtor = Checks[i].first; 5054 assert(!Dtor->getParent()->isDependentType() && 5055 "Should not ever add destructors of templates into the list."); 5056 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 5057 } 5058 5059 // Check that any explicitly-defaulted methods have exception specifications 5060 // compatible with their implicit exception specifications. 5061 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5062 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5063 Specs[I].second); 5064 } 5065 5066 namespace { 5067 struct SpecialMemberDeletionInfo { 5068 Sema &S; 5069 CXXMethodDecl *MD; 5070 Sema::CXXSpecialMember CSM; 5071 bool Diagnose; 5072 5073 // Properties of the special member, computed for convenience. 5074 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5075 SourceLocation Loc; 5076 5077 bool AllFieldsAreConst; 5078 5079 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5080 Sema::CXXSpecialMember CSM, bool Diagnose) 5081 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5082 IsConstructor(false), IsAssignment(false), IsMove(false), 5083 ConstArg(false), Loc(MD->getLocation()), 5084 AllFieldsAreConst(true) { 5085 switch (CSM) { 5086 case Sema::CXXDefaultConstructor: 5087 case Sema::CXXCopyConstructor: 5088 IsConstructor = true; 5089 break; 5090 case Sema::CXXMoveConstructor: 5091 IsConstructor = true; 5092 IsMove = true; 5093 break; 5094 case Sema::CXXCopyAssignment: 5095 IsAssignment = true; 5096 break; 5097 case Sema::CXXMoveAssignment: 5098 IsAssignment = true; 5099 IsMove = true; 5100 break; 5101 case Sema::CXXDestructor: 5102 break; 5103 case Sema::CXXInvalid: 5104 llvm_unreachable("invalid special member kind"); 5105 } 5106 5107 if (MD->getNumParams()) { 5108 if (const ReferenceType *RT = 5109 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5110 ConstArg = RT->getPointeeType().isConstQualified(); 5111 } 5112 } 5113 5114 bool inUnion() const { return MD->getParent()->isUnion(); } 5115 5116 /// Look up the corresponding special member in the given class. 5117 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5118 unsigned Quals, bool IsMutable) { 5119 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5120 ConstArg && !IsMutable); 5121 } 5122 5123 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5124 5125 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5126 bool shouldDeleteForField(FieldDecl *FD); 5127 bool shouldDeleteForAllConstMembers(); 5128 5129 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5130 unsigned Quals); 5131 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5132 Sema::SpecialMemberOverloadResult *SMOR, 5133 bool IsDtorCallInCtor); 5134 5135 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5136 }; 5137 } 5138 5139 /// Is the given special member inaccessible when used on the given 5140 /// sub-object. 5141 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5142 CXXMethodDecl *target) { 5143 /// If we're operating on a base class, the object type is the 5144 /// type of this special member. 5145 QualType objectTy; 5146 AccessSpecifier access = target->getAccess(); 5147 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5148 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5149 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5150 5151 // If we're operating on a field, the object type is the type of the field. 5152 } else { 5153 objectTy = S.Context.getTypeDeclType(target->getParent()); 5154 } 5155 5156 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5157 } 5158 5159 /// Check whether we should delete a special member due to the implicit 5160 /// definition containing a call to a special member of a subobject. 5161 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5162 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5163 bool IsDtorCallInCtor) { 5164 CXXMethodDecl *Decl = SMOR->getMethod(); 5165 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5166 5167 int DiagKind = -1; 5168 5169 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5170 DiagKind = !Decl ? 0 : 1; 5171 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5172 DiagKind = 2; 5173 else if (!isAccessible(Subobj, Decl)) 5174 DiagKind = 3; 5175 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5176 !Decl->isTrivial()) { 5177 // A member of a union must have a trivial corresponding special member. 5178 // As a weird special case, a destructor call from a union's constructor 5179 // must be accessible and non-deleted, but need not be trivial. Such a 5180 // destructor is never actually called, but is semantically checked as 5181 // if it were. 5182 DiagKind = 4; 5183 } 5184 5185 if (DiagKind == -1) 5186 return false; 5187 5188 if (Diagnose) { 5189 if (Field) { 5190 S.Diag(Field->getLocation(), 5191 diag::note_deleted_special_member_class_subobject) 5192 << CSM << MD->getParent() << /*IsField*/true 5193 << Field << DiagKind << IsDtorCallInCtor; 5194 } else { 5195 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5196 S.Diag(Base->getLocStart(), 5197 diag::note_deleted_special_member_class_subobject) 5198 << CSM << MD->getParent() << /*IsField*/false 5199 << Base->getType() << DiagKind << IsDtorCallInCtor; 5200 } 5201 5202 if (DiagKind == 1) 5203 S.NoteDeletedFunction(Decl); 5204 // FIXME: Explain inaccessibility if DiagKind == 3. 5205 } 5206 5207 return true; 5208 } 5209 5210 /// Check whether we should delete a special member function due to having a 5211 /// direct or virtual base class or non-static data member of class type M. 5212 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5213 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5214 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5215 bool IsMutable = Field && Field->isMutable(); 5216 5217 // C++11 [class.ctor]p5: 5218 // -- any direct or virtual base class, or non-static data member with no 5219 // brace-or-equal-initializer, has class type M (or array thereof) and 5220 // either M has no default constructor or overload resolution as applied 5221 // to M's default constructor results in an ambiguity or in a function 5222 // that is deleted or inaccessible 5223 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5224 // -- a direct or virtual base class B that cannot be copied/moved because 5225 // overload resolution, as applied to B's corresponding special member, 5226 // results in an ambiguity or a function that is deleted or inaccessible 5227 // from the defaulted special member 5228 // C++11 [class.dtor]p5: 5229 // -- any direct or virtual base class [...] has a type with a destructor 5230 // that is deleted or inaccessible 5231 if (!(CSM == Sema::CXXDefaultConstructor && 5232 Field && Field->hasInClassInitializer()) && 5233 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5234 false)) 5235 return true; 5236 5237 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5238 // -- any direct or virtual base class or non-static data member has a 5239 // type with a destructor that is deleted or inaccessible 5240 if (IsConstructor) { 5241 Sema::SpecialMemberOverloadResult *SMOR = 5242 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5243 false, false, false, false, false); 5244 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5245 return true; 5246 } 5247 5248 return false; 5249 } 5250 5251 /// Check whether we should delete a special member function due to the class 5252 /// having a particular direct or virtual base class. 5253 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5254 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5255 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5256 } 5257 5258 /// Check whether we should delete a special member function due to the class 5259 /// having a particular non-static data member. 5260 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5261 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5262 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5263 5264 if (CSM == Sema::CXXDefaultConstructor) { 5265 // For a default constructor, all references must be initialized in-class 5266 // and, if a union, it must have a non-const member. 5267 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5268 if (Diagnose) 5269 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5270 << MD->getParent() << FD << FieldType << /*Reference*/0; 5271 return true; 5272 } 5273 // C++11 [class.ctor]p5: any non-variant non-static data member of 5274 // const-qualified type (or array thereof) with no 5275 // brace-or-equal-initializer does not have a user-provided default 5276 // constructor. 5277 if (!inUnion() && FieldType.isConstQualified() && 5278 !FD->hasInClassInitializer() && 5279 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5280 if (Diagnose) 5281 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5282 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5283 return true; 5284 } 5285 5286 if (inUnion() && !FieldType.isConstQualified()) 5287 AllFieldsAreConst = false; 5288 } else if (CSM == Sema::CXXCopyConstructor) { 5289 // For a copy constructor, data members must not be of rvalue reference 5290 // type. 5291 if (FieldType->isRValueReferenceType()) { 5292 if (Diagnose) 5293 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5294 << MD->getParent() << FD << FieldType; 5295 return true; 5296 } 5297 } else if (IsAssignment) { 5298 // For an assignment operator, data members must not be of reference type. 5299 if (FieldType->isReferenceType()) { 5300 if (Diagnose) 5301 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5302 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5303 return true; 5304 } 5305 if (!FieldRecord && FieldType.isConstQualified()) { 5306 // C++11 [class.copy]p23: 5307 // -- a non-static data member of const non-class type (or array thereof) 5308 if (Diagnose) 5309 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5310 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5311 return true; 5312 } 5313 } 5314 5315 if (FieldRecord) { 5316 // Some additional restrictions exist on the variant members. 5317 if (!inUnion() && FieldRecord->isUnion() && 5318 FieldRecord->isAnonymousStructOrUnion()) { 5319 bool AllVariantFieldsAreConst = true; 5320 5321 // FIXME: Handle anonymous unions declared within anonymous unions. 5322 for (auto *UI : FieldRecord->fields()) { 5323 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5324 5325 if (!UnionFieldType.isConstQualified()) 5326 AllVariantFieldsAreConst = false; 5327 5328 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5329 if (UnionFieldRecord && 5330 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5331 UnionFieldType.getCVRQualifiers())) 5332 return true; 5333 } 5334 5335 // At least one member in each anonymous union must be non-const 5336 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5337 !FieldRecord->field_empty()) { 5338 if (Diagnose) 5339 S.Diag(FieldRecord->getLocation(), 5340 diag::note_deleted_default_ctor_all_const) 5341 << MD->getParent() << /*anonymous union*/1; 5342 return true; 5343 } 5344 5345 // Don't check the implicit member of the anonymous union type. 5346 // This is technically non-conformant, but sanity demands it. 5347 return false; 5348 } 5349 5350 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5351 FieldType.getCVRQualifiers())) 5352 return true; 5353 } 5354 5355 return false; 5356 } 5357 5358 /// C++11 [class.ctor] p5: 5359 /// A defaulted default constructor for a class X is defined as deleted if 5360 /// X is a union and all of its variant members are of const-qualified type. 5361 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5362 // This is a silly definition, because it gives an empty union a deleted 5363 // default constructor. Don't do that. 5364 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5365 !MD->getParent()->field_empty()) { 5366 if (Diagnose) 5367 S.Diag(MD->getParent()->getLocation(), 5368 diag::note_deleted_default_ctor_all_const) 5369 << MD->getParent() << /*not anonymous union*/0; 5370 return true; 5371 } 5372 return false; 5373 } 5374 5375 /// Determine whether a defaulted special member function should be defined as 5376 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5377 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5378 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5379 bool Diagnose) { 5380 if (MD->isInvalidDecl()) 5381 return false; 5382 CXXRecordDecl *RD = MD->getParent(); 5383 assert(!RD->isDependentType() && "do deletion after instantiation"); 5384 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5385 return false; 5386 5387 // C++11 [expr.lambda.prim]p19: 5388 // The closure type associated with a lambda-expression has a 5389 // deleted (8.4.3) default constructor and a deleted copy 5390 // assignment operator. 5391 if (RD->isLambda() && 5392 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5393 if (Diagnose) 5394 Diag(RD->getLocation(), diag::note_lambda_decl); 5395 return true; 5396 } 5397 5398 // For an anonymous struct or union, the copy and assignment special members 5399 // will never be used, so skip the check. For an anonymous union declared at 5400 // namespace scope, the constructor and destructor are used. 5401 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5402 RD->isAnonymousStructOrUnion()) 5403 return false; 5404 5405 // C++11 [class.copy]p7, p18: 5406 // If the class definition declares a move constructor or move assignment 5407 // operator, an implicitly declared copy constructor or copy assignment 5408 // operator is defined as deleted. 5409 if (MD->isImplicit() && 5410 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5411 CXXMethodDecl *UserDeclaredMove = nullptr; 5412 5413 // In Microsoft mode, a user-declared move only causes the deletion of the 5414 // corresponding copy operation, not both copy operations. 5415 if (RD->hasUserDeclaredMoveConstructor() && 5416 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5417 if (!Diagnose) return true; 5418 5419 // Find any user-declared move constructor. 5420 for (auto *I : RD->ctors()) { 5421 if (I->isMoveConstructor()) { 5422 UserDeclaredMove = I; 5423 break; 5424 } 5425 } 5426 assert(UserDeclaredMove); 5427 } else if (RD->hasUserDeclaredMoveAssignment() && 5428 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5429 if (!Diagnose) return true; 5430 5431 // Find any user-declared move assignment operator. 5432 for (auto *I : RD->methods()) { 5433 if (I->isMoveAssignmentOperator()) { 5434 UserDeclaredMove = I; 5435 break; 5436 } 5437 } 5438 assert(UserDeclaredMove); 5439 } 5440 5441 if (UserDeclaredMove) { 5442 Diag(UserDeclaredMove->getLocation(), 5443 diag::note_deleted_copy_user_declared_move) 5444 << (CSM == CXXCopyAssignment) << RD 5445 << UserDeclaredMove->isMoveAssignmentOperator(); 5446 return true; 5447 } 5448 } 5449 5450 // Do access control from the special member function 5451 ContextRAII MethodContext(*this, MD); 5452 5453 // C++11 [class.dtor]p5: 5454 // -- for a virtual destructor, lookup of the non-array deallocation function 5455 // results in an ambiguity or in a function that is deleted or inaccessible 5456 if (CSM == CXXDestructor && MD->isVirtual()) { 5457 FunctionDecl *OperatorDelete = nullptr; 5458 DeclarationName Name = 5459 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5460 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5461 OperatorDelete, false)) { 5462 if (Diagnose) 5463 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5464 return true; 5465 } 5466 } 5467 5468 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5469 5470 for (auto &BI : RD->bases()) 5471 if (!BI.isVirtual() && 5472 SMI.shouldDeleteForBase(&BI)) 5473 return true; 5474 5475 // Per DR1611, do not consider virtual bases of constructors of abstract 5476 // classes, since we are not going to construct them. 5477 if (!RD->isAbstract() || !SMI.IsConstructor) { 5478 for (auto &BI : RD->vbases()) 5479 if (SMI.shouldDeleteForBase(&BI)) 5480 return true; 5481 } 5482 5483 for (auto *FI : RD->fields()) 5484 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5485 SMI.shouldDeleteForField(FI)) 5486 return true; 5487 5488 if (SMI.shouldDeleteForAllConstMembers()) 5489 return true; 5490 5491 return false; 5492 } 5493 5494 /// Perform lookup for a special member of the specified kind, and determine 5495 /// whether it is trivial. If the triviality can be determined without the 5496 /// lookup, skip it. This is intended for use when determining whether a 5497 /// special member of a containing object is trivial, and thus does not ever 5498 /// perform overload resolution for default constructors. 5499 /// 5500 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5501 /// member that was most likely to be intended to be trivial, if any. 5502 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5503 Sema::CXXSpecialMember CSM, unsigned Quals, 5504 bool ConstRHS, CXXMethodDecl **Selected) { 5505 if (Selected) 5506 *Selected = nullptr; 5507 5508 switch (CSM) { 5509 case Sema::CXXInvalid: 5510 llvm_unreachable("not a special member"); 5511 5512 case Sema::CXXDefaultConstructor: 5513 // C++11 [class.ctor]p5: 5514 // A default constructor is trivial if: 5515 // - all the [direct subobjects] have trivial default constructors 5516 // 5517 // Note, no overload resolution is performed in this case. 5518 if (RD->hasTrivialDefaultConstructor()) 5519 return true; 5520 5521 if (Selected) { 5522 // If there's a default constructor which could have been trivial, dig it 5523 // out. Otherwise, if there's any user-provided default constructor, point 5524 // to that as an example of why there's not a trivial one. 5525 CXXConstructorDecl *DefCtor = nullptr; 5526 if (RD->needsImplicitDefaultConstructor()) 5527 S.DeclareImplicitDefaultConstructor(RD); 5528 for (auto *CI : RD->ctors()) { 5529 if (!CI->isDefaultConstructor()) 5530 continue; 5531 DefCtor = CI; 5532 if (!DefCtor->isUserProvided()) 5533 break; 5534 } 5535 5536 *Selected = DefCtor; 5537 } 5538 5539 return false; 5540 5541 case Sema::CXXDestructor: 5542 // C++11 [class.dtor]p5: 5543 // A destructor is trivial if: 5544 // - all the direct [subobjects] have trivial destructors 5545 if (RD->hasTrivialDestructor()) 5546 return true; 5547 5548 if (Selected) { 5549 if (RD->needsImplicitDestructor()) 5550 S.DeclareImplicitDestructor(RD); 5551 *Selected = RD->getDestructor(); 5552 } 5553 5554 return false; 5555 5556 case Sema::CXXCopyConstructor: 5557 // C++11 [class.copy]p12: 5558 // A copy constructor is trivial if: 5559 // - the constructor selected to copy each direct [subobject] is trivial 5560 if (RD->hasTrivialCopyConstructor()) { 5561 if (Quals == Qualifiers::Const) 5562 // We must either select the trivial copy constructor or reach an 5563 // ambiguity; no need to actually perform overload resolution. 5564 return true; 5565 } else if (!Selected) { 5566 return false; 5567 } 5568 // In C++98, we are not supposed to perform overload resolution here, but we 5569 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5570 // cases like B as having a non-trivial copy constructor: 5571 // struct A { template<typename T> A(T&); }; 5572 // struct B { mutable A a; }; 5573 goto NeedOverloadResolution; 5574 5575 case Sema::CXXCopyAssignment: 5576 // C++11 [class.copy]p25: 5577 // A copy assignment operator is trivial if: 5578 // - the assignment operator selected to copy each direct [subobject] is 5579 // trivial 5580 if (RD->hasTrivialCopyAssignment()) { 5581 if (Quals == Qualifiers::Const) 5582 return true; 5583 } else if (!Selected) { 5584 return false; 5585 } 5586 // In C++98, we are not supposed to perform overload resolution here, but we 5587 // treat that as a language defect. 5588 goto NeedOverloadResolution; 5589 5590 case Sema::CXXMoveConstructor: 5591 case Sema::CXXMoveAssignment: 5592 NeedOverloadResolution: 5593 Sema::SpecialMemberOverloadResult *SMOR = 5594 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5595 5596 // The standard doesn't describe how to behave if the lookup is ambiguous. 5597 // We treat it as not making the member non-trivial, just like the standard 5598 // mandates for the default constructor. This should rarely matter, because 5599 // the member will also be deleted. 5600 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5601 return true; 5602 5603 if (!SMOR->getMethod()) { 5604 assert(SMOR->getKind() == 5605 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5606 return false; 5607 } 5608 5609 // We deliberately don't check if we found a deleted special member. We're 5610 // not supposed to! 5611 if (Selected) 5612 *Selected = SMOR->getMethod(); 5613 return SMOR->getMethod()->isTrivial(); 5614 } 5615 5616 llvm_unreachable("unknown special method kind"); 5617 } 5618 5619 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5620 for (auto *CI : RD->ctors()) 5621 if (!CI->isImplicit()) 5622 return CI; 5623 5624 // Look for constructor templates. 5625 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5626 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5627 if (CXXConstructorDecl *CD = 5628 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5629 return CD; 5630 } 5631 5632 return nullptr; 5633 } 5634 5635 /// The kind of subobject we are checking for triviality. The values of this 5636 /// enumeration are used in diagnostics. 5637 enum TrivialSubobjectKind { 5638 /// The subobject is a base class. 5639 TSK_BaseClass, 5640 /// The subobject is a non-static data member. 5641 TSK_Field, 5642 /// The object is actually the complete object. 5643 TSK_CompleteObject 5644 }; 5645 5646 /// Check whether the special member selected for a given type would be trivial. 5647 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5648 QualType SubType, bool ConstRHS, 5649 Sema::CXXSpecialMember CSM, 5650 TrivialSubobjectKind Kind, 5651 bool Diagnose) { 5652 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5653 if (!SubRD) 5654 return true; 5655 5656 CXXMethodDecl *Selected; 5657 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5658 ConstRHS, Diagnose ? &Selected : nullptr)) 5659 return true; 5660 5661 if (Diagnose) { 5662 if (ConstRHS) 5663 SubType.addConst(); 5664 5665 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5666 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5667 << Kind << SubType.getUnqualifiedType(); 5668 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5669 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5670 } else if (!Selected) 5671 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5672 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5673 else if (Selected->isUserProvided()) { 5674 if (Kind == TSK_CompleteObject) 5675 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5676 << Kind << SubType.getUnqualifiedType() << CSM; 5677 else { 5678 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5679 << Kind << SubType.getUnqualifiedType() << CSM; 5680 S.Diag(Selected->getLocation(), diag::note_declared_at); 5681 } 5682 } else { 5683 if (Kind != TSK_CompleteObject) 5684 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5685 << Kind << SubType.getUnqualifiedType() << CSM; 5686 5687 // Explain why the defaulted or deleted special member isn't trivial. 5688 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5689 } 5690 } 5691 5692 return false; 5693 } 5694 5695 /// Check whether the members of a class type allow a special member to be 5696 /// trivial. 5697 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5698 Sema::CXXSpecialMember CSM, 5699 bool ConstArg, bool Diagnose) { 5700 for (const auto *FI : RD->fields()) { 5701 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5702 continue; 5703 5704 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5705 5706 // Pretend anonymous struct or union members are members of this class. 5707 if (FI->isAnonymousStructOrUnion()) { 5708 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5709 CSM, ConstArg, Diagnose)) 5710 return false; 5711 continue; 5712 } 5713 5714 // C++11 [class.ctor]p5: 5715 // A default constructor is trivial if [...] 5716 // -- no non-static data member of its class has a 5717 // brace-or-equal-initializer 5718 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5719 if (Diagnose) 5720 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5721 return false; 5722 } 5723 5724 // Objective C ARC 4.3.5: 5725 // [...] nontrivally ownership-qualified types are [...] not trivially 5726 // default constructible, copy constructible, move constructible, copy 5727 // assignable, move assignable, or destructible [...] 5728 if (S.getLangOpts().ObjCAutoRefCount && 5729 FieldType.hasNonTrivialObjCLifetime()) { 5730 if (Diagnose) 5731 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5732 << RD << FieldType.getObjCLifetime(); 5733 return false; 5734 } 5735 5736 bool ConstRHS = ConstArg && !FI->isMutable(); 5737 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5738 CSM, TSK_Field, Diagnose)) 5739 return false; 5740 } 5741 5742 return true; 5743 } 5744 5745 /// Diagnose why the specified class does not have a trivial special member of 5746 /// the given kind. 5747 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5748 QualType Ty = Context.getRecordType(RD); 5749 5750 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5751 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5752 TSK_CompleteObject, /*Diagnose*/true); 5753 } 5754 5755 /// Determine whether a defaulted or deleted special member function is trivial, 5756 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5757 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5758 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5759 bool Diagnose) { 5760 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5761 5762 CXXRecordDecl *RD = MD->getParent(); 5763 5764 bool ConstArg = false; 5765 5766 // C++11 [class.copy]p12, p25: [DR1593] 5767 // A [special member] is trivial if [...] its parameter-type-list is 5768 // equivalent to the parameter-type-list of an implicit declaration [...] 5769 switch (CSM) { 5770 case CXXDefaultConstructor: 5771 case CXXDestructor: 5772 // Trivial default constructors and destructors cannot have parameters. 5773 break; 5774 5775 case CXXCopyConstructor: 5776 case CXXCopyAssignment: { 5777 // Trivial copy operations always have const, non-volatile parameter types. 5778 ConstArg = true; 5779 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5780 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5781 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5782 if (Diagnose) 5783 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5784 << Param0->getSourceRange() << Param0->getType() 5785 << Context.getLValueReferenceType( 5786 Context.getRecordType(RD).withConst()); 5787 return false; 5788 } 5789 break; 5790 } 5791 5792 case CXXMoveConstructor: 5793 case CXXMoveAssignment: { 5794 // Trivial move operations always have non-cv-qualified parameters. 5795 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5796 const RValueReferenceType *RT = 5797 Param0->getType()->getAs<RValueReferenceType>(); 5798 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5799 if (Diagnose) 5800 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5801 << Param0->getSourceRange() << Param0->getType() 5802 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5803 return false; 5804 } 5805 break; 5806 } 5807 5808 case CXXInvalid: 5809 llvm_unreachable("not a special member"); 5810 } 5811 5812 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5813 if (Diagnose) 5814 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5815 diag::note_nontrivial_default_arg) 5816 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5817 return false; 5818 } 5819 if (MD->isVariadic()) { 5820 if (Diagnose) 5821 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5822 return false; 5823 } 5824 5825 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5826 // A copy/move [constructor or assignment operator] is trivial if 5827 // -- the [member] selected to copy/move each direct base class subobject 5828 // is trivial 5829 // 5830 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5831 // A [default constructor or destructor] is trivial if 5832 // -- all the direct base classes have trivial [default constructors or 5833 // destructors] 5834 for (const auto &BI : RD->bases()) 5835 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5836 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5837 return false; 5838 5839 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5840 // A copy/move [constructor or assignment operator] for a class X is 5841 // trivial if 5842 // -- for each non-static data member of X that is of class type (or array 5843 // thereof), the constructor selected to copy/move that member is 5844 // trivial 5845 // 5846 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5847 // A [default constructor or destructor] is trivial if 5848 // -- for all of the non-static data members of its class that are of class 5849 // type (or array thereof), each such class has a trivial [default 5850 // constructor or destructor] 5851 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5852 return false; 5853 5854 // C++11 [class.dtor]p5: 5855 // A destructor is trivial if [...] 5856 // -- the destructor is not virtual 5857 if (CSM == CXXDestructor && MD->isVirtual()) { 5858 if (Diagnose) 5859 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5860 return false; 5861 } 5862 5863 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5864 // A [special member] for class X is trivial if [...] 5865 // -- class X has no virtual functions and no virtual base classes 5866 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5867 if (!Diagnose) 5868 return false; 5869 5870 if (RD->getNumVBases()) { 5871 // Check for virtual bases. We already know that the corresponding 5872 // member in all bases is trivial, so vbases must all be direct. 5873 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5874 assert(BS.isVirtual()); 5875 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5876 return false; 5877 } 5878 5879 // Must have a virtual method. 5880 for (const auto *MI : RD->methods()) { 5881 if (MI->isVirtual()) { 5882 SourceLocation MLoc = MI->getLocStart(); 5883 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5884 return false; 5885 } 5886 } 5887 5888 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5889 } 5890 5891 // Looks like it's trivial! 5892 return true; 5893 } 5894 5895 /// \brief Data used with FindHiddenVirtualMethod 5896 namespace { 5897 struct FindHiddenVirtualMethodData { 5898 Sema *S; 5899 CXXMethodDecl *Method; 5900 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5901 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5902 }; 5903 } 5904 5905 /// \brief Check whether any most overriden method from MD in Methods 5906 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5907 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5908 if (MD->size_overridden_methods() == 0) 5909 return Methods.count(MD->getCanonicalDecl()); 5910 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5911 E = MD->end_overridden_methods(); 5912 I != E; ++I) 5913 if (CheckMostOverridenMethods(*I, Methods)) 5914 return true; 5915 return false; 5916 } 5917 5918 /// \brief Member lookup function that determines whether a given C++ 5919 /// method overloads virtual methods in a base class without overriding any, 5920 /// to be used with CXXRecordDecl::lookupInBases(). 5921 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5922 CXXBasePath &Path, 5923 void *UserData) { 5924 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5925 5926 FindHiddenVirtualMethodData &Data 5927 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5928 5929 DeclarationName Name = Data.Method->getDeclName(); 5930 assert(Name.getNameKind() == DeclarationName::Identifier); 5931 5932 bool foundSameNameMethod = false; 5933 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5934 for (Path.Decls = BaseRecord->lookup(Name); 5935 !Path.Decls.empty(); 5936 Path.Decls = Path.Decls.slice(1)) { 5937 NamedDecl *D = Path.Decls.front(); 5938 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5939 MD = MD->getCanonicalDecl(); 5940 foundSameNameMethod = true; 5941 // Interested only in hidden virtual methods. 5942 if (!MD->isVirtual()) 5943 continue; 5944 // If the method we are checking overrides a method from its base 5945 // don't warn about the other overloaded methods. Clang deviates from GCC 5946 // by only diagnosing overloads of inherited virtual functions that do not 5947 // override any other virtual functions in the base. GCC's 5948 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 5949 // function from a base class. These cases may be better served by a 5950 // warning (not specific to virtual functions) on call sites when the call 5951 // would select a different function from the base class, were it visible. 5952 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 5953 if (!Data.S->IsOverload(Data.Method, MD, false)) 5954 return true; 5955 // Collect the overload only if its hidden. 5956 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5957 overloadedMethods.push_back(MD); 5958 } 5959 } 5960 5961 if (foundSameNameMethod) 5962 Data.OverloadedMethods.append(overloadedMethods.begin(), 5963 overloadedMethods.end()); 5964 return foundSameNameMethod; 5965 } 5966 5967 /// \brief Add the most overriden methods from MD to Methods 5968 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5969 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5970 if (MD->size_overridden_methods() == 0) 5971 Methods.insert(MD->getCanonicalDecl()); 5972 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5973 E = MD->end_overridden_methods(); 5974 I != E; ++I) 5975 AddMostOverridenMethods(*I, Methods); 5976 } 5977 5978 /// \brief Check if a method overloads virtual methods in a base class without 5979 /// overriding any. 5980 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5981 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5982 if (!MD->getDeclName().isIdentifier()) 5983 return; 5984 5985 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5986 /*bool RecordPaths=*/false, 5987 /*bool DetectVirtual=*/false); 5988 FindHiddenVirtualMethodData Data; 5989 Data.Method = MD; 5990 Data.S = this; 5991 5992 // Keep the base methods that were overriden or introduced in the subclass 5993 // by 'using' in a set. A base method not in this set is hidden. 5994 CXXRecordDecl *DC = MD->getParent(); 5995 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5996 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5997 NamedDecl *ND = *I; 5998 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5999 ND = shad->getTargetDecl(); 6000 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6001 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6002 } 6003 6004 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6005 OverloadedMethods = Data.OverloadedMethods; 6006 } 6007 6008 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6009 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6010 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6011 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6012 PartialDiagnostic PD = PDiag( 6013 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6014 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6015 Diag(overloadedMD->getLocation(), PD); 6016 } 6017 } 6018 6019 /// \brief Diagnose methods which overload virtual methods in a base class 6020 /// without overriding any. 6021 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6022 if (MD->isInvalidDecl()) 6023 return; 6024 6025 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6026 return; 6027 6028 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6029 FindHiddenVirtualMethods(MD, OverloadedMethods); 6030 if (!OverloadedMethods.empty()) { 6031 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6032 << MD << (OverloadedMethods.size() > 1); 6033 6034 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6035 } 6036 } 6037 6038 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6039 Decl *TagDecl, 6040 SourceLocation LBrac, 6041 SourceLocation RBrac, 6042 AttributeList *AttrList) { 6043 if (!TagDecl) 6044 return; 6045 6046 AdjustDeclIfTemplate(TagDecl); 6047 6048 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6049 if (l->getKind() != AttributeList::AT_Visibility) 6050 continue; 6051 l->setInvalid(); 6052 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6053 l->getName(); 6054 } 6055 6056 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6057 // strict aliasing violation! 6058 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6059 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6060 6061 CheckCompletedCXXClass( 6062 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6063 } 6064 6065 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6066 /// special functions, such as the default constructor, copy 6067 /// constructor, or destructor, to the given C++ class (C++ 6068 /// [special]p1). This routine can only be executed just before the 6069 /// definition of the class is complete. 6070 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6071 if (!ClassDecl->hasUserDeclaredConstructor()) 6072 ++ASTContext::NumImplicitDefaultConstructors; 6073 6074 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6075 ++ASTContext::NumImplicitCopyConstructors; 6076 6077 // If the properties or semantics of the copy constructor couldn't be 6078 // determined while the class was being declared, force a declaration 6079 // of it now. 6080 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6081 DeclareImplicitCopyConstructor(ClassDecl); 6082 } 6083 6084 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6085 ++ASTContext::NumImplicitMoveConstructors; 6086 6087 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6088 DeclareImplicitMoveConstructor(ClassDecl); 6089 } 6090 6091 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6092 ++ASTContext::NumImplicitCopyAssignmentOperators; 6093 6094 // If we have a dynamic class, then the copy assignment operator may be 6095 // virtual, so we have to declare it immediately. This ensures that, e.g., 6096 // it shows up in the right place in the vtable and that we diagnose 6097 // problems with the implicit exception specification. 6098 if (ClassDecl->isDynamicClass() || 6099 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6100 DeclareImplicitCopyAssignment(ClassDecl); 6101 } 6102 6103 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6104 ++ASTContext::NumImplicitMoveAssignmentOperators; 6105 6106 // Likewise for the move assignment operator. 6107 if (ClassDecl->isDynamicClass() || 6108 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6109 DeclareImplicitMoveAssignment(ClassDecl); 6110 } 6111 6112 if (!ClassDecl->hasUserDeclaredDestructor()) { 6113 ++ASTContext::NumImplicitDestructors; 6114 6115 // If we have a dynamic class, then the destructor may be virtual, so we 6116 // have to declare the destructor immediately. This ensures that, e.g., it 6117 // shows up in the right place in the vtable and that we diagnose problems 6118 // with the implicit exception specification. 6119 if (ClassDecl->isDynamicClass() || 6120 ClassDecl->needsOverloadResolutionForDestructor()) 6121 DeclareImplicitDestructor(ClassDecl); 6122 } 6123 } 6124 6125 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6126 if (!D) 6127 return 0; 6128 6129 // The order of template parameters is not important here. All names 6130 // get added to the same scope. 6131 SmallVector<TemplateParameterList *, 4> ParameterLists; 6132 6133 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6134 D = TD->getTemplatedDecl(); 6135 6136 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6137 ParameterLists.push_back(PSD->getTemplateParameters()); 6138 6139 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6140 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6141 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6142 6143 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6144 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6145 ParameterLists.push_back(FTD->getTemplateParameters()); 6146 } 6147 } 6148 6149 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6150 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6151 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6152 6153 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6154 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6155 ParameterLists.push_back(CTD->getTemplateParameters()); 6156 } 6157 } 6158 6159 unsigned Count = 0; 6160 for (TemplateParameterList *Params : ParameterLists) { 6161 if (Params->size() > 0) 6162 // Ignore explicit specializations; they don't contribute to the template 6163 // depth. 6164 ++Count; 6165 for (NamedDecl *Param : *Params) { 6166 if (Param->getDeclName()) { 6167 S->AddDecl(Param); 6168 IdResolver.AddDecl(Param); 6169 } 6170 } 6171 } 6172 6173 return Count; 6174 } 6175 6176 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6177 if (!RecordD) return; 6178 AdjustDeclIfTemplate(RecordD); 6179 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6180 PushDeclContext(S, Record); 6181 } 6182 6183 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6184 if (!RecordD) return; 6185 PopDeclContext(); 6186 } 6187 6188 /// This is used to implement the constant expression evaluation part of the 6189 /// attribute enable_if extension. There is nothing in standard C++ which would 6190 /// require reentering parameters. 6191 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6192 if (!Param) 6193 return; 6194 6195 S->AddDecl(Param); 6196 if (Param->getDeclName()) 6197 IdResolver.AddDecl(Param); 6198 } 6199 6200 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6201 /// parsing a top-level (non-nested) C++ class, and we are now 6202 /// parsing those parts of the given Method declaration that could 6203 /// not be parsed earlier (C++ [class.mem]p2), such as default 6204 /// arguments. This action should enter the scope of the given 6205 /// Method declaration as if we had just parsed the qualified method 6206 /// name. However, it should not bring the parameters into scope; 6207 /// that will be performed by ActOnDelayedCXXMethodParameter. 6208 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6209 } 6210 6211 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6212 /// C++ method declaration. We're (re-)introducing the given 6213 /// function parameter into scope for use in parsing later parts of 6214 /// the method declaration. For example, we could see an 6215 /// ActOnParamDefaultArgument event for this parameter. 6216 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6217 if (!ParamD) 6218 return; 6219 6220 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6221 6222 // If this parameter has an unparsed default argument, clear it out 6223 // to make way for the parsed default argument. 6224 if (Param->hasUnparsedDefaultArg()) 6225 Param->setDefaultArg(nullptr); 6226 6227 S->AddDecl(Param); 6228 if (Param->getDeclName()) 6229 IdResolver.AddDecl(Param); 6230 } 6231 6232 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6233 /// processing the delayed method declaration for Method. The method 6234 /// declaration is now considered finished. There may be a separate 6235 /// ActOnStartOfFunctionDef action later (not necessarily 6236 /// immediately!) for this method, if it was also defined inside the 6237 /// class body. 6238 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6239 if (!MethodD) 6240 return; 6241 6242 AdjustDeclIfTemplate(MethodD); 6243 6244 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6245 6246 // Now that we have our default arguments, check the constructor 6247 // again. It could produce additional diagnostics or affect whether 6248 // the class has implicitly-declared destructors, among other 6249 // things. 6250 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6251 CheckConstructor(Constructor); 6252 6253 // Check the default arguments, which we may have added. 6254 if (!Method->isInvalidDecl()) 6255 CheckCXXDefaultArguments(Method); 6256 } 6257 6258 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6259 /// the well-formedness of the constructor declarator @p D with type @p 6260 /// R. If there are any errors in the declarator, this routine will 6261 /// emit diagnostics and set the invalid bit to true. In any case, the type 6262 /// will be updated to reflect a well-formed type for the constructor and 6263 /// returned. 6264 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6265 StorageClass &SC) { 6266 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6267 6268 // C++ [class.ctor]p3: 6269 // A constructor shall not be virtual (10.3) or static (9.4). A 6270 // constructor can be invoked for a const, volatile or const 6271 // volatile object. A constructor shall not be declared const, 6272 // volatile, or const volatile (9.3.2). 6273 if (isVirtual) { 6274 if (!D.isInvalidType()) 6275 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6276 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6277 << SourceRange(D.getIdentifierLoc()); 6278 D.setInvalidType(); 6279 } 6280 if (SC == SC_Static) { 6281 if (!D.isInvalidType()) 6282 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6283 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6284 << SourceRange(D.getIdentifierLoc()); 6285 D.setInvalidType(); 6286 SC = SC_None; 6287 } 6288 6289 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6290 diagnoseIgnoredQualifiers( 6291 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6292 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6293 D.getDeclSpec().getRestrictSpecLoc(), 6294 D.getDeclSpec().getAtomicSpecLoc()); 6295 D.setInvalidType(); 6296 } 6297 6298 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6299 if (FTI.TypeQuals != 0) { 6300 if (FTI.TypeQuals & Qualifiers::Const) 6301 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6302 << "const" << SourceRange(D.getIdentifierLoc()); 6303 if (FTI.TypeQuals & Qualifiers::Volatile) 6304 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6305 << "volatile" << SourceRange(D.getIdentifierLoc()); 6306 if (FTI.TypeQuals & Qualifiers::Restrict) 6307 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6308 << "restrict" << SourceRange(D.getIdentifierLoc()); 6309 D.setInvalidType(); 6310 } 6311 6312 // C++0x [class.ctor]p4: 6313 // A constructor shall not be declared with a ref-qualifier. 6314 if (FTI.hasRefQualifier()) { 6315 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6316 << FTI.RefQualifierIsLValueRef 6317 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6318 D.setInvalidType(); 6319 } 6320 6321 // Rebuild the function type "R" without any type qualifiers (in 6322 // case any of the errors above fired) and with "void" as the 6323 // return type, since constructors don't have return types. 6324 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6325 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6326 return R; 6327 6328 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6329 EPI.TypeQuals = 0; 6330 EPI.RefQualifier = RQ_None; 6331 6332 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6333 } 6334 6335 /// CheckConstructor - Checks a fully-formed constructor for 6336 /// well-formedness, issuing any diagnostics required. Returns true if 6337 /// the constructor declarator is invalid. 6338 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6339 CXXRecordDecl *ClassDecl 6340 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6341 if (!ClassDecl) 6342 return Constructor->setInvalidDecl(); 6343 6344 // C++ [class.copy]p3: 6345 // A declaration of a constructor for a class X is ill-formed if 6346 // its first parameter is of type (optionally cv-qualified) X and 6347 // either there are no other parameters or else all other 6348 // parameters have default arguments. 6349 if (!Constructor->isInvalidDecl() && 6350 ((Constructor->getNumParams() == 1) || 6351 (Constructor->getNumParams() > 1 && 6352 Constructor->getParamDecl(1)->hasDefaultArg())) && 6353 Constructor->getTemplateSpecializationKind() 6354 != TSK_ImplicitInstantiation) { 6355 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6356 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6357 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6358 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6359 const char *ConstRef 6360 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6361 : " const &"; 6362 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6363 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6364 6365 // FIXME: Rather that making the constructor invalid, we should endeavor 6366 // to fix the type. 6367 Constructor->setInvalidDecl(); 6368 } 6369 } 6370 } 6371 6372 /// CheckDestructor - Checks a fully-formed destructor definition for 6373 /// well-formedness, issuing any diagnostics required. Returns true 6374 /// on error. 6375 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6376 CXXRecordDecl *RD = Destructor->getParent(); 6377 6378 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6379 SourceLocation Loc; 6380 6381 if (!Destructor->isImplicit()) 6382 Loc = Destructor->getLocation(); 6383 else 6384 Loc = RD->getLocation(); 6385 6386 // If we have a virtual destructor, look up the deallocation function 6387 FunctionDecl *OperatorDelete = nullptr; 6388 DeclarationName Name = 6389 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6390 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6391 return true; 6392 // If there's no class-specific operator delete, look up the global 6393 // non-array delete. 6394 if (!OperatorDelete) 6395 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6396 6397 MarkFunctionReferenced(Loc, OperatorDelete); 6398 6399 Destructor->setOperatorDelete(OperatorDelete); 6400 } 6401 6402 return false; 6403 } 6404 6405 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6406 /// the well-formednes of the destructor declarator @p D with type @p 6407 /// R. If there are any errors in the declarator, this routine will 6408 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6409 /// will be updated to reflect a well-formed type for the destructor and 6410 /// returned. 6411 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6412 StorageClass& SC) { 6413 // C++ [class.dtor]p1: 6414 // [...] A typedef-name that names a class is a class-name 6415 // (7.1.3); however, a typedef-name that names a class shall not 6416 // be used as the identifier in the declarator for a destructor 6417 // declaration. 6418 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6419 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6420 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6421 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6422 else if (const TemplateSpecializationType *TST = 6423 DeclaratorType->getAs<TemplateSpecializationType>()) 6424 if (TST->isTypeAlias()) 6425 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6426 << DeclaratorType << 1; 6427 6428 // C++ [class.dtor]p2: 6429 // A destructor is used to destroy objects of its class type. A 6430 // destructor takes no parameters, and no return type can be 6431 // specified for it (not even void). The address of a destructor 6432 // shall not be taken. A destructor shall not be static. A 6433 // destructor can be invoked for a const, volatile or const 6434 // volatile object. A destructor shall not be declared const, 6435 // volatile or const volatile (9.3.2). 6436 if (SC == SC_Static) { 6437 if (!D.isInvalidType()) 6438 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6439 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6440 << SourceRange(D.getIdentifierLoc()) 6441 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6442 6443 SC = SC_None; 6444 } 6445 if (!D.isInvalidType()) { 6446 // Destructors don't have return types, but the parser will 6447 // happily parse something like: 6448 // 6449 // class X { 6450 // float ~X(); 6451 // }; 6452 // 6453 // The return type will be eliminated later. 6454 if (D.getDeclSpec().hasTypeSpecifier()) 6455 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6456 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6457 << SourceRange(D.getIdentifierLoc()); 6458 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6459 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6460 SourceLocation(), 6461 D.getDeclSpec().getConstSpecLoc(), 6462 D.getDeclSpec().getVolatileSpecLoc(), 6463 D.getDeclSpec().getRestrictSpecLoc(), 6464 D.getDeclSpec().getAtomicSpecLoc()); 6465 D.setInvalidType(); 6466 } 6467 } 6468 6469 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6470 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6471 if (FTI.TypeQuals & Qualifiers::Const) 6472 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6473 << "const" << SourceRange(D.getIdentifierLoc()); 6474 if (FTI.TypeQuals & Qualifiers::Volatile) 6475 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6476 << "volatile" << SourceRange(D.getIdentifierLoc()); 6477 if (FTI.TypeQuals & Qualifiers::Restrict) 6478 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6479 << "restrict" << SourceRange(D.getIdentifierLoc()); 6480 D.setInvalidType(); 6481 } 6482 6483 // C++0x [class.dtor]p2: 6484 // A destructor shall not be declared with a ref-qualifier. 6485 if (FTI.hasRefQualifier()) { 6486 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6487 << FTI.RefQualifierIsLValueRef 6488 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6489 D.setInvalidType(); 6490 } 6491 6492 // Make sure we don't have any parameters. 6493 if (FTIHasNonVoidParameters(FTI)) { 6494 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6495 6496 // Delete the parameters. 6497 FTI.freeParams(); 6498 D.setInvalidType(); 6499 } 6500 6501 // Make sure the destructor isn't variadic. 6502 if (FTI.isVariadic) { 6503 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6504 D.setInvalidType(); 6505 } 6506 6507 // Rebuild the function type "R" without any type qualifiers or 6508 // parameters (in case any of the errors above fired) and with 6509 // "void" as the return type, since destructors don't have return 6510 // types. 6511 if (!D.isInvalidType()) 6512 return R; 6513 6514 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6515 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6516 EPI.Variadic = false; 6517 EPI.TypeQuals = 0; 6518 EPI.RefQualifier = RQ_None; 6519 return Context.getFunctionType(Context.VoidTy, None, EPI); 6520 } 6521 6522 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6523 /// well-formednes of the conversion function declarator @p D with 6524 /// type @p R. If there are any errors in the declarator, this routine 6525 /// will emit diagnostics and return true. Otherwise, it will return 6526 /// false. Either way, the type @p R will be updated to reflect a 6527 /// well-formed type for the conversion operator. 6528 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6529 StorageClass& SC) { 6530 // C++ [class.conv.fct]p1: 6531 // Neither parameter types nor return type can be specified. The 6532 // type of a conversion function (8.3.5) is "function taking no 6533 // parameter returning conversion-type-id." 6534 if (SC == SC_Static) { 6535 if (!D.isInvalidType()) 6536 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6537 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6538 << D.getName().getSourceRange(); 6539 D.setInvalidType(); 6540 SC = SC_None; 6541 } 6542 6543 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6544 6545 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6546 // Conversion functions don't have return types, but the parser will 6547 // happily parse something like: 6548 // 6549 // class X { 6550 // float operator bool(); 6551 // }; 6552 // 6553 // The return type will be changed later anyway. 6554 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6555 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6556 << SourceRange(D.getIdentifierLoc()); 6557 D.setInvalidType(); 6558 } 6559 6560 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6561 6562 // Make sure we don't have any parameters. 6563 if (Proto->getNumParams() > 0) { 6564 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6565 6566 // Delete the parameters. 6567 D.getFunctionTypeInfo().freeParams(); 6568 D.setInvalidType(); 6569 } else if (Proto->isVariadic()) { 6570 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6571 D.setInvalidType(); 6572 } 6573 6574 // Diagnose "&operator bool()" and other such nonsense. This 6575 // is actually a gcc extension which we don't support. 6576 if (Proto->getReturnType() != ConvType) { 6577 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6578 << Proto->getReturnType(); 6579 D.setInvalidType(); 6580 ConvType = Proto->getReturnType(); 6581 } 6582 6583 // C++ [class.conv.fct]p4: 6584 // The conversion-type-id shall not represent a function type nor 6585 // an array type. 6586 if (ConvType->isArrayType()) { 6587 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6588 ConvType = Context.getPointerType(ConvType); 6589 D.setInvalidType(); 6590 } else if (ConvType->isFunctionType()) { 6591 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6592 ConvType = Context.getPointerType(ConvType); 6593 D.setInvalidType(); 6594 } 6595 6596 // Rebuild the function type "R" without any parameters (in case any 6597 // of the errors above fired) and with the conversion type as the 6598 // return type. 6599 if (D.isInvalidType()) 6600 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6601 6602 // C++0x explicit conversion operators. 6603 if (D.getDeclSpec().isExplicitSpecified()) 6604 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6605 getLangOpts().CPlusPlus11 ? 6606 diag::warn_cxx98_compat_explicit_conversion_functions : 6607 diag::ext_explicit_conversion_functions) 6608 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6609 } 6610 6611 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6612 /// the declaration of the given C++ conversion function. This routine 6613 /// is responsible for recording the conversion function in the C++ 6614 /// class, if possible. 6615 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6616 assert(Conversion && "Expected to receive a conversion function declaration"); 6617 6618 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6619 6620 // Make sure we aren't redeclaring the conversion function. 6621 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6622 6623 // C++ [class.conv.fct]p1: 6624 // [...] A conversion function is never used to convert a 6625 // (possibly cv-qualified) object to the (possibly cv-qualified) 6626 // same object type (or a reference to it), to a (possibly 6627 // cv-qualified) base class of that type (or a reference to it), 6628 // or to (possibly cv-qualified) void. 6629 // FIXME: Suppress this warning if the conversion function ends up being a 6630 // virtual function that overrides a virtual function in a base class. 6631 QualType ClassType 6632 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6633 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6634 ConvType = ConvTypeRef->getPointeeType(); 6635 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6636 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6637 /* Suppress diagnostics for instantiations. */; 6638 else if (ConvType->isRecordType()) { 6639 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6640 if (ConvType == ClassType) 6641 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6642 << ClassType; 6643 else if (IsDerivedFrom(ClassType, ConvType)) 6644 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6645 << ClassType << ConvType; 6646 } else if (ConvType->isVoidType()) { 6647 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6648 << ClassType << ConvType; 6649 } 6650 6651 if (FunctionTemplateDecl *ConversionTemplate 6652 = Conversion->getDescribedFunctionTemplate()) 6653 return ConversionTemplate; 6654 6655 return Conversion; 6656 } 6657 6658 //===----------------------------------------------------------------------===// 6659 // Namespace Handling 6660 //===----------------------------------------------------------------------===// 6661 6662 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6663 /// reopened. 6664 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6665 SourceLocation Loc, 6666 IdentifierInfo *II, bool *IsInline, 6667 NamespaceDecl *PrevNS) { 6668 assert(*IsInline != PrevNS->isInline()); 6669 6670 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6671 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6672 // inline namespaces, with the intention of bringing names into namespace std. 6673 // 6674 // We support this just well enough to get that case working; this is not 6675 // sufficient to support reopening namespaces as inline in general. 6676 if (*IsInline && II && II->getName().startswith("__atomic") && 6677 S.getSourceManager().isInSystemHeader(Loc)) { 6678 // Mark all prior declarations of the namespace as inline. 6679 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6680 NS = NS->getPreviousDecl()) 6681 NS->setInline(*IsInline); 6682 // Patch up the lookup table for the containing namespace. This isn't really 6683 // correct, but it's good enough for this particular case. 6684 for (auto *I : PrevNS->decls()) 6685 if (auto *ND = dyn_cast<NamedDecl>(I)) 6686 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6687 return; 6688 } 6689 6690 if (PrevNS->isInline()) 6691 // The user probably just forgot the 'inline', so suggest that it 6692 // be added back. 6693 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6694 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6695 else 6696 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6697 6698 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6699 *IsInline = PrevNS->isInline(); 6700 } 6701 6702 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6703 /// definition. 6704 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6705 SourceLocation InlineLoc, 6706 SourceLocation NamespaceLoc, 6707 SourceLocation IdentLoc, 6708 IdentifierInfo *II, 6709 SourceLocation LBrace, 6710 AttributeList *AttrList) { 6711 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6712 // For anonymous namespace, take the location of the left brace. 6713 SourceLocation Loc = II ? IdentLoc : LBrace; 6714 bool IsInline = InlineLoc.isValid(); 6715 bool IsInvalid = false; 6716 bool IsStd = false; 6717 bool AddToKnown = false; 6718 Scope *DeclRegionScope = NamespcScope->getParent(); 6719 6720 NamespaceDecl *PrevNS = nullptr; 6721 if (II) { 6722 // C++ [namespace.def]p2: 6723 // The identifier in an original-namespace-definition shall not 6724 // have been previously defined in the declarative region in 6725 // which the original-namespace-definition appears. The 6726 // identifier in an original-namespace-definition is the name of 6727 // the namespace. Subsequently in that declarative region, it is 6728 // treated as an original-namespace-name. 6729 // 6730 // Since namespace names are unique in their scope, and we don't 6731 // look through using directives, just look for any ordinary names. 6732 6733 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6734 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6735 Decl::IDNS_Namespace; 6736 NamedDecl *PrevDecl = nullptr; 6737 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6738 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6739 ++I) { 6740 if ((*I)->getIdentifierNamespace() & IDNS) { 6741 PrevDecl = *I; 6742 break; 6743 } 6744 } 6745 6746 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6747 6748 if (PrevNS) { 6749 // This is an extended namespace definition. 6750 if (IsInline != PrevNS->isInline()) 6751 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6752 &IsInline, PrevNS); 6753 } else if (PrevDecl) { 6754 // This is an invalid name redefinition. 6755 Diag(Loc, diag::err_redefinition_different_kind) 6756 << II; 6757 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6758 IsInvalid = true; 6759 // Continue on to push Namespc as current DeclContext and return it. 6760 } else if (II->isStr("std") && 6761 CurContext->getRedeclContext()->isTranslationUnit()) { 6762 // This is the first "real" definition of the namespace "std", so update 6763 // our cache of the "std" namespace to point at this definition. 6764 PrevNS = getStdNamespace(); 6765 IsStd = true; 6766 AddToKnown = !IsInline; 6767 } else { 6768 // We've seen this namespace for the first time. 6769 AddToKnown = !IsInline; 6770 } 6771 } else { 6772 // Anonymous namespaces. 6773 6774 // Determine whether the parent already has an anonymous namespace. 6775 DeclContext *Parent = CurContext->getRedeclContext(); 6776 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6777 PrevNS = TU->getAnonymousNamespace(); 6778 } else { 6779 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6780 PrevNS = ND->getAnonymousNamespace(); 6781 } 6782 6783 if (PrevNS && IsInline != PrevNS->isInline()) 6784 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6785 &IsInline, PrevNS); 6786 } 6787 6788 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6789 StartLoc, Loc, II, PrevNS); 6790 if (IsInvalid) 6791 Namespc->setInvalidDecl(); 6792 6793 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6794 6795 // FIXME: Should we be merging attributes? 6796 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6797 PushNamespaceVisibilityAttr(Attr, Loc); 6798 6799 if (IsStd) 6800 StdNamespace = Namespc; 6801 if (AddToKnown) 6802 KnownNamespaces[Namespc] = false; 6803 6804 if (II) { 6805 PushOnScopeChains(Namespc, DeclRegionScope); 6806 } else { 6807 // Link the anonymous namespace into its parent. 6808 DeclContext *Parent = CurContext->getRedeclContext(); 6809 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6810 TU->setAnonymousNamespace(Namespc); 6811 } else { 6812 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6813 } 6814 6815 CurContext->addDecl(Namespc); 6816 6817 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6818 // behaves as if it were replaced by 6819 // namespace unique { /* empty body */ } 6820 // using namespace unique; 6821 // namespace unique { namespace-body } 6822 // where all occurrences of 'unique' in a translation unit are 6823 // replaced by the same identifier and this identifier differs 6824 // from all other identifiers in the entire program. 6825 6826 // We just create the namespace with an empty name and then add an 6827 // implicit using declaration, just like the standard suggests. 6828 // 6829 // CodeGen enforces the "universally unique" aspect by giving all 6830 // declarations semantically contained within an anonymous 6831 // namespace internal linkage. 6832 6833 if (!PrevNS) { 6834 UsingDirectiveDecl* UD 6835 = UsingDirectiveDecl::Create(Context, Parent, 6836 /* 'using' */ LBrace, 6837 /* 'namespace' */ SourceLocation(), 6838 /* qualifier */ NestedNameSpecifierLoc(), 6839 /* identifier */ SourceLocation(), 6840 Namespc, 6841 /* Ancestor */ Parent); 6842 UD->setImplicit(); 6843 Parent->addDecl(UD); 6844 } 6845 } 6846 6847 ActOnDocumentableDecl(Namespc); 6848 6849 // Although we could have an invalid decl (i.e. the namespace name is a 6850 // redefinition), push it as current DeclContext and try to continue parsing. 6851 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6852 // for the namespace has the declarations that showed up in that particular 6853 // namespace definition. 6854 PushDeclContext(NamespcScope, Namespc); 6855 return Namespc; 6856 } 6857 6858 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6859 /// is a namespace alias, returns the namespace it points to. 6860 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6861 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6862 return AD->getNamespace(); 6863 return dyn_cast_or_null<NamespaceDecl>(D); 6864 } 6865 6866 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6867 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6868 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6869 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6870 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6871 Namespc->setRBraceLoc(RBrace); 6872 PopDeclContext(); 6873 if (Namespc->hasAttr<VisibilityAttr>()) 6874 PopPragmaVisibility(true, RBrace); 6875 } 6876 6877 CXXRecordDecl *Sema::getStdBadAlloc() const { 6878 return cast_or_null<CXXRecordDecl>( 6879 StdBadAlloc.get(Context.getExternalSource())); 6880 } 6881 6882 NamespaceDecl *Sema::getStdNamespace() const { 6883 return cast_or_null<NamespaceDecl>( 6884 StdNamespace.get(Context.getExternalSource())); 6885 } 6886 6887 /// \brief Retrieve the special "std" namespace, which may require us to 6888 /// implicitly define the namespace. 6889 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6890 if (!StdNamespace) { 6891 // The "std" namespace has not yet been defined, so build one implicitly. 6892 StdNamespace = NamespaceDecl::Create(Context, 6893 Context.getTranslationUnitDecl(), 6894 /*Inline=*/false, 6895 SourceLocation(), SourceLocation(), 6896 &PP.getIdentifierTable().get("std"), 6897 /*PrevDecl=*/nullptr); 6898 getStdNamespace()->setImplicit(true); 6899 } 6900 6901 return getStdNamespace(); 6902 } 6903 6904 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6905 assert(getLangOpts().CPlusPlus && 6906 "Looking for std::initializer_list outside of C++."); 6907 6908 // We're looking for implicit instantiations of 6909 // template <typename E> class std::initializer_list. 6910 6911 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6912 return false; 6913 6914 ClassTemplateDecl *Template = nullptr; 6915 const TemplateArgument *Arguments = nullptr; 6916 6917 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6918 6919 ClassTemplateSpecializationDecl *Specialization = 6920 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6921 if (!Specialization) 6922 return false; 6923 6924 Template = Specialization->getSpecializedTemplate(); 6925 Arguments = Specialization->getTemplateArgs().data(); 6926 } else if (const TemplateSpecializationType *TST = 6927 Ty->getAs<TemplateSpecializationType>()) { 6928 Template = dyn_cast_or_null<ClassTemplateDecl>( 6929 TST->getTemplateName().getAsTemplateDecl()); 6930 Arguments = TST->getArgs(); 6931 } 6932 if (!Template) 6933 return false; 6934 6935 if (!StdInitializerList) { 6936 // Haven't recognized std::initializer_list yet, maybe this is it. 6937 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6938 if (TemplateClass->getIdentifier() != 6939 &PP.getIdentifierTable().get("initializer_list") || 6940 !getStdNamespace()->InEnclosingNamespaceSetOf( 6941 TemplateClass->getDeclContext())) 6942 return false; 6943 // This is a template called std::initializer_list, but is it the right 6944 // template? 6945 TemplateParameterList *Params = Template->getTemplateParameters(); 6946 if (Params->getMinRequiredArguments() != 1) 6947 return false; 6948 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6949 return false; 6950 6951 // It's the right template. 6952 StdInitializerList = Template; 6953 } 6954 6955 if (Template != StdInitializerList) 6956 return false; 6957 6958 // This is an instance of std::initializer_list. Find the argument type. 6959 if (Element) 6960 *Element = Arguments[0].getAsType(); 6961 return true; 6962 } 6963 6964 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6965 NamespaceDecl *Std = S.getStdNamespace(); 6966 if (!Std) { 6967 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6968 return nullptr; 6969 } 6970 6971 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6972 Loc, Sema::LookupOrdinaryName); 6973 if (!S.LookupQualifiedName(Result, Std)) { 6974 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6975 return nullptr; 6976 } 6977 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6978 if (!Template) { 6979 Result.suppressDiagnostics(); 6980 // We found something weird. Complain about the first thing we found. 6981 NamedDecl *Found = *Result.begin(); 6982 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6983 return nullptr; 6984 } 6985 6986 // We found some template called std::initializer_list. Now verify that it's 6987 // correct. 6988 TemplateParameterList *Params = Template->getTemplateParameters(); 6989 if (Params->getMinRequiredArguments() != 1 || 6990 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6991 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6992 return nullptr; 6993 } 6994 6995 return Template; 6996 } 6997 6998 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6999 if (!StdInitializerList) { 7000 StdInitializerList = LookupStdInitializerList(*this, Loc); 7001 if (!StdInitializerList) 7002 return QualType(); 7003 } 7004 7005 TemplateArgumentListInfo Args(Loc, Loc); 7006 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7007 Context.getTrivialTypeSourceInfo(Element, 7008 Loc))); 7009 return Context.getCanonicalType( 7010 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7011 } 7012 7013 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7014 // C++ [dcl.init.list]p2: 7015 // A constructor is an initializer-list constructor if its first parameter 7016 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7017 // std::initializer_list<E> for some type E, and either there are no other 7018 // parameters or else all other parameters have default arguments. 7019 if (Ctor->getNumParams() < 1 || 7020 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7021 return false; 7022 7023 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7024 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7025 ArgType = RT->getPointeeType().getUnqualifiedType(); 7026 7027 return isStdInitializerList(ArgType, nullptr); 7028 } 7029 7030 /// \brief Determine whether a using statement is in a context where it will be 7031 /// apply in all contexts. 7032 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7033 switch (CurContext->getDeclKind()) { 7034 case Decl::TranslationUnit: 7035 return true; 7036 case Decl::LinkageSpec: 7037 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7038 default: 7039 return false; 7040 } 7041 } 7042 7043 namespace { 7044 7045 // Callback to only accept typo corrections that are namespaces. 7046 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7047 public: 7048 bool ValidateCandidate(const TypoCorrection &candidate) override { 7049 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7050 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7051 return false; 7052 } 7053 }; 7054 7055 } 7056 7057 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7058 CXXScopeSpec &SS, 7059 SourceLocation IdentLoc, 7060 IdentifierInfo *Ident) { 7061 NamespaceValidatorCCC Validator; 7062 R.clear(); 7063 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 7064 R.getLookupKind(), Sc, &SS, 7065 Validator, 7066 Sema::CTK_ErrorRecovery)) { 7067 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7068 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7069 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7070 Ident->getName().equals(CorrectedStr); 7071 S.diagnoseTypo(Corrected, 7072 S.PDiag(diag::err_using_directive_member_suggest) 7073 << Ident << DC << DroppedSpecifier << SS.getRange(), 7074 S.PDiag(diag::note_namespace_defined_here)); 7075 } else { 7076 S.diagnoseTypo(Corrected, 7077 S.PDiag(diag::err_using_directive_suggest) << Ident, 7078 S.PDiag(diag::note_namespace_defined_here)); 7079 } 7080 R.addDecl(Corrected.getCorrectionDecl()); 7081 return true; 7082 } 7083 return false; 7084 } 7085 7086 Decl *Sema::ActOnUsingDirective(Scope *S, 7087 SourceLocation UsingLoc, 7088 SourceLocation NamespcLoc, 7089 CXXScopeSpec &SS, 7090 SourceLocation IdentLoc, 7091 IdentifierInfo *NamespcName, 7092 AttributeList *AttrList) { 7093 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7094 assert(NamespcName && "Invalid NamespcName."); 7095 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7096 7097 // This can only happen along a recovery path. 7098 while (S->getFlags() & Scope::TemplateParamScope) 7099 S = S->getParent(); 7100 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7101 7102 UsingDirectiveDecl *UDir = nullptr; 7103 NestedNameSpecifier *Qualifier = nullptr; 7104 if (SS.isSet()) 7105 Qualifier = SS.getScopeRep(); 7106 7107 // Lookup namespace name. 7108 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7109 LookupParsedName(R, S, &SS); 7110 if (R.isAmbiguous()) 7111 return nullptr; 7112 7113 if (R.empty()) { 7114 R.clear(); 7115 // Allow "using namespace std;" or "using namespace ::std;" even if 7116 // "std" hasn't been defined yet, for GCC compatibility. 7117 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7118 NamespcName->isStr("std")) { 7119 Diag(IdentLoc, diag::ext_using_undefined_std); 7120 R.addDecl(getOrCreateStdNamespace()); 7121 R.resolveKind(); 7122 } 7123 // Otherwise, attempt typo correction. 7124 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7125 } 7126 7127 if (!R.empty()) { 7128 NamedDecl *Named = R.getFoundDecl(); 7129 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7130 && "expected namespace decl"); 7131 // C++ [namespace.udir]p1: 7132 // A using-directive specifies that the names in the nominated 7133 // namespace can be used in the scope in which the 7134 // using-directive appears after the using-directive. During 7135 // unqualified name lookup (3.4.1), the names appear as if they 7136 // were declared in the nearest enclosing namespace which 7137 // contains both the using-directive and the nominated 7138 // namespace. [Note: in this context, "contains" means "contains 7139 // directly or indirectly". ] 7140 7141 // Find enclosing context containing both using-directive and 7142 // nominated namespace. 7143 NamespaceDecl *NS = getNamespaceDecl(Named); 7144 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7145 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7146 CommonAncestor = CommonAncestor->getParent(); 7147 7148 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7149 SS.getWithLocInContext(Context), 7150 IdentLoc, Named, CommonAncestor); 7151 7152 if (IsUsingDirectiveInToplevelContext(CurContext) && 7153 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7154 Diag(IdentLoc, diag::warn_using_directive_in_header); 7155 } 7156 7157 PushUsingDirective(S, UDir); 7158 } else { 7159 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7160 } 7161 7162 if (UDir) 7163 ProcessDeclAttributeList(S, UDir, AttrList); 7164 7165 return UDir; 7166 } 7167 7168 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7169 // If the scope has an associated entity and the using directive is at 7170 // namespace or translation unit scope, add the UsingDirectiveDecl into 7171 // its lookup structure so qualified name lookup can find it. 7172 DeclContext *Ctx = S->getEntity(); 7173 if (Ctx && !Ctx->isFunctionOrMethod()) 7174 Ctx->addDecl(UDir); 7175 else 7176 // Otherwise, it is at block scope. The using-directives will affect lookup 7177 // only to the end of the scope. 7178 S->PushUsingDirective(UDir); 7179 } 7180 7181 7182 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7183 AccessSpecifier AS, 7184 bool HasUsingKeyword, 7185 SourceLocation UsingLoc, 7186 CXXScopeSpec &SS, 7187 UnqualifiedId &Name, 7188 AttributeList *AttrList, 7189 bool HasTypenameKeyword, 7190 SourceLocation TypenameLoc) { 7191 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7192 7193 switch (Name.getKind()) { 7194 case UnqualifiedId::IK_ImplicitSelfParam: 7195 case UnqualifiedId::IK_Identifier: 7196 case UnqualifiedId::IK_OperatorFunctionId: 7197 case UnqualifiedId::IK_LiteralOperatorId: 7198 case UnqualifiedId::IK_ConversionFunctionId: 7199 break; 7200 7201 case UnqualifiedId::IK_ConstructorName: 7202 case UnqualifiedId::IK_ConstructorTemplateId: 7203 // C++11 inheriting constructors. 7204 Diag(Name.getLocStart(), 7205 getLangOpts().CPlusPlus11 ? 7206 diag::warn_cxx98_compat_using_decl_constructor : 7207 diag::err_using_decl_constructor) 7208 << SS.getRange(); 7209 7210 if (getLangOpts().CPlusPlus11) break; 7211 7212 return nullptr; 7213 7214 case UnqualifiedId::IK_DestructorName: 7215 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7216 << SS.getRange(); 7217 return nullptr; 7218 7219 case UnqualifiedId::IK_TemplateId: 7220 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7221 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7222 return nullptr; 7223 } 7224 7225 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7226 DeclarationName TargetName = TargetNameInfo.getName(); 7227 if (!TargetName) 7228 return nullptr; 7229 7230 // Warn about access declarations. 7231 if (!HasUsingKeyword) { 7232 Diag(Name.getLocStart(), 7233 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7234 : diag::warn_access_decl_deprecated) 7235 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7236 } 7237 7238 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7239 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7240 return nullptr; 7241 7242 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7243 TargetNameInfo, AttrList, 7244 /* IsInstantiation */ false, 7245 HasTypenameKeyword, TypenameLoc); 7246 if (UD) 7247 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7248 7249 return UD; 7250 } 7251 7252 /// \brief Determine whether a using declaration considers the given 7253 /// declarations as "equivalent", e.g., if they are redeclarations of 7254 /// the same entity or are both typedefs of the same type. 7255 static bool 7256 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7257 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7258 return true; 7259 7260 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7261 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7262 return Context.hasSameType(TD1->getUnderlyingType(), 7263 TD2->getUnderlyingType()); 7264 7265 return false; 7266 } 7267 7268 7269 /// Determines whether to create a using shadow decl for a particular 7270 /// decl, given the set of decls existing prior to this using lookup. 7271 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7272 const LookupResult &Previous, 7273 UsingShadowDecl *&PrevShadow) { 7274 // Diagnose finding a decl which is not from a base class of the 7275 // current class. We do this now because there are cases where this 7276 // function will silently decide not to build a shadow decl, which 7277 // will pre-empt further diagnostics. 7278 // 7279 // We don't need to do this in C++0x because we do the check once on 7280 // the qualifier. 7281 // 7282 // FIXME: diagnose the following if we care enough: 7283 // struct A { int foo; }; 7284 // struct B : A { using A::foo; }; 7285 // template <class T> struct C : A {}; 7286 // template <class T> struct D : C<T> { using B::foo; } // <--- 7287 // This is invalid (during instantiation) in C++03 because B::foo 7288 // resolves to the using decl in B, which is not a base class of D<T>. 7289 // We can't diagnose it immediately because C<T> is an unknown 7290 // specialization. The UsingShadowDecl in D<T> then points directly 7291 // to A::foo, which will look well-formed when we instantiate. 7292 // The right solution is to not collapse the shadow-decl chain. 7293 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7294 DeclContext *OrigDC = Orig->getDeclContext(); 7295 7296 // Handle enums and anonymous structs. 7297 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7298 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7299 while (OrigRec->isAnonymousStructOrUnion()) 7300 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7301 7302 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7303 if (OrigDC == CurContext) { 7304 Diag(Using->getLocation(), 7305 diag::err_using_decl_nested_name_specifier_is_current_class) 7306 << Using->getQualifierLoc().getSourceRange(); 7307 Diag(Orig->getLocation(), diag::note_using_decl_target); 7308 return true; 7309 } 7310 7311 Diag(Using->getQualifierLoc().getBeginLoc(), 7312 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7313 << Using->getQualifier() 7314 << cast<CXXRecordDecl>(CurContext) 7315 << Using->getQualifierLoc().getSourceRange(); 7316 Diag(Orig->getLocation(), diag::note_using_decl_target); 7317 return true; 7318 } 7319 } 7320 7321 if (Previous.empty()) return false; 7322 7323 NamedDecl *Target = Orig; 7324 if (isa<UsingShadowDecl>(Target)) 7325 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7326 7327 // If the target happens to be one of the previous declarations, we 7328 // don't have a conflict. 7329 // 7330 // FIXME: but we might be increasing its access, in which case we 7331 // should redeclare it. 7332 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7333 bool FoundEquivalentDecl = false; 7334 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7335 I != E; ++I) { 7336 NamedDecl *D = (*I)->getUnderlyingDecl(); 7337 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7338 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7339 PrevShadow = Shadow; 7340 FoundEquivalentDecl = true; 7341 } 7342 7343 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7344 } 7345 7346 if (FoundEquivalentDecl) 7347 return false; 7348 7349 if (FunctionDecl *FD = Target->getAsFunction()) { 7350 NamedDecl *OldDecl = nullptr; 7351 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7352 /*IsForUsingDecl*/ true)) { 7353 case Ovl_Overload: 7354 return false; 7355 7356 case Ovl_NonFunction: 7357 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7358 break; 7359 7360 // We found a decl with the exact signature. 7361 case Ovl_Match: 7362 // If we're in a record, we want to hide the target, so we 7363 // return true (without a diagnostic) to tell the caller not to 7364 // build a shadow decl. 7365 if (CurContext->isRecord()) 7366 return true; 7367 7368 // If we're not in a record, this is an error. 7369 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7370 break; 7371 } 7372 7373 Diag(Target->getLocation(), diag::note_using_decl_target); 7374 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7375 return true; 7376 } 7377 7378 // Target is not a function. 7379 7380 if (isa<TagDecl>(Target)) { 7381 // No conflict between a tag and a non-tag. 7382 if (!Tag) return false; 7383 7384 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7385 Diag(Target->getLocation(), diag::note_using_decl_target); 7386 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7387 return true; 7388 } 7389 7390 // No conflict between a tag and a non-tag. 7391 if (!NonTag) return false; 7392 7393 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7394 Diag(Target->getLocation(), diag::note_using_decl_target); 7395 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7396 return true; 7397 } 7398 7399 /// Builds a shadow declaration corresponding to a 'using' declaration. 7400 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7401 UsingDecl *UD, 7402 NamedDecl *Orig, 7403 UsingShadowDecl *PrevDecl) { 7404 7405 // If we resolved to another shadow declaration, just coalesce them. 7406 NamedDecl *Target = Orig; 7407 if (isa<UsingShadowDecl>(Target)) { 7408 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7409 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7410 } 7411 7412 UsingShadowDecl *Shadow 7413 = UsingShadowDecl::Create(Context, CurContext, 7414 UD->getLocation(), UD, Target); 7415 UD->addShadowDecl(Shadow); 7416 7417 Shadow->setAccess(UD->getAccess()); 7418 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7419 Shadow->setInvalidDecl(); 7420 7421 Shadow->setPreviousDecl(PrevDecl); 7422 7423 if (S) 7424 PushOnScopeChains(Shadow, S); 7425 else 7426 CurContext->addDecl(Shadow); 7427 7428 7429 return Shadow; 7430 } 7431 7432 /// Hides a using shadow declaration. This is required by the current 7433 /// using-decl implementation when a resolvable using declaration in a 7434 /// class is followed by a declaration which would hide or override 7435 /// one or more of the using decl's targets; for example: 7436 /// 7437 /// struct Base { void foo(int); }; 7438 /// struct Derived : Base { 7439 /// using Base::foo; 7440 /// void foo(int); 7441 /// }; 7442 /// 7443 /// The governing language is C++03 [namespace.udecl]p12: 7444 /// 7445 /// When a using-declaration brings names from a base class into a 7446 /// derived class scope, member functions in the derived class 7447 /// override and/or hide member functions with the same name and 7448 /// parameter types in a base class (rather than conflicting). 7449 /// 7450 /// There are two ways to implement this: 7451 /// (1) optimistically create shadow decls when they're not hidden 7452 /// by existing declarations, or 7453 /// (2) don't create any shadow decls (or at least don't make them 7454 /// visible) until we've fully parsed/instantiated the class. 7455 /// The problem with (1) is that we might have to retroactively remove 7456 /// a shadow decl, which requires several O(n) operations because the 7457 /// decl structures are (very reasonably) not designed for removal. 7458 /// (2) avoids this but is very fiddly and phase-dependent. 7459 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7460 if (Shadow->getDeclName().getNameKind() == 7461 DeclarationName::CXXConversionFunctionName) 7462 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7463 7464 // Remove it from the DeclContext... 7465 Shadow->getDeclContext()->removeDecl(Shadow); 7466 7467 // ...and the scope, if applicable... 7468 if (S) { 7469 S->RemoveDecl(Shadow); 7470 IdResolver.RemoveDecl(Shadow); 7471 } 7472 7473 // ...and the using decl. 7474 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7475 7476 // TODO: complain somehow if Shadow was used. It shouldn't 7477 // be possible for this to happen, because...? 7478 } 7479 7480 /// Find the base specifier for a base class with the given type. 7481 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7482 QualType DesiredBase, 7483 bool &AnyDependentBases) { 7484 // Check whether the named type is a direct base class. 7485 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7486 for (auto &Base : Derived->bases()) { 7487 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7488 if (CanonicalDesiredBase == BaseType) 7489 return &Base; 7490 if (BaseType->isDependentType()) 7491 AnyDependentBases = true; 7492 } 7493 return nullptr; 7494 } 7495 7496 namespace { 7497 class UsingValidatorCCC : public CorrectionCandidateCallback { 7498 public: 7499 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7500 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7501 : HasTypenameKeyword(HasTypenameKeyword), 7502 IsInstantiation(IsInstantiation), OldNNS(NNS), 7503 RequireMemberOf(RequireMemberOf) {} 7504 7505 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7506 NamedDecl *ND = Candidate.getCorrectionDecl(); 7507 7508 // Keywords are not valid here. 7509 if (!ND || isa<NamespaceDecl>(ND)) 7510 return false; 7511 7512 // Completely unqualified names are invalid for a 'using' declaration. 7513 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7514 return false; 7515 7516 if (RequireMemberOf) { 7517 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7518 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7519 // No-one ever wants a using-declaration to name an injected-class-name 7520 // of a base class, unless they're declaring an inheriting constructor. 7521 ASTContext &Ctx = ND->getASTContext(); 7522 if (!Ctx.getLangOpts().CPlusPlus11) 7523 return false; 7524 QualType FoundType = Ctx.getRecordType(FoundRecord); 7525 7526 // Check that the injected-class-name is named as a member of its own 7527 // type; we don't want to suggest 'using Derived::Base;', since that 7528 // means something else. 7529 NestedNameSpecifier *Specifier = 7530 Candidate.WillReplaceSpecifier() 7531 ? Candidate.getCorrectionSpecifier() 7532 : OldNNS; 7533 if (!Specifier->getAsType() || 7534 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7535 return false; 7536 7537 // Check that this inheriting constructor declaration actually names a 7538 // direct base class of the current class. 7539 bool AnyDependentBases = false; 7540 if (!findDirectBaseWithType(RequireMemberOf, 7541 Ctx.getRecordType(FoundRecord), 7542 AnyDependentBases) && 7543 !AnyDependentBases) 7544 return false; 7545 } else { 7546 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7547 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7548 return false; 7549 7550 // FIXME: Check that the base class member is accessible? 7551 } 7552 } 7553 7554 if (isa<TypeDecl>(ND)) 7555 return HasTypenameKeyword || !IsInstantiation; 7556 7557 return !HasTypenameKeyword; 7558 } 7559 7560 private: 7561 bool HasTypenameKeyword; 7562 bool IsInstantiation; 7563 NestedNameSpecifier *OldNNS; 7564 CXXRecordDecl *RequireMemberOf; 7565 }; 7566 } // end anonymous namespace 7567 7568 /// Builds a using declaration. 7569 /// 7570 /// \param IsInstantiation - Whether this call arises from an 7571 /// instantiation of an unresolved using declaration. We treat 7572 /// the lookup differently for these declarations. 7573 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7574 SourceLocation UsingLoc, 7575 CXXScopeSpec &SS, 7576 DeclarationNameInfo NameInfo, 7577 AttributeList *AttrList, 7578 bool IsInstantiation, 7579 bool HasTypenameKeyword, 7580 SourceLocation TypenameLoc) { 7581 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7582 SourceLocation IdentLoc = NameInfo.getLoc(); 7583 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7584 7585 // FIXME: We ignore attributes for now. 7586 7587 if (SS.isEmpty()) { 7588 Diag(IdentLoc, diag::err_using_requires_qualname); 7589 return nullptr; 7590 } 7591 7592 // Do the redeclaration lookup in the current scope. 7593 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7594 ForRedeclaration); 7595 Previous.setHideTags(false); 7596 if (S) { 7597 LookupName(Previous, S); 7598 7599 // It is really dumb that we have to do this. 7600 LookupResult::Filter F = Previous.makeFilter(); 7601 while (F.hasNext()) { 7602 NamedDecl *D = F.next(); 7603 if (!isDeclInScope(D, CurContext, S)) 7604 F.erase(); 7605 // If we found a local extern declaration that's not ordinarily visible, 7606 // and this declaration is being added to a non-block scope, ignore it. 7607 // We're only checking for scope conflicts here, not also for violations 7608 // of the linkage rules. 7609 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7610 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7611 F.erase(); 7612 } 7613 F.done(); 7614 } else { 7615 assert(IsInstantiation && "no scope in non-instantiation"); 7616 assert(CurContext->isRecord() && "scope not record in instantiation"); 7617 LookupQualifiedName(Previous, CurContext); 7618 } 7619 7620 // Check for invalid redeclarations. 7621 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7622 SS, IdentLoc, Previous)) 7623 return nullptr; 7624 7625 // Check for bad qualifiers. 7626 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7627 return nullptr; 7628 7629 DeclContext *LookupContext = computeDeclContext(SS); 7630 NamedDecl *D; 7631 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7632 if (!LookupContext) { 7633 if (HasTypenameKeyword) { 7634 // FIXME: not all declaration name kinds are legal here 7635 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7636 UsingLoc, TypenameLoc, 7637 QualifierLoc, 7638 IdentLoc, NameInfo.getName()); 7639 } else { 7640 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7641 QualifierLoc, NameInfo); 7642 } 7643 D->setAccess(AS); 7644 CurContext->addDecl(D); 7645 return D; 7646 } 7647 7648 auto Build = [&](bool Invalid) { 7649 UsingDecl *UD = 7650 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7651 HasTypenameKeyword); 7652 UD->setAccess(AS); 7653 CurContext->addDecl(UD); 7654 UD->setInvalidDecl(Invalid); 7655 return UD; 7656 }; 7657 auto BuildInvalid = [&]{ return Build(true); }; 7658 auto BuildValid = [&]{ return Build(false); }; 7659 7660 if (RequireCompleteDeclContext(SS, LookupContext)) 7661 return BuildInvalid(); 7662 7663 // The normal rules do not apply to inheriting constructor declarations. 7664 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7665 UsingDecl *UD = BuildValid(); 7666 CheckInheritingConstructorUsingDecl(UD); 7667 return UD; 7668 } 7669 7670 // Otherwise, look up the target name. 7671 7672 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7673 7674 // Unlike most lookups, we don't always want to hide tag 7675 // declarations: tag names are visible through the using declaration 7676 // even if hidden by ordinary names, *except* in a dependent context 7677 // where it's important for the sanity of two-phase lookup. 7678 if (!IsInstantiation) 7679 R.setHideTags(false); 7680 7681 // For the purposes of this lookup, we have a base object type 7682 // equal to that of the current context. 7683 if (CurContext->isRecord()) { 7684 R.setBaseObjectType( 7685 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7686 } 7687 7688 LookupQualifiedName(R, LookupContext); 7689 7690 // Try to correct typos if possible. 7691 if (R.empty()) { 7692 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7693 dyn_cast<CXXRecordDecl>(CurContext)); 7694 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7695 R.getLookupKind(), S, &SS, CCC, 7696 CTK_ErrorRecovery)){ 7697 // We reject any correction for which ND would be NULL. 7698 NamedDecl *ND = Corrected.getCorrectionDecl(); 7699 7700 // We reject candidates where DroppedSpecifier == true, hence the 7701 // literal '0' below. 7702 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7703 << NameInfo.getName() << LookupContext << 0 7704 << SS.getRange()); 7705 7706 // If we corrected to an inheriting constructor, handle it as one. 7707 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7708 if (RD && RD->isInjectedClassName()) { 7709 // Fix up the information we'll use to build the using declaration. 7710 if (Corrected.WillReplaceSpecifier()) { 7711 NestedNameSpecifierLocBuilder Builder; 7712 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7713 QualifierLoc.getSourceRange()); 7714 QualifierLoc = Builder.getWithLocInContext(Context); 7715 } 7716 7717 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 7718 Context.getCanonicalType(Context.getRecordType(RD)))); 7719 NameInfo.setNamedTypeInfo(nullptr); 7720 7721 // Build it and process it as an inheriting constructor. 7722 UsingDecl *UD = BuildValid(); 7723 CheckInheritingConstructorUsingDecl(UD); 7724 return UD; 7725 } 7726 7727 // FIXME: Pick up all the declarations if we found an overloaded function. 7728 R.setLookupName(Corrected.getCorrection()); 7729 R.addDecl(ND); 7730 } else { 7731 Diag(IdentLoc, diag::err_no_member) 7732 << NameInfo.getName() << LookupContext << SS.getRange(); 7733 return BuildInvalid(); 7734 } 7735 } 7736 7737 if (R.isAmbiguous()) 7738 return BuildInvalid(); 7739 7740 if (HasTypenameKeyword) { 7741 // If we asked for a typename and got a non-type decl, error out. 7742 if (!R.getAsSingle<TypeDecl>()) { 7743 Diag(IdentLoc, diag::err_using_typename_non_type); 7744 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7745 Diag((*I)->getUnderlyingDecl()->getLocation(), 7746 diag::note_using_decl_target); 7747 return BuildInvalid(); 7748 } 7749 } else { 7750 // If we asked for a non-typename and we got a type, error out, 7751 // but only if this is an instantiation of an unresolved using 7752 // decl. Otherwise just silently find the type name. 7753 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7754 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7755 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7756 return BuildInvalid(); 7757 } 7758 } 7759 7760 // C++0x N2914 [namespace.udecl]p6: 7761 // A using-declaration shall not name a namespace. 7762 if (R.getAsSingle<NamespaceDecl>()) { 7763 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7764 << SS.getRange(); 7765 return BuildInvalid(); 7766 } 7767 7768 UsingDecl *UD = BuildValid(); 7769 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7770 UsingShadowDecl *PrevDecl = nullptr; 7771 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7772 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7773 } 7774 7775 return UD; 7776 } 7777 7778 /// Additional checks for a using declaration referring to a constructor name. 7779 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7780 assert(!UD->hasTypename() && "expecting a constructor name"); 7781 7782 const Type *SourceType = UD->getQualifier()->getAsType(); 7783 assert(SourceType && 7784 "Using decl naming constructor doesn't have type in scope spec."); 7785 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7786 7787 // Check whether the named type is a direct base class. 7788 bool AnyDependentBases = false; 7789 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 7790 AnyDependentBases); 7791 if (!Base && !AnyDependentBases) { 7792 Diag(UD->getUsingLoc(), 7793 diag::err_using_decl_constructor_not_in_direct_base) 7794 << UD->getNameInfo().getSourceRange() 7795 << QualType(SourceType, 0) << TargetClass; 7796 UD->setInvalidDecl(); 7797 return true; 7798 } 7799 7800 if (Base) 7801 Base->setInheritConstructors(); 7802 7803 return false; 7804 } 7805 7806 /// Checks that the given using declaration is not an invalid 7807 /// redeclaration. Note that this is checking only for the using decl 7808 /// itself, not for any ill-formedness among the UsingShadowDecls. 7809 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7810 bool HasTypenameKeyword, 7811 const CXXScopeSpec &SS, 7812 SourceLocation NameLoc, 7813 const LookupResult &Prev) { 7814 // C++03 [namespace.udecl]p8: 7815 // C++0x [namespace.udecl]p10: 7816 // A using-declaration is a declaration and can therefore be used 7817 // repeatedly where (and only where) multiple declarations are 7818 // allowed. 7819 // 7820 // That's in non-member contexts. 7821 if (!CurContext->getRedeclContext()->isRecord()) 7822 return false; 7823 7824 NestedNameSpecifier *Qual = SS.getScopeRep(); 7825 7826 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7827 NamedDecl *D = *I; 7828 7829 bool DTypename; 7830 NestedNameSpecifier *DQual; 7831 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7832 DTypename = UD->hasTypename(); 7833 DQual = UD->getQualifier(); 7834 } else if (UnresolvedUsingValueDecl *UD 7835 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7836 DTypename = false; 7837 DQual = UD->getQualifier(); 7838 } else if (UnresolvedUsingTypenameDecl *UD 7839 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7840 DTypename = true; 7841 DQual = UD->getQualifier(); 7842 } else continue; 7843 7844 // using decls differ if one says 'typename' and the other doesn't. 7845 // FIXME: non-dependent using decls? 7846 if (HasTypenameKeyword != DTypename) continue; 7847 7848 // using decls differ if they name different scopes (but note that 7849 // template instantiation can cause this check to trigger when it 7850 // didn't before instantiation). 7851 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7852 Context.getCanonicalNestedNameSpecifier(DQual)) 7853 continue; 7854 7855 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7856 Diag(D->getLocation(), diag::note_using_decl) << 1; 7857 return true; 7858 } 7859 7860 return false; 7861 } 7862 7863 7864 /// Checks that the given nested-name qualifier used in a using decl 7865 /// in the current context is appropriately related to the current 7866 /// scope. If an error is found, diagnoses it and returns true. 7867 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7868 const CXXScopeSpec &SS, 7869 const DeclarationNameInfo &NameInfo, 7870 SourceLocation NameLoc) { 7871 DeclContext *NamedContext = computeDeclContext(SS); 7872 7873 if (!CurContext->isRecord()) { 7874 // C++03 [namespace.udecl]p3: 7875 // C++0x [namespace.udecl]p8: 7876 // A using-declaration for a class member shall be a member-declaration. 7877 7878 // If we weren't able to compute a valid scope, it must be a 7879 // dependent class scope. 7880 if (!NamedContext || NamedContext->isRecord()) { 7881 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7882 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7883 RD = nullptr; 7884 7885 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7886 << SS.getRange(); 7887 7888 // If we have a complete, non-dependent source type, try to suggest a 7889 // way to get the same effect. 7890 if (!RD) 7891 return true; 7892 7893 // Find what this using-declaration was referring to. 7894 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7895 R.setHideTags(false); 7896 R.suppressDiagnostics(); 7897 LookupQualifiedName(R, RD); 7898 7899 if (R.getAsSingle<TypeDecl>()) { 7900 if (getLangOpts().CPlusPlus11) { 7901 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7902 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7903 << 0 // alias declaration 7904 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7905 NameInfo.getName().getAsString() + 7906 " = "); 7907 } else { 7908 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7909 SourceLocation InsertLoc = 7910 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7911 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7912 << 1 // typedef declaration 7913 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7914 << FixItHint::CreateInsertion( 7915 InsertLoc, " " + NameInfo.getName().getAsString()); 7916 } 7917 } else if (R.getAsSingle<VarDecl>()) { 7918 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7919 // repeating the type of the static data member here. 7920 FixItHint FixIt; 7921 if (getLangOpts().CPlusPlus11) { 7922 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7923 FixIt = FixItHint::CreateReplacement( 7924 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7925 } 7926 7927 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7928 << 2 // reference declaration 7929 << FixIt; 7930 } 7931 return true; 7932 } 7933 7934 // Otherwise, everything is known to be fine. 7935 return false; 7936 } 7937 7938 // The current scope is a record. 7939 7940 // If the named context is dependent, we can't decide much. 7941 if (!NamedContext) { 7942 // FIXME: in C++0x, we can diagnose if we can prove that the 7943 // nested-name-specifier does not refer to a base class, which is 7944 // still possible in some cases. 7945 7946 // Otherwise we have to conservatively report that things might be 7947 // okay. 7948 return false; 7949 } 7950 7951 if (!NamedContext->isRecord()) { 7952 // Ideally this would point at the last name in the specifier, 7953 // but we don't have that level of source info. 7954 Diag(SS.getRange().getBegin(), 7955 diag::err_using_decl_nested_name_specifier_is_not_class) 7956 << SS.getScopeRep() << SS.getRange(); 7957 return true; 7958 } 7959 7960 if (!NamedContext->isDependentContext() && 7961 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7962 return true; 7963 7964 if (getLangOpts().CPlusPlus11) { 7965 // C++0x [namespace.udecl]p3: 7966 // In a using-declaration used as a member-declaration, the 7967 // nested-name-specifier shall name a base class of the class 7968 // being defined. 7969 7970 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7971 cast<CXXRecordDecl>(NamedContext))) { 7972 if (CurContext == NamedContext) { 7973 Diag(NameLoc, 7974 diag::err_using_decl_nested_name_specifier_is_current_class) 7975 << SS.getRange(); 7976 return true; 7977 } 7978 7979 Diag(SS.getRange().getBegin(), 7980 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7981 << SS.getScopeRep() 7982 << cast<CXXRecordDecl>(CurContext) 7983 << SS.getRange(); 7984 return true; 7985 } 7986 7987 return false; 7988 } 7989 7990 // C++03 [namespace.udecl]p4: 7991 // A using-declaration used as a member-declaration shall refer 7992 // to a member of a base class of the class being defined [etc.]. 7993 7994 // Salient point: SS doesn't have to name a base class as long as 7995 // lookup only finds members from base classes. Therefore we can 7996 // diagnose here only if we can prove that that can't happen, 7997 // i.e. if the class hierarchies provably don't intersect. 7998 7999 // TODO: it would be nice if "definitely valid" results were cached 8000 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8001 // need to be repeated. 8002 8003 struct UserData { 8004 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8005 8006 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8007 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8008 Data->Bases.insert(Base); 8009 return true; 8010 } 8011 8012 bool hasDependentBases(const CXXRecordDecl *Class) { 8013 return !Class->forallBases(collect, this); 8014 } 8015 8016 /// Returns true if the base is dependent or is one of the 8017 /// accumulated base classes. 8018 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8019 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8020 return !Data->Bases.count(Base); 8021 } 8022 8023 bool mightShareBases(const CXXRecordDecl *Class) { 8024 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8025 } 8026 }; 8027 8028 UserData Data; 8029 8030 // Returns false if we find a dependent base. 8031 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8032 return false; 8033 8034 // Returns false if the class has a dependent base or if it or one 8035 // of its bases is present in the base set of the current context. 8036 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8037 return false; 8038 8039 Diag(SS.getRange().getBegin(), 8040 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8041 << SS.getScopeRep() 8042 << cast<CXXRecordDecl>(CurContext) 8043 << SS.getRange(); 8044 8045 return true; 8046 } 8047 8048 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8049 AccessSpecifier AS, 8050 MultiTemplateParamsArg TemplateParamLists, 8051 SourceLocation UsingLoc, 8052 UnqualifiedId &Name, 8053 AttributeList *AttrList, 8054 TypeResult Type) { 8055 // Skip up to the relevant declaration scope. 8056 while (S->getFlags() & Scope::TemplateParamScope) 8057 S = S->getParent(); 8058 assert((S->getFlags() & Scope::DeclScope) && 8059 "got alias-declaration outside of declaration scope"); 8060 8061 if (Type.isInvalid()) 8062 return nullptr; 8063 8064 bool Invalid = false; 8065 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8066 TypeSourceInfo *TInfo = nullptr; 8067 GetTypeFromParser(Type.get(), &TInfo); 8068 8069 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8070 return nullptr; 8071 8072 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8073 UPPC_DeclarationType)) { 8074 Invalid = true; 8075 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8076 TInfo->getTypeLoc().getBeginLoc()); 8077 } 8078 8079 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8080 LookupName(Previous, S); 8081 8082 // Warn about shadowing the name of a template parameter. 8083 if (Previous.isSingleResult() && 8084 Previous.getFoundDecl()->isTemplateParameter()) { 8085 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8086 Previous.clear(); 8087 } 8088 8089 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8090 "name in alias declaration must be an identifier"); 8091 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8092 Name.StartLocation, 8093 Name.Identifier, TInfo); 8094 8095 NewTD->setAccess(AS); 8096 8097 if (Invalid) 8098 NewTD->setInvalidDecl(); 8099 8100 ProcessDeclAttributeList(S, NewTD, AttrList); 8101 8102 CheckTypedefForVariablyModifiedType(S, NewTD); 8103 Invalid |= NewTD->isInvalidDecl(); 8104 8105 bool Redeclaration = false; 8106 8107 NamedDecl *NewND; 8108 if (TemplateParamLists.size()) { 8109 TypeAliasTemplateDecl *OldDecl = nullptr; 8110 TemplateParameterList *OldTemplateParams = nullptr; 8111 8112 if (TemplateParamLists.size() != 1) { 8113 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8114 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8115 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8116 } 8117 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8118 8119 // Only consider previous declarations in the same scope. 8120 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8121 /*ExplicitInstantiationOrSpecialization*/false); 8122 if (!Previous.empty()) { 8123 Redeclaration = true; 8124 8125 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8126 if (!OldDecl && !Invalid) { 8127 Diag(UsingLoc, diag::err_redefinition_different_kind) 8128 << Name.Identifier; 8129 8130 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8131 if (OldD->getLocation().isValid()) 8132 Diag(OldD->getLocation(), diag::note_previous_definition); 8133 8134 Invalid = true; 8135 } 8136 8137 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8138 if (TemplateParameterListsAreEqual(TemplateParams, 8139 OldDecl->getTemplateParameters(), 8140 /*Complain=*/true, 8141 TPL_TemplateMatch)) 8142 OldTemplateParams = OldDecl->getTemplateParameters(); 8143 else 8144 Invalid = true; 8145 8146 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8147 if (!Invalid && 8148 !Context.hasSameType(OldTD->getUnderlyingType(), 8149 NewTD->getUnderlyingType())) { 8150 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8151 // but we can't reasonably accept it. 8152 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8153 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8154 if (OldTD->getLocation().isValid()) 8155 Diag(OldTD->getLocation(), diag::note_previous_definition); 8156 Invalid = true; 8157 } 8158 } 8159 } 8160 8161 // Merge any previous default template arguments into our parameters, 8162 // and check the parameter list. 8163 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8164 TPC_TypeAliasTemplate)) 8165 return nullptr; 8166 8167 TypeAliasTemplateDecl *NewDecl = 8168 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8169 Name.Identifier, TemplateParams, 8170 NewTD); 8171 8172 NewDecl->setAccess(AS); 8173 8174 if (Invalid) 8175 NewDecl->setInvalidDecl(); 8176 else if (OldDecl) 8177 NewDecl->setPreviousDecl(OldDecl); 8178 8179 NewND = NewDecl; 8180 } else { 8181 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8182 NewND = NewTD; 8183 } 8184 8185 if (!Redeclaration) 8186 PushOnScopeChains(NewND, S); 8187 8188 ActOnDocumentableDecl(NewND); 8189 return NewND; 8190 } 8191 8192 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 8193 SourceLocation NamespaceLoc, 8194 SourceLocation AliasLoc, 8195 IdentifierInfo *Alias, 8196 CXXScopeSpec &SS, 8197 SourceLocation IdentLoc, 8198 IdentifierInfo *Ident) { 8199 8200 // Lookup the namespace name. 8201 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8202 LookupParsedName(R, S, &SS); 8203 8204 // Check if we have a previous declaration with the same name. 8205 NamedDecl *PrevDecl 8206 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8207 ForRedeclaration); 8208 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8209 PrevDecl = nullptr; 8210 8211 if (PrevDecl) { 8212 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8213 // We already have an alias with the same name that points to the same 8214 // namespace, so don't create a new one. 8215 // FIXME: At some point, we'll want to create the (redundant) 8216 // declaration to maintain better source information. 8217 if (!R.isAmbiguous() && !R.empty() && 8218 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 8219 return nullptr; 8220 } 8221 8222 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 8223 diag::err_redefinition_different_kind; 8224 Diag(AliasLoc, DiagID) << Alias; 8225 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8226 return nullptr; 8227 } 8228 8229 if (R.isAmbiguous()) 8230 return nullptr; 8231 8232 if (R.empty()) { 8233 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8234 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8235 return nullptr; 8236 } 8237 } 8238 8239 NamespaceAliasDecl *AliasDecl = 8240 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8241 Alias, SS.getWithLocInContext(Context), 8242 IdentLoc, R.getFoundDecl()); 8243 8244 PushOnScopeChains(AliasDecl, S); 8245 return AliasDecl; 8246 } 8247 8248 Sema::ImplicitExceptionSpecification 8249 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8250 CXXMethodDecl *MD) { 8251 CXXRecordDecl *ClassDecl = MD->getParent(); 8252 8253 // C++ [except.spec]p14: 8254 // An implicitly declared special member function (Clause 12) shall have an 8255 // exception-specification. [...] 8256 ImplicitExceptionSpecification ExceptSpec(*this); 8257 if (ClassDecl->isInvalidDecl()) 8258 return ExceptSpec; 8259 8260 // Direct base-class constructors. 8261 for (const auto &B : ClassDecl->bases()) { 8262 if (B.isVirtual()) // Handled below. 8263 continue; 8264 8265 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8266 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8267 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8268 // If this is a deleted function, add it anyway. This might be conformant 8269 // with the standard. This might not. I'm not sure. It might not matter. 8270 if (Constructor) 8271 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8272 } 8273 } 8274 8275 // Virtual base-class constructors. 8276 for (const auto &B : ClassDecl->vbases()) { 8277 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8278 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8279 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8280 // If this is a deleted function, add it anyway. This might be conformant 8281 // with the standard. This might not. I'm not sure. It might not matter. 8282 if (Constructor) 8283 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8284 } 8285 } 8286 8287 // Field constructors. 8288 for (const auto *F : ClassDecl->fields()) { 8289 if (F->hasInClassInitializer()) { 8290 if (Expr *E = F->getInClassInitializer()) 8291 ExceptSpec.CalledExpr(E); 8292 else if (!F->isInvalidDecl()) 8293 // DR1351: 8294 // If the brace-or-equal-initializer of a non-static data member 8295 // invokes a defaulted default constructor of its class or of an 8296 // enclosing class in a potentially evaluated subexpression, the 8297 // program is ill-formed. 8298 // 8299 // This resolution is unworkable: the exception specification of the 8300 // default constructor can be needed in an unevaluated context, in 8301 // particular, in the operand of a noexcept-expression, and we can be 8302 // unable to compute an exception specification for an enclosed class. 8303 // 8304 // We do not allow an in-class initializer to require the evaluation 8305 // of the exception specification for any in-class initializer whose 8306 // definition is not lexically complete. 8307 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8308 } else if (const RecordType *RecordTy 8309 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8310 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8311 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8312 // If this is a deleted function, add it anyway. This might be conformant 8313 // with the standard. This might not. I'm not sure. It might not matter. 8314 // In particular, the problem is that this function never gets called. It 8315 // might just be ill-formed because this function attempts to refer to 8316 // a deleted function here. 8317 if (Constructor) 8318 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8319 } 8320 } 8321 8322 return ExceptSpec; 8323 } 8324 8325 Sema::ImplicitExceptionSpecification 8326 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8327 CXXRecordDecl *ClassDecl = CD->getParent(); 8328 8329 // C++ [except.spec]p14: 8330 // An inheriting constructor [...] shall have an exception-specification. [...] 8331 ImplicitExceptionSpecification ExceptSpec(*this); 8332 if (ClassDecl->isInvalidDecl()) 8333 return ExceptSpec; 8334 8335 // Inherited constructor. 8336 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8337 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8338 // FIXME: Copying or moving the parameters could add extra exceptions to the 8339 // set, as could the default arguments for the inherited constructor. This 8340 // will be addressed when we implement the resolution of core issue 1351. 8341 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8342 8343 // Direct base-class constructors. 8344 for (const auto &B : ClassDecl->bases()) { 8345 if (B.isVirtual()) // Handled below. 8346 continue; 8347 8348 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8349 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8350 if (BaseClassDecl == InheritedDecl) 8351 continue; 8352 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8353 if (Constructor) 8354 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8355 } 8356 } 8357 8358 // Virtual base-class constructors. 8359 for (const auto &B : ClassDecl->vbases()) { 8360 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8362 if (BaseClassDecl == InheritedDecl) 8363 continue; 8364 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8365 if (Constructor) 8366 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8367 } 8368 } 8369 8370 // Field constructors. 8371 for (const auto *F : ClassDecl->fields()) { 8372 if (F->hasInClassInitializer()) { 8373 if (Expr *E = F->getInClassInitializer()) 8374 ExceptSpec.CalledExpr(E); 8375 else if (!F->isInvalidDecl()) 8376 Diag(CD->getLocation(), 8377 diag::err_in_class_initializer_references_def_ctor) << CD; 8378 } else if (const RecordType *RecordTy 8379 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8380 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8381 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8382 if (Constructor) 8383 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8384 } 8385 } 8386 8387 return ExceptSpec; 8388 } 8389 8390 namespace { 8391 /// RAII object to register a special member as being currently declared. 8392 struct DeclaringSpecialMember { 8393 Sema &S; 8394 Sema::SpecialMemberDecl D; 8395 bool WasAlreadyBeingDeclared; 8396 8397 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8398 : S(S), D(RD, CSM) { 8399 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8400 if (WasAlreadyBeingDeclared) 8401 // This almost never happens, but if it does, ensure that our cache 8402 // doesn't contain a stale result. 8403 S.SpecialMemberCache.clear(); 8404 8405 // FIXME: Register a note to be produced if we encounter an error while 8406 // declaring the special member. 8407 } 8408 ~DeclaringSpecialMember() { 8409 if (!WasAlreadyBeingDeclared) 8410 S.SpecialMembersBeingDeclared.erase(D); 8411 } 8412 8413 /// \brief Are we already trying to declare this special member? 8414 bool isAlreadyBeingDeclared() const { 8415 return WasAlreadyBeingDeclared; 8416 } 8417 }; 8418 } 8419 8420 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8421 CXXRecordDecl *ClassDecl) { 8422 // C++ [class.ctor]p5: 8423 // A default constructor for a class X is a constructor of class X 8424 // that can be called without an argument. If there is no 8425 // user-declared constructor for class X, a default constructor is 8426 // implicitly declared. An implicitly-declared default constructor 8427 // is an inline public member of its class. 8428 assert(ClassDecl->needsImplicitDefaultConstructor() && 8429 "Should not build implicit default constructor!"); 8430 8431 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8432 if (DSM.isAlreadyBeingDeclared()) 8433 return nullptr; 8434 8435 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8436 CXXDefaultConstructor, 8437 false); 8438 8439 // Create the actual constructor declaration. 8440 CanQualType ClassType 8441 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8442 SourceLocation ClassLoc = ClassDecl->getLocation(); 8443 DeclarationName Name 8444 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8445 DeclarationNameInfo NameInfo(Name, ClassLoc); 8446 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8447 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8448 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8449 /*isImplicitlyDeclared=*/true, Constexpr); 8450 DefaultCon->setAccess(AS_public); 8451 DefaultCon->setDefaulted(); 8452 DefaultCon->setImplicit(); 8453 8454 // Build an exception specification pointing back at this constructor. 8455 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8456 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8457 8458 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8459 // constructors is easy to compute. 8460 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8461 8462 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8463 SetDeclDeleted(DefaultCon, ClassLoc); 8464 8465 // Note that we have declared this constructor. 8466 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8467 8468 if (Scope *S = getScopeForContext(ClassDecl)) 8469 PushOnScopeChains(DefaultCon, S, false); 8470 ClassDecl->addDecl(DefaultCon); 8471 8472 return DefaultCon; 8473 } 8474 8475 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8476 CXXConstructorDecl *Constructor) { 8477 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8478 !Constructor->doesThisDeclarationHaveABody() && 8479 !Constructor->isDeleted()) && 8480 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8481 8482 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8483 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8484 8485 SynthesizedFunctionScope Scope(*this, Constructor); 8486 DiagnosticErrorTrap Trap(Diags); 8487 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8488 Trap.hasErrorOccurred()) { 8489 Diag(CurrentLocation, diag::note_member_synthesized_at) 8490 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8491 Constructor->setInvalidDecl(); 8492 return; 8493 } 8494 8495 SourceLocation Loc = Constructor->getLocEnd().isValid() 8496 ? Constructor->getLocEnd() 8497 : Constructor->getLocation(); 8498 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8499 8500 Constructor->markUsed(Context); 8501 MarkVTableUsed(CurrentLocation, ClassDecl); 8502 8503 if (ASTMutationListener *L = getASTMutationListener()) { 8504 L->CompletedImplicitDefinition(Constructor); 8505 } 8506 8507 DiagnoseUninitializedFields(*this, Constructor); 8508 } 8509 8510 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8511 // Perform any delayed checks on exception specifications. 8512 CheckDelayedMemberExceptionSpecs(); 8513 } 8514 8515 namespace { 8516 /// Information on inheriting constructors to declare. 8517 class InheritingConstructorInfo { 8518 public: 8519 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8520 : SemaRef(SemaRef), Derived(Derived) { 8521 // Mark the constructors that we already have in the derived class. 8522 // 8523 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8524 // unless there is a user-declared constructor with the same signature in 8525 // the class where the using-declaration appears. 8526 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8527 } 8528 8529 void inheritAll(CXXRecordDecl *RD) { 8530 visitAll(RD, &InheritingConstructorInfo::inherit); 8531 } 8532 8533 private: 8534 /// Information about an inheriting constructor. 8535 struct InheritingConstructor { 8536 InheritingConstructor() 8537 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8538 8539 /// If \c true, a constructor with this signature is already declared 8540 /// in the derived class. 8541 bool DeclaredInDerived; 8542 8543 /// The constructor which is inherited. 8544 const CXXConstructorDecl *BaseCtor; 8545 8546 /// The derived constructor we declared. 8547 CXXConstructorDecl *DerivedCtor; 8548 }; 8549 8550 /// Inheriting constructors with a given canonical type. There can be at 8551 /// most one such non-template constructor, and any number of templated 8552 /// constructors. 8553 struct InheritingConstructorsForType { 8554 InheritingConstructor NonTemplate; 8555 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8556 Templates; 8557 8558 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8559 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8560 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8561 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8562 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8563 false, S.TPL_TemplateMatch)) 8564 return Templates[I].second; 8565 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8566 return Templates.back().second; 8567 } 8568 8569 return NonTemplate; 8570 } 8571 }; 8572 8573 /// Get or create the inheriting constructor record for a constructor. 8574 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8575 QualType CtorType) { 8576 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8577 .getEntry(SemaRef, Ctor); 8578 } 8579 8580 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8581 8582 /// Process all constructors for a class. 8583 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8584 for (const auto *Ctor : RD->ctors()) 8585 (this->*Callback)(Ctor); 8586 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8587 I(RD->decls_begin()), E(RD->decls_end()); 8588 I != E; ++I) { 8589 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8590 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8591 (this->*Callback)(CD); 8592 } 8593 } 8594 8595 /// Note that a constructor (or constructor template) was declared in Derived. 8596 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8597 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8598 } 8599 8600 /// Inherit a single constructor. 8601 void inherit(const CXXConstructorDecl *Ctor) { 8602 const FunctionProtoType *CtorType = 8603 Ctor->getType()->castAs<FunctionProtoType>(); 8604 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8605 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8606 8607 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8608 8609 // Core issue (no number yet): the ellipsis is always discarded. 8610 if (EPI.Variadic) { 8611 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8612 SemaRef.Diag(Ctor->getLocation(), 8613 diag::note_using_decl_constructor_ellipsis); 8614 EPI.Variadic = false; 8615 } 8616 8617 // Declare a constructor for each number of parameters. 8618 // 8619 // C++11 [class.inhctor]p1: 8620 // The candidate set of inherited constructors from the class X named in 8621 // the using-declaration consists of [... modulo defects ...] for each 8622 // constructor or constructor template of X, the set of constructors or 8623 // constructor templates that results from omitting any ellipsis parameter 8624 // specification and successively omitting parameters with a default 8625 // argument from the end of the parameter-type-list 8626 unsigned MinParams = minParamsToInherit(Ctor); 8627 unsigned Params = Ctor->getNumParams(); 8628 if (Params >= MinParams) { 8629 do 8630 declareCtor(UsingLoc, Ctor, 8631 SemaRef.Context.getFunctionType( 8632 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8633 while (Params > MinParams && 8634 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8635 } 8636 } 8637 8638 /// Find the using-declaration which specified that we should inherit the 8639 /// constructors of \p Base. 8640 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8641 // No fancy lookup required; just look for the base constructor name 8642 // directly within the derived class. 8643 ASTContext &Context = SemaRef.Context; 8644 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8645 Context.getCanonicalType(Context.getRecordType(Base))); 8646 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8647 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8648 } 8649 8650 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8651 // C++11 [class.inhctor]p3: 8652 // [F]or each constructor template in the candidate set of inherited 8653 // constructors, a constructor template is implicitly declared 8654 if (Ctor->getDescribedFunctionTemplate()) 8655 return 0; 8656 8657 // For each non-template constructor in the candidate set of inherited 8658 // constructors other than a constructor having no parameters or a 8659 // copy/move constructor having a single parameter, a constructor is 8660 // implicitly declared [...] 8661 if (Ctor->getNumParams() == 0) 8662 return 1; 8663 if (Ctor->isCopyOrMoveConstructor()) 8664 return 2; 8665 8666 // Per discussion on core reflector, never inherit a constructor which 8667 // would become a default, copy, or move constructor of Derived either. 8668 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8669 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8670 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8671 } 8672 8673 /// Declare a single inheriting constructor, inheriting the specified 8674 /// constructor, with the given type. 8675 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8676 QualType DerivedType) { 8677 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8678 8679 // C++11 [class.inhctor]p3: 8680 // ... a constructor is implicitly declared with the same constructor 8681 // characteristics unless there is a user-declared constructor with 8682 // the same signature in the class where the using-declaration appears 8683 if (Entry.DeclaredInDerived) 8684 return; 8685 8686 // C++11 [class.inhctor]p7: 8687 // If two using-declarations declare inheriting constructors with the 8688 // same signature, the program is ill-formed 8689 if (Entry.DerivedCtor) { 8690 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8691 // Only diagnose this once per constructor. 8692 if (Entry.DerivedCtor->isInvalidDecl()) 8693 return; 8694 Entry.DerivedCtor->setInvalidDecl(); 8695 8696 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8697 SemaRef.Diag(BaseCtor->getLocation(), 8698 diag::note_using_decl_constructor_conflict_current_ctor); 8699 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8700 diag::note_using_decl_constructor_conflict_previous_ctor); 8701 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8702 diag::note_using_decl_constructor_conflict_previous_using); 8703 } else { 8704 // Core issue (no number): if the same inheriting constructor is 8705 // produced by multiple base class constructors from the same base 8706 // class, the inheriting constructor is defined as deleted. 8707 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8708 } 8709 8710 return; 8711 } 8712 8713 ASTContext &Context = SemaRef.Context; 8714 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8715 Context.getCanonicalType(Context.getRecordType(Derived))); 8716 DeclarationNameInfo NameInfo(Name, UsingLoc); 8717 8718 TemplateParameterList *TemplateParams = nullptr; 8719 if (const FunctionTemplateDecl *FTD = 8720 BaseCtor->getDescribedFunctionTemplate()) { 8721 TemplateParams = FTD->getTemplateParameters(); 8722 // We're reusing template parameters from a different DeclContext. This 8723 // is questionable at best, but works out because the template depth in 8724 // both places is guaranteed to be 0. 8725 // FIXME: Rebuild the template parameters in the new context, and 8726 // transform the function type to refer to them. 8727 } 8728 8729 // Build type source info pointing at the using-declaration. This is 8730 // required by template instantiation. 8731 TypeSourceInfo *TInfo = 8732 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8733 FunctionProtoTypeLoc ProtoLoc = 8734 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8735 8736 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8737 Context, Derived, UsingLoc, NameInfo, DerivedType, 8738 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8739 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8740 8741 // Build an unevaluated exception specification for this constructor. 8742 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8743 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8744 EPI.ExceptionSpec.Type = EST_Unevaluated; 8745 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 8746 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8747 FPT->getParamTypes(), EPI)); 8748 8749 // Build the parameter declarations. 8750 SmallVector<ParmVarDecl *, 16> ParamDecls; 8751 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8752 TypeSourceInfo *TInfo = 8753 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8754 ParmVarDecl *PD = ParmVarDecl::Create( 8755 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 8756 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 8757 PD->setScopeInfo(0, I); 8758 PD->setImplicit(); 8759 ParamDecls.push_back(PD); 8760 ProtoLoc.setParam(I, PD); 8761 } 8762 8763 // Set up the new constructor. 8764 DerivedCtor->setAccess(BaseCtor->getAccess()); 8765 DerivedCtor->setParams(ParamDecls); 8766 DerivedCtor->setInheritedConstructor(BaseCtor); 8767 if (BaseCtor->isDeleted()) 8768 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8769 8770 // If this is a constructor template, build the template declaration. 8771 if (TemplateParams) { 8772 FunctionTemplateDecl *DerivedTemplate = 8773 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8774 TemplateParams, DerivedCtor); 8775 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8776 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8777 Derived->addDecl(DerivedTemplate); 8778 } else { 8779 Derived->addDecl(DerivedCtor); 8780 } 8781 8782 Entry.BaseCtor = BaseCtor; 8783 Entry.DerivedCtor = DerivedCtor; 8784 } 8785 8786 Sema &SemaRef; 8787 CXXRecordDecl *Derived; 8788 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8789 MapType Map; 8790 }; 8791 } 8792 8793 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8794 // Defer declaring the inheriting constructors until the class is 8795 // instantiated. 8796 if (ClassDecl->isDependentContext()) 8797 return; 8798 8799 // Find base classes from which we might inherit constructors. 8800 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8801 for (const auto &BaseIt : ClassDecl->bases()) 8802 if (BaseIt.getInheritConstructors()) 8803 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8804 8805 // Go no further if we're not inheriting any constructors. 8806 if (InheritedBases.empty()) 8807 return; 8808 8809 // Declare the inherited constructors. 8810 InheritingConstructorInfo ICI(*this, ClassDecl); 8811 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8812 ICI.inheritAll(InheritedBases[I]); 8813 } 8814 8815 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8816 CXXConstructorDecl *Constructor) { 8817 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8818 assert(Constructor->getInheritedConstructor() && 8819 !Constructor->doesThisDeclarationHaveABody() && 8820 !Constructor->isDeleted()); 8821 8822 SynthesizedFunctionScope Scope(*this, Constructor); 8823 DiagnosticErrorTrap Trap(Diags); 8824 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8825 Trap.hasErrorOccurred()) { 8826 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8827 << Context.getTagDeclType(ClassDecl); 8828 Constructor->setInvalidDecl(); 8829 return; 8830 } 8831 8832 SourceLocation Loc = Constructor->getLocation(); 8833 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8834 8835 Constructor->markUsed(Context); 8836 MarkVTableUsed(CurrentLocation, ClassDecl); 8837 8838 if (ASTMutationListener *L = getASTMutationListener()) { 8839 L->CompletedImplicitDefinition(Constructor); 8840 } 8841 } 8842 8843 8844 Sema::ImplicitExceptionSpecification 8845 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8846 CXXRecordDecl *ClassDecl = MD->getParent(); 8847 8848 // C++ [except.spec]p14: 8849 // An implicitly declared special member function (Clause 12) shall have 8850 // an exception-specification. 8851 ImplicitExceptionSpecification ExceptSpec(*this); 8852 if (ClassDecl->isInvalidDecl()) 8853 return ExceptSpec; 8854 8855 // Direct base-class destructors. 8856 for (const auto &B : ClassDecl->bases()) { 8857 if (B.isVirtual()) // Handled below. 8858 continue; 8859 8860 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8861 ExceptSpec.CalledDecl(B.getLocStart(), 8862 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8863 } 8864 8865 // Virtual base-class destructors. 8866 for (const auto &B : ClassDecl->vbases()) { 8867 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8868 ExceptSpec.CalledDecl(B.getLocStart(), 8869 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8870 } 8871 8872 // Field destructors. 8873 for (const auto *F : ClassDecl->fields()) { 8874 if (const RecordType *RecordTy 8875 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8876 ExceptSpec.CalledDecl(F->getLocation(), 8877 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8878 } 8879 8880 return ExceptSpec; 8881 } 8882 8883 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8884 // C++ [class.dtor]p2: 8885 // If a class has no user-declared destructor, a destructor is 8886 // declared implicitly. An implicitly-declared destructor is an 8887 // inline public member of its class. 8888 assert(ClassDecl->needsImplicitDestructor()); 8889 8890 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8891 if (DSM.isAlreadyBeingDeclared()) 8892 return nullptr; 8893 8894 // Create the actual destructor declaration. 8895 CanQualType ClassType 8896 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8897 SourceLocation ClassLoc = ClassDecl->getLocation(); 8898 DeclarationName Name 8899 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8900 DeclarationNameInfo NameInfo(Name, ClassLoc); 8901 CXXDestructorDecl *Destructor 8902 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8903 QualType(), nullptr, /*isInline=*/true, 8904 /*isImplicitlyDeclared=*/true); 8905 Destructor->setAccess(AS_public); 8906 Destructor->setDefaulted(); 8907 Destructor->setImplicit(); 8908 8909 // Build an exception specification pointing back at this destructor. 8910 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8911 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8912 8913 AddOverriddenMethods(ClassDecl, Destructor); 8914 8915 // We don't need to use SpecialMemberIsTrivial here; triviality for 8916 // destructors is easy to compute. 8917 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8918 8919 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8920 SetDeclDeleted(Destructor, ClassLoc); 8921 8922 // Note that we have declared this destructor. 8923 ++ASTContext::NumImplicitDestructorsDeclared; 8924 8925 // Introduce this destructor into its scope. 8926 if (Scope *S = getScopeForContext(ClassDecl)) 8927 PushOnScopeChains(Destructor, S, false); 8928 ClassDecl->addDecl(Destructor); 8929 8930 return Destructor; 8931 } 8932 8933 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8934 CXXDestructorDecl *Destructor) { 8935 assert((Destructor->isDefaulted() && 8936 !Destructor->doesThisDeclarationHaveABody() && 8937 !Destructor->isDeleted()) && 8938 "DefineImplicitDestructor - call it for implicit default dtor"); 8939 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8940 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8941 8942 if (Destructor->isInvalidDecl()) 8943 return; 8944 8945 SynthesizedFunctionScope Scope(*this, Destructor); 8946 8947 DiagnosticErrorTrap Trap(Diags); 8948 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8949 Destructor->getParent()); 8950 8951 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8952 Diag(CurrentLocation, diag::note_member_synthesized_at) 8953 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8954 8955 Destructor->setInvalidDecl(); 8956 return; 8957 } 8958 8959 SourceLocation Loc = Destructor->getLocEnd().isValid() 8960 ? Destructor->getLocEnd() 8961 : Destructor->getLocation(); 8962 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8963 Destructor->markUsed(Context); 8964 MarkVTableUsed(CurrentLocation, ClassDecl); 8965 8966 if (ASTMutationListener *L = getASTMutationListener()) { 8967 L->CompletedImplicitDefinition(Destructor); 8968 } 8969 } 8970 8971 /// \brief Perform any semantic analysis which needs to be delayed until all 8972 /// pending class member declarations have been parsed. 8973 void Sema::ActOnFinishCXXMemberDecls() { 8974 // If the context is an invalid C++ class, just suppress these checks. 8975 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8976 if (Record->isInvalidDecl()) { 8977 DelayedDefaultedMemberExceptionSpecs.clear(); 8978 DelayedDestructorExceptionSpecChecks.clear(); 8979 return; 8980 } 8981 } 8982 } 8983 8984 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8985 CXXDestructorDecl *Destructor) { 8986 assert(getLangOpts().CPlusPlus11 && 8987 "adjusting dtor exception specs was introduced in c++11"); 8988 8989 // C++11 [class.dtor]p3: 8990 // A declaration of a destructor that does not have an exception- 8991 // specification is implicitly considered to have the same exception- 8992 // specification as an implicit declaration. 8993 const FunctionProtoType *DtorType = Destructor->getType()-> 8994 getAs<FunctionProtoType>(); 8995 if (DtorType->hasExceptionSpec()) 8996 return; 8997 8998 // Replace the destructor's type, building off the existing one. Fortunately, 8999 // the only thing of interest in the destructor type is its extended info. 9000 // The return and arguments are fixed. 9001 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9002 EPI.ExceptionSpec.Type = EST_Unevaluated; 9003 EPI.ExceptionSpec.SourceDecl = Destructor; 9004 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9005 9006 // FIXME: If the destructor has a body that could throw, and the newly created 9007 // spec doesn't allow exceptions, we should emit a warning, because this 9008 // change in behavior can break conforming C++03 programs at runtime. 9009 // However, we don't have a body or an exception specification yet, so it 9010 // needs to be done somewhere else. 9011 } 9012 9013 namespace { 9014 /// \brief An abstract base class for all helper classes used in building the 9015 // copy/move operators. These classes serve as factory functions and help us 9016 // avoid using the same Expr* in the AST twice. 9017 class ExprBuilder { 9018 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9019 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9020 9021 protected: 9022 static Expr *assertNotNull(Expr *E) { 9023 assert(E && "Expression construction must not fail."); 9024 return E; 9025 } 9026 9027 public: 9028 ExprBuilder() {} 9029 virtual ~ExprBuilder() {} 9030 9031 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9032 }; 9033 9034 class RefBuilder: public ExprBuilder { 9035 VarDecl *Var; 9036 QualType VarType; 9037 9038 public: 9039 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9040 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9041 } 9042 9043 RefBuilder(VarDecl *Var, QualType VarType) 9044 : Var(Var), VarType(VarType) {} 9045 }; 9046 9047 class ThisBuilder: public ExprBuilder { 9048 public: 9049 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9050 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9051 } 9052 }; 9053 9054 class CastBuilder: public ExprBuilder { 9055 const ExprBuilder &Builder; 9056 QualType Type; 9057 ExprValueKind Kind; 9058 const CXXCastPath &Path; 9059 9060 public: 9061 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9062 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9063 CK_UncheckedDerivedToBase, Kind, 9064 &Path).get()); 9065 } 9066 9067 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9068 const CXXCastPath &Path) 9069 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9070 }; 9071 9072 class DerefBuilder: public ExprBuilder { 9073 const ExprBuilder &Builder; 9074 9075 public: 9076 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9077 return assertNotNull( 9078 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9079 } 9080 9081 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9082 }; 9083 9084 class MemberBuilder: public ExprBuilder { 9085 const ExprBuilder &Builder; 9086 QualType Type; 9087 CXXScopeSpec SS; 9088 bool IsArrow; 9089 LookupResult &MemberLookup; 9090 9091 public: 9092 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9093 return assertNotNull(S.BuildMemberReferenceExpr( 9094 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9095 nullptr, MemberLookup, nullptr).get()); 9096 } 9097 9098 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9099 LookupResult &MemberLookup) 9100 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9101 MemberLookup(MemberLookup) {} 9102 }; 9103 9104 class MoveCastBuilder: public ExprBuilder { 9105 const ExprBuilder &Builder; 9106 9107 public: 9108 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9109 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9110 } 9111 9112 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9113 }; 9114 9115 class LvalueConvBuilder: public ExprBuilder { 9116 const ExprBuilder &Builder; 9117 9118 public: 9119 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9120 return assertNotNull( 9121 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9122 } 9123 9124 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9125 }; 9126 9127 class SubscriptBuilder: public ExprBuilder { 9128 const ExprBuilder &Base; 9129 const ExprBuilder &Index; 9130 9131 public: 9132 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9133 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9134 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9135 } 9136 9137 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9138 : Base(Base), Index(Index) {} 9139 }; 9140 9141 } // end anonymous namespace 9142 9143 /// When generating a defaulted copy or move assignment operator, if a field 9144 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9145 /// do so. This optimization only applies for arrays of scalars, and for arrays 9146 /// of class type where the selected copy/move-assignment operator is trivial. 9147 static StmtResult 9148 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9149 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9150 // Compute the size of the memory buffer to be copied. 9151 QualType SizeType = S.Context.getSizeType(); 9152 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9153 S.Context.getTypeSizeInChars(T).getQuantity()); 9154 9155 // Take the address of the field references for "from" and "to". We 9156 // directly construct UnaryOperators here because semantic analysis 9157 // does not permit us to take the address of an xvalue. 9158 Expr *From = FromB.build(S, Loc); 9159 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9160 S.Context.getPointerType(From->getType()), 9161 VK_RValue, OK_Ordinary, Loc); 9162 Expr *To = ToB.build(S, Loc); 9163 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9164 S.Context.getPointerType(To->getType()), 9165 VK_RValue, OK_Ordinary, Loc); 9166 9167 const Type *E = T->getBaseElementTypeUnsafe(); 9168 bool NeedsCollectableMemCpy = 9169 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9170 9171 // Create a reference to the __builtin_objc_memmove_collectable function 9172 StringRef MemCpyName = NeedsCollectableMemCpy ? 9173 "__builtin_objc_memmove_collectable" : 9174 "__builtin_memcpy"; 9175 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9176 Sema::LookupOrdinaryName); 9177 S.LookupName(R, S.TUScope, true); 9178 9179 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9180 if (!MemCpy) 9181 // Something went horribly wrong earlier, and we will have complained 9182 // about it. 9183 return StmtError(); 9184 9185 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9186 VK_RValue, Loc, nullptr); 9187 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9188 9189 Expr *CallArgs[] = { 9190 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9191 }; 9192 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9193 Loc, CallArgs, Loc); 9194 9195 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9196 return Call.getAs<Stmt>(); 9197 } 9198 9199 /// \brief Builds a statement that copies/moves the given entity from \p From to 9200 /// \c To. 9201 /// 9202 /// This routine is used to copy/move the members of a class with an 9203 /// implicitly-declared copy/move assignment operator. When the entities being 9204 /// copied are arrays, this routine builds for loops to copy them. 9205 /// 9206 /// \param S The Sema object used for type-checking. 9207 /// 9208 /// \param Loc The location where the implicit copy/move is being generated. 9209 /// 9210 /// \param T The type of the expressions being copied/moved. Both expressions 9211 /// must have this type. 9212 /// 9213 /// \param To The expression we are copying/moving to. 9214 /// 9215 /// \param From The expression we are copying/moving from. 9216 /// 9217 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9218 /// Otherwise, it's a non-static member subobject. 9219 /// 9220 /// \param Copying Whether we're copying or moving. 9221 /// 9222 /// \param Depth Internal parameter recording the depth of the recursion. 9223 /// 9224 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9225 /// if a memcpy should be used instead. 9226 static StmtResult 9227 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9228 const ExprBuilder &To, const ExprBuilder &From, 9229 bool CopyingBaseSubobject, bool Copying, 9230 unsigned Depth = 0) { 9231 // C++11 [class.copy]p28: 9232 // Each subobject is assigned in the manner appropriate to its type: 9233 // 9234 // - if the subobject is of class type, as if by a call to operator= with 9235 // the subobject as the object expression and the corresponding 9236 // subobject of x as a single function argument (as if by explicit 9237 // qualification; that is, ignoring any possible virtual overriding 9238 // functions in more derived classes); 9239 // 9240 // C++03 [class.copy]p13: 9241 // - if the subobject is of class type, the copy assignment operator for 9242 // the class is used (as if by explicit qualification; that is, 9243 // ignoring any possible virtual overriding functions in more derived 9244 // classes); 9245 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9246 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9247 9248 // Look for operator=. 9249 DeclarationName Name 9250 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9251 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9252 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9253 9254 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9255 // operator. 9256 if (!S.getLangOpts().CPlusPlus11) { 9257 LookupResult::Filter F = OpLookup.makeFilter(); 9258 while (F.hasNext()) { 9259 NamedDecl *D = F.next(); 9260 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9261 if (Method->isCopyAssignmentOperator() || 9262 (!Copying && Method->isMoveAssignmentOperator())) 9263 continue; 9264 9265 F.erase(); 9266 } 9267 F.done(); 9268 } 9269 9270 // Suppress the protected check (C++ [class.protected]) for each of the 9271 // assignment operators we found. This strange dance is required when 9272 // we're assigning via a base classes's copy-assignment operator. To 9273 // ensure that we're getting the right base class subobject (without 9274 // ambiguities), we need to cast "this" to that subobject type; to 9275 // ensure that we don't go through the virtual call mechanism, we need 9276 // to qualify the operator= name with the base class (see below). However, 9277 // this means that if the base class has a protected copy assignment 9278 // operator, the protected member access check will fail. So, we 9279 // rewrite "protected" access to "public" access in this case, since we 9280 // know by construction that we're calling from a derived class. 9281 if (CopyingBaseSubobject) { 9282 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9283 L != LEnd; ++L) { 9284 if (L.getAccess() == AS_protected) 9285 L.setAccess(AS_public); 9286 } 9287 } 9288 9289 // Create the nested-name-specifier that will be used to qualify the 9290 // reference to operator=; this is required to suppress the virtual 9291 // call mechanism. 9292 CXXScopeSpec SS; 9293 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9294 SS.MakeTrivial(S.Context, 9295 NestedNameSpecifier::Create(S.Context, nullptr, false, 9296 CanonicalT), 9297 Loc); 9298 9299 // Create the reference to operator=. 9300 ExprResult OpEqualRef 9301 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9302 SS, /*TemplateKWLoc=*/SourceLocation(), 9303 /*FirstQualifierInScope=*/nullptr, 9304 OpLookup, 9305 /*TemplateArgs=*/nullptr, 9306 /*SuppressQualifierCheck=*/true); 9307 if (OpEqualRef.isInvalid()) 9308 return StmtError(); 9309 9310 // Build the call to the assignment operator. 9311 9312 Expr *FromInst = From.build(S, Loc); 9313 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9314 OpEqualRef.getAs<Expr>(), 9315 Loc, FromInst, Loc); 9316 if (Call.isInvalid()) 9317 return StmtError(); 9318 9319 // If we built a call to a trivial 'operator=' while copying an array, 9320 // bail out. We'll replace the whole shebang with a memcpy. 9321 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9322 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9323 return StmtResult((Stmt*)nullptr); 9324 9325 // Convert to an expression-statement, and clean up any produced 9326 // temporaries. 9327 return S.ActOnExprStmt(Call); 9328 } 9329 9330 // - if the subobject is of scalar type, the built-in assignment 9331 // operator is used. 9332 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9333 if (!ArrayTy) { 9334 ExprResult Assignment = S.CreateBuiltinBinOp( 9335 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9336 if (Assignment.isInvalid()) 9337 return StmtError(); 9338 return S.ActOnExprStmt(Assignment); 9339 } 9340 9341 // - if the subobject is an array, each element is assigned, in the 9342 // manner appropriate to the element type; 9343 9344 // Construct a loop over the array bounds, e.g., 9345 // 9346 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9347 // 9348 // that will copy each of the array elements. 9349 QualType SizeType = S.Context.getSizeType(); 9350 9351 // Create the iteration variable. 9352 IdentifierInfo *IterationVarName = nullptr; 9353 { 9354 SmallString<8> Str; 9355 llvm::raw_svector_ostream OS(Str); 9356 OS << "__i" << Depth; 9357 IterationVarName = &S.Context.Idents.get(OS.str()); 9358 } 9359 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9360 IterationVarName, SizeType, 9361 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9362 SC_None); 9363 9364 // Initialize the iteration variable to zero. 9365 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9366 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9367 9368 // Creates a reference to the iteration variable. 9369 RefBuilder IterationVarRef(IterationVar, SizeType); 9370 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9371 9372 // Create the DeclStmt that holds the iteration variable. 9373 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9374 9375 // Subscript the "from" and "to" expressions with the iteration variable. 9376 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9377 MoveCastBuilder FromIndexMove(FromIndexCopy); 9378 const ExprBuilder *FromIndex; 9379 if (Copying) 9380 FromIndex = &FromIndexCopy; 9381 else 9382 FromIndex = &FromIndexMove; 9383 9384 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9385 9386 // Build the copy/move for an individual element of the array. 9387 StmtResult Copy = 9388 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9389 ToIndex, *FromIndex, CopyingBaseSubobject, 9390 Copying, Depth + 1); 9391 // Bail out if copying fails or if we determined that we should use memcpy. 9392 if (Copy.isInvalid() || !Copy.get()) 9393 return Copy; 9394 9395 // Create the comparison against the array bound. 9396 llvm::APInt Upper 9397 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9398 Expr *Comparison 9399 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9400 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9401 BO_NE, S.Context.BoolTy, 9402 VK_RValue, OK_Ordinary, Loc, false); 9403 9404 // Create the pre-increment of the iteration variable. 9405 Expr *Increment 9406 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9407 SizeType, VK_LValue, OK_Ordinary, Loc); 9408 9409 // Construct the loop that copies all elements of this array. 9410 return S.ActOnForStmt(Loc, Loc, InitStmt, 9411 S.MakeFullExpr(Comparison), 9412 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9413 Loc, Copy.get()); 9414 } 9415 9416 static StmtResult 9417 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9418 const ExprBuilder &To, const ExprBuilder &From, 9419 bool CopyingBaseSubobject, bool Copying) { 9420 // Maybe we should use a memcpy? 9421 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9422 T.isTriviallyCopyableType(S.Context)) 9423 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9424 9425 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9426 CopyingBaseSubobject, 9427 Copying, 0)); 9428 9429 // If we ended up picking a trivial assignment operator for an array of a 9430 // non-trivially-copyable class type, just emit a memcpy. 9431 if (!Result.isInvalid() && !Result.get()) 9432 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9433 9434 return Result; 9435 } 9436 9437 Sema::ImplicitExceptionSpecification 9438 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9439 CXXRecordDecl *ClassDecl = MD->getParent(); 9440 9441 ImplicitExceptionSpecification ExceptSpec(*this); 9442 if (ClassDecl->isInvalidDecl()) 9443 return ExceptSpec; 9444 9445 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9446 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9447 unsigned ArgQuals = 9448 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9449 9450 // C++ [except.spec]p14: 9451 // An implicitly declared special member function (Clause 12) shall have an 9452 // exception-specification. [...] 9453 9454 // It is unspecified whether or not an implicit copy assignment operator 9455 // attempts to deduplicate calls to assignment operators of virtual bases are 9456 // made. As such, this exception specification is effectively unspecified. 9457 // Based on a similar decision made for constness in C++0x, we're erring on 9458 // the side of assuming such calls to be made regardless of whether they 9459 // actually happen. 9460 for (const auto &Base : ClassDecl->bases()) { 9461 if (Base.isVirtual()) 9462 continue; 9463 9464 CXXRecordDecl *BaseClassDecl 9465 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9466 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9467 ArgQuals, false, 0)) 9468 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9469 } 9470 9471 for (const auto &Base : ClassDecl->vbases()) { 9472 CXXRecordDecl *BaseClassDecl 9473 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9474 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9475 ArgQuals, false, 0)) 9476 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9477 } 9478 9479 for (const auto *Field : ClassDecl->fields()) { 9480 QualType FieldType = Context.getBaseElementType(Field->getType()); 9481 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9482 if (CXXMethodDecl *CopyAssign = 9483 LookupCopyingAssignment(FieldClassDecl, 9484 ArgQuals | FieldType.getCVRQualifiers(), 9485 false, 0)) 9486 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9487 } 9488 } 9489 9490 return ExceptSpec; 9491 } 9492 9493 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9494 // Note: The following rules are largely analoguous to the copy 9495 // constructor rules. Note that virtual bases are not taken into account 9496 // for determining the argument type of the operator. Note also that 9497 // operators taking an object instead of a reference are allowed. 9498 assert(ClassDecl->needsImplicitCopyAssignment()); 9499 9500 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9501 if (DSM.isAlreadyBeingDeclared()) 9502 return nullptr; 9503 9504 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9505 QualType RetType = Context.getLValueReferenceType(ArgType); 9506 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9507 if (Const) 9508 ArgType = ArgType.withConst(); 9509 ArgType = Context.getLValueReferenceType(ArgType); 9510 9511 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9512 CXXCopyAssignment, 9513 Const); 9514 9515 // An implicitly-declared copy assignment operator is an inline public 9516 // member of its class. 9517 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9518 SourceLocation ClassLoc = ClassDecl->getLocation(); 9519 DeclarationNameInfo NameInfo(Name, ClassLoc); 9520 CXXMethodDecl *CopyAssignment = 9521 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9522 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9523 /*isInline=*/true, Constexpr, SourceLocation()); 9524 CopyAssignment->setAccess(AS_public); 9525 CopyAssignment->setDefaulted(); 9526 CopyAssignment->setImplicit(); 9527 9528 // Build an exception specification pointing back at this member. 9529 FunctionProtoType::ExtProtoInfo EPI = 9530 getImplicitMethodEPI(*this, CopyAssignment); 9531 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9532 9533 // Add the parameter to the operator. 9534 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9535 ClassLoc, ClassLoc, 9536 /*Id=*/nullptr, ArgType, 9537 /*TInfo=*/nullptr, SC_None, 9538 nullptr); 9539 CopyAssignment->setParams(FromParam); 9540 9541 AddOverriddenMethods(ClassDecl, CopyAssignment); 9542 9543 CopyAssignment->setTrivial( 9544 ClassDecl->needsOverloadResolutionForCopyAssignment() 9545 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9546 : ClassDecl->hasTrivialCopyAssignment()); 9547 9548 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9549 SetDeclDeleted(CopyAssignment, ClassLoc); 9550 9551 // Note that we have added this copy-assignment operator. 9552 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9553 9554 if (Scope *S = getScopeForContext(ClassDecl)) 9555 PushOnScopeChains(CopyAssignment, S, false); 9556 ClassDecl->addDecl(CopyAssignment); 9557 9558 return CopyAssignment; 9559 } 9560 9561 /// Diagnose an implicit copy operation for a class which is odr-used, but 9562 /// which is deprecated because the class has a user-declared copy constructor, 9563 /// copy assignment operator, or destructor. 9564 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9565 SourceLocation UseLoc) { 9566 assert(CopyOp->isImplicit()); 9567 9568 CXXRecordDecl *RD = CopyOp->getParent(); 9569 CXXMethodDecl *UserDeclaredOperation = nullptr; 9570 9571 // In Microsoft mode, assignment operations don't affect constructors and 9572 // vice versa. 9573 if (RD->hasUserDeclaredDestructor()) { 9574 UserDeclaredOperation = RD->getDestructor(); 9575 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9576 RD->hasUserDeclaredCopyConstructor() && 9577 !S.getLangOpts().MSVCCompat) { 9578 // Find any user-declared copy constructor. 9579 for (auto *I : RD->ctors()) { 9580 if (I->isCopyConstructor()) { 9581 UserDeclaredOperation = I; 9582 break; 9583 } 9584 } 9585 assert(UserDeclaredOperation); 9586 } else if (isa<CXXConstructorDecl>(CopyOp) && 9587 RD->hasUserDeclaredCopyAssignment() && 9588 !S.getLangOpts().MSVCCompat) { 9589 // Find any user-declared move assignment operator. 9590 for (auto *I : RD->methods()) { 9591 if (I->isCopyAssignmentOperator()) { 9592 UserDeclaredOperation = I; 9593 break; 9594 } 9595 } 9596 assert(UserDeclaredOperation); 9597 } 9598 9599 if (UserDeclaredOperation) { 9600 S.Diag(UserDeclaredOperation->getLocation(), 9601 diag::warn_deprecated_copy_operation) 9602 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9603 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9604 S.Diag(UseLoc, diag::note_member_synthesized_at) 9605 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9606 : Sema::CXXCopyAssignment) 9607 << RD; 9608 } 9609 } 9610 9611 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9612 CXXMethodDecl *CopyAssignOperator) { 9613 assert((CopyAssignOperator->isDefaulted() && 9614 CopyAssignOperator->isOverloadedOperator() && 9615 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9616 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9617 !CopyAssignOperator->isDeleted()) && 9618 "DefineImplicitCopyAssignment called for wrong function"); 9619 9620 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9621 9622 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9623 CopyAssignOperator->setInvalidDecl(); 9624 return; 9625 } 9626 9627 // C++11 [class.copy]p18: 9628 // The [definition of an implicitly declared copy assignment operator] is 9629 // deprecated if the class has a user-declared copy constructor or a 9630 // user-declared destructor. 9631 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9632 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9633 9634 CopyAssignOperator->markUsed(Context); 9635 9636 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9637 DiagnosticErrorTrap Trap(Diags); 9638 9639 // C++0x [class.copy]p30: 9640 // The implicitly-defined or explicitly-defaulted copy assignment operator 9641 // for a non-union class X performs memberwise copy assignment of its 9642 // subobjects. The direct base classes of X are assigned first, in the 9643 // order of their declaration in the base-specifier-list, and then the 9644 // immediate non-static data members of X are assigned, in the order in 9645 // which they were declared in the class definition. 9646 9647 // The statements that form the synthesized function body. 9648 SmallVector<Stmt*, 8> Statements; 9649 9650 // The parameter for the "other" object, which we are copying from. 9651 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9652 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9653 QualType OtherRefType = Other->getType(); 9654 if (const LValueReferenceType *OtherRef 9655 = OtherRefType->getAs<LValueReferenceType>()) { 9656 OtherRefType = OtherRef->getPointeeType(); 9657 OtherQuals = OtherRefType.getQualifiers(); 9658 } 9659 9660 // Our location for everything implicitly-generated. 9661 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9662 ? CopyAssignOperator->getLocEnd() 9663 : CopyAssignOperator->getLocation(); 9664 9665 // Builds a DeclRefExpr for the "other" object. 9666 RefBuilder OtherRef(Other, OtherRefType); 9667 9668 // Builds the "this" pointer. 9669 ThisBuilder This; 9670 9671 // Assign base classes. 9672 bool Invalid = false; 9673 for (auto &Base : ClassDecl->bases()) { 9674 // Form the assignment: 9675 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9676 QualType BaseType = Base.getType().getUnqualifiedType(); 9677 if (!BaseType->isRecordType()) { 9678 Invalid = true; 9679 continue; 9680 } 9681 9682 CXXCastPath BasePath; 9683 BasePath.push_back(&Base); 9684 9685 // Construct the "from" expression, which is an implicit cast to the 9686 // appropriately-qualified base type. 9687 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9688 VK_LValue, BasePath); 9689 9690 // Dereference "this". 9691 DerefBuilder DerefThis(This); 9692 CastBuilder To(DerefThis, 9693 Context.getCVRQualifiedType( 9694 BaseType, CopyAssignOperator->getTypeQualifiers()), 9695 VK_LValue, BasePath); 9696 9697 // Build the copy. 9698 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9699 To, From, 9700 /*CopyingBaseSubobject=*/true, 9701 /*Copying=*/true); 9702 if (Copy.isInvalid()) { 9703 Diag(CurrentLocation, diag::note_member_synthesized_at) 9704 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9705 CopyAssignOperator->setInvalidDecl(); 9706 return; 9707 } 9708 9709 // Success! Record the copy. 9710 Statements.push_back(Copy.getAs<Expr>()); 9711 } 9712 9713 // Assign non-static members. 9714 for (auto *Field : ClassDecl->fields()) { 9715 if (Field->isUnnamedBitfield()) 9716 continue; 9717 9718 if (Field->isInvalidDecl()) { 9719 Invalid = true; 9720 continue; 9721 } 9722 9723 // Check for members of reference type; we can't copy those. 9724 if (Field->getType()->isReferenceType()) { 9725 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9726 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9727 Diag(Field->getLocation(), diag::note_declared_at); 9728 Diag(CurrentLocation, diag::note_member_synthesized_at) 9729 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9730 Invalid = true; 9731 continue; 9732 } 9733 9734 // Check for members of const-qualified, non-class type. 9735 QualType BaseType = Context.getBaseElementType(Field->getType()); 9736 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9737 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9738 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9739 Diag(Field->getLocation(), diag::note_declared_at); 9740 Diag(CurrentLocation, diag::note_member_synthesized_at) 9741 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9742 Invalid = true; 9743 continue; 9744 } 9745 9746 // Suppress assigning zero-width bitfields. 9747 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9748 continue; 9749 9750 QualType FieldType = Field->getType().getNonReferenceType(); 9751 if (FieldType->isIncompleteArrayType()) { 9752 assert(ClassDecl->hasFlexibleArrayMember() && 9753 "Incomplete array type is not valid"); 9754 continue; 9755 } 9756 9757 // Build references to the field in the object we're copying from and to. 9758 CXXScopeSpec SS; // Intentionally empty 9759 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9760 LookupMemberName); 9761 MemberLookup.addDecl(Field); 9762 MemberLookup.resolveKind(); 9763 9764 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9765 9766 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9767 9768 // Build the copy of this field. 9769 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9770 To, From, 9771 /*CopyingBaseSubobject=*/false, 9772 /*Copying=*/true); 9773 if (Copy.isInvalid()) { 9774 Diag(CurrentLocation, diag::note_member_synthesized_at) 9775 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9776 CopyAssignOperator->setInvalidDecl(); 9777 return; 9778 } 9779 9780 // Success! Record the copy. 9781 Statements.push_back(Copy.getAs<Stmt>()); 9782 } 9783 9784 if (!Invalid) { 9785 // Add a "return *this;" 9786 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9787 9788 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 9789 if (Return.isInvalid()) 9790 Invalid = true; 9791 else { 9792 Statements.push_back(Return.getAs<Stmt>()); 9793 9794 if (Trap.hasErrorOccurred()) { 9795 Diag(CurrentLocation, diag::note_member_synthesized_at) 9796 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9797 Invalid = true; 9798 } 9799 } 9800 } 9801 9802 if (Invalid) { 9803 CopyAssignOperator->setInvalidDecl(); 9804 return; 9805 } 9806 9807 StmtResult Body; 9808 { 9809 CompoundScopeRAII CompoundScope(*this); 9810 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9811 /*isStmtExpr=*/false); 9812 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9813 } 9814 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 9815 9816 if (ASTMutationListener *L = getASTMutationListener()) { 9817 L->CompletedImplicitDefinition(CopyAssignOperator); 9818 } 9819 } 9820 9821 Sema::ImplicitExceptionSpecification 9822 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9823 CXXRecordDecl *ClassDecl = MD->getParent(); 9824 9825 ImplicitExceptionSpecification ExceptSpec(*this); 9826 if (ClassDecl->isInvalidDecl()) 9827 return ExceptSpec; 9828 9829 // C++0x [except.spec]p14: 9830 // An implicitly declared special member function (Clause 12) shall have an 9831 // exception-specification. [...] 9832 9833 // It is unspecified whether or not an implicit move assignment operator 9834 // attempts to deduplicate calls to assignment operators of virtual bases are 9835 // made. As such, this exception specification is effectively unspecified. 9836 // Based on a similar decision made for constness in C++0x, we're erring on 9837 // the side of assuming such calls to be made regardless of whether they 9838 // actually happen. 9839 // Note that a move constructor is not implicitly declared when there are 9840 // virtual bases, but it can still be user-declared and explicitly defaulted. 9841 for (const auto &Base : ClassDecl->bases()) { 9842 if (Base.isVirtual()) 9843 continue; 9844 9845 CXXRecordDecl *BaseClassDecl 9846 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9847 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9848 0, false, 0)) 9849 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9850 } 9851 9852 for (const auto &Base : ClassDecl->vbases()) { 9853 CXXRecordDecl *BaseClassDecl 9854 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9855 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9856 0, false, 0)) 9857 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9858 } 9859 9860 for (const auto *Field : ClassDecl->fields()) { 9861 QualType FieldType = Context.getBaseElementType(Field->getType()); 9862 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9863 if (CXXMethodDecl *MoveAssign = 9864 LookupMovingAssignment(FieldClassDecl, 9865 FieldType.getCVRQualifiers(), 9866 false, 0)) 9867 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9868 } 9869 } 9870 9871 return ExceptSpec; 9872 } 9873 9874 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9875 assert(ClassDecl->needsImplicitMoveAssignment()); 9876 9877 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9878 if (DSM.isAlreadyBeingDeclared()) 9879 return nullptr; 9880 9881 // Note: The following rules are largely analoguous to the move 9882 // constructor rules. 9883 9884 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9885 QualType RetType = Context.getLValueReferenceType(ArgType); 9886 ArgType = Context.getRValueReferenceType(ArgType); 9887 9888 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9889 CXXMoveAssignment, 9890 false); 9891 9892 // An implicitly-declared move assignment operator is an inline public 9893 // member of its class. 9894 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9895 SourceLocation ClassLoc = ClassDecl->getLocation(); 9896 DeclarationNameInfo NameInfo(Name, ClassLoc); 9897 CXXMethodDecl *MoveAssignment = 9898 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9899 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9900 /*isInline=*/true, Constexpr, SourceLocation()); 9901 MoveAssignment->setAccess(AS_public); 9902 MoveAssignment->setDefaulted(); 9903 MoveAssignment->setImplicit(); 9904 9905 // Build an exception specification pointing back at this member. 9906 FunctionProtoType::ExtProtoInfo EPI = 9907 getImplicitMethodEPI(*this, MoveAssignment); 9908 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9909 9910 // Add the parameter to the operator. 9911 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9912 ClassLoc, ClassLoc, 9913 /*Id=*/nullptr, ArgType, 9914 /*TInfo=*/nullptr, SC_None, 9915 nullptr); 9916 MoveAssignment->setParams(FromParam); 9917 9918 AddOverriddenMethods(ClassDecl, MoveAssignment); 9919 9920 MoveAssignment->setTrivial( 9921 ClassDecl->needsOverloadResolutionForMoveAssignment() 9922 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9923 : ClassDecl->hasTrivialMoveAssignment()); 9924 9925 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9926 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9927 SetDeclDeleted(MoveAssignment, ClassLoc); 9928 } 9929 9930 // Note that we have added this copy-assignment operator. 9931 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9932 9933 if (Scope *S = getScopeForContext(ClassDecl)) 9934 PushOnScopeChains(MoveAssignment, S, false); 9935 ClassDecl->addDecl(MoveAssignment); 9936 9937 return MoveAssignment; 9938 } 9939 9940 /// Check if we're implicitly defining a move assignment operator for a class 9941 /// with virtual bases. Such a move assignment might move-assign the virtual 9942 /// base multiple times. 9943 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9944 SourceLocation CurrentLocation) { 9945 assert(!Class->isDependentContext() && "should not define dependent move"); 9946 9947 // Only a virtual base could get implicitly move-assigned multiple times. 9948 // Only a non-trivial move assignment can observe this. We only want to 9949 // diagnose if we implicitly define an assignment operator that assigns 9950 // two base classes, both of which move-assign the same virtual base. 9951 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9952 Class->getNumBases() < 2) 9953 return; 9954 9955 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9956 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9957 VBaseMap VBases; 9958 9959 for (auto &BI : Class->bases()) { 9960 Worklist.push_back(&BI); 9961 while (!Worklist.empty()) { 9962 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9963 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9964 9965 // If the base has no non-trivial move assignment operators, 9966 // we don't care about moves from it. 9967 if (!Base->hasNonTrivialMoveAssignment()) 9968 continue; 9969 9970 // If there's nothing virtual here, skip it. 9971 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9972 continue; 9973 9974 // If we're not actually going to call a move assignment for this base, 9975 // or the selected move assignment is trivial, skip it. 9976 Sema::SpecialMemberOverloadResult *SMOR = 9977 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9978 /*ConstArg*/false, /*VolatileArg*/false, 9979 /*RValueThis*/true, /*ConstThis*/false, 9980 /*VolatileThis*/false); 9981 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9982 !SMOR->getMethod()->isMoveAssignmentOperator()) 9983 continue; 9984 9985 if (BaseSpec->isVirtual()) { 9986 // We're going to move-assign this virtual base, and its move 9987 // assignment operator is not trivial. If this can happen for 9988 // multiple distinct direct bases of Class, diagnose it. (If it 9989 // only happens in one base, we'll diagnose it when synthesizing 9990 // that base class's move assignment operator.) 9991 CXXBaseSpecifier *&Existing = 9992 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9993 .first->second; 9994 if (Existing && Existing != &BI) { 9995 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9996 << Class << Base; 9997 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9998 << (Base->getCanonicalDecl() == 9999 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10000 << Base << Existing->getType() << Existing->getSourceRange(); 10001 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10002 << (Base->getCanonicalDecl() == 10003 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10004 << Base << BI.getType() << BaseSpec->getSourceRange(); 10005 10006 // Only diagnose each vbase once. 10007 Existing = nullptr; 10008 } 10009 } else { 10010 // Only walk over bases that have defaulted move assignment operators. 10011 // We assume that any user-provided move assignment operator handles 10012 // the multiple-moves-of-vbase case itself somehow. 10013 if (!SMOR->getMethod()->isDefaulted()) 10014 continue; 10015 10016 // We're going to move the base classes of Base. Add them to the list. 10017 for (auto &BI : Base->bases()) 10018 Worklist.push_back(&BI); 10019 } 10020 } 10021 } 10022 } 10023 10024 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10025 CXXMethodDecl *MoveAssignOperator) { 10026 assert((MoveAssignOperator->isDefaulted() && 10027 MoveAssignOperator->isOverloadedOperator() && 10028 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10029 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10030 !MoveAssignOperator->isDeleted()) && 10031 "DefineImplicitMoveAssignment called for wrong function"); 10032 10033 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10034 10035 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10036 MoveAssignOperator->setInvalidDecl(); 10037 return; 10038 } 10039 10040 MoveAssignOperator->markUsed(Context); 10041 10042 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10043 DiagnosticErrorTrap Trap(Diags); 10044 10045 // C++0x [class.copy]p28: 10046 // The implicitly-defined or move assignment operator for a non-union class 10047 // X performs memberwise move assignment of its subobjects. The direct base 10048 // classes of X are assigned first, in the order of their declaration in the 10049 // base-specifier-list, and then the immediate non-static data members of X 10050 // are assigned, in the order in which they were declared in the class 10051 // definition. 10052 10053 // Issue a warning if our implicit move assignment operator will move 10054 // from a virtual base more than once. 10055 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10056 10057 // The statements that form the synthesized function body. 10058 SmallVector<Stmt*, 8> Statements; 10059 10060 // The parameter for the "other" object, which we are move from. 10061 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10062 QualType OtherRefType = Other->getType()-> 10063 getAs<RValueReferenceType>()->getPointeeType(); 10064 assert(!OtherRefType.getQualifiers() && 10065 "Bad argument type of defaulted move assignment"); 10066 10067 // Our location for everything implicitly-generated. 10068 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10069 ? MoveAssignOperator->getLocEnd() 10070 : MoveAssignOperator->getLocation(); 10071 10072 // Builds a reference to the "other" object. 10073 RefBuilder OtherRef(Other, OtherRefType); 10074 // Cast to rvalue. 10075 MoveCastBuilder MoveOther(OtherRef); 10076 10077 // Builds the "this" pointer. 10078 ThisBuilder This; 10079 10080 // Assign base classes. 10081 bool Invalid = false; 10082 for (auto &Base : ClassDecl->bases()) { 10083 // C++11 [class.copy]p28: 10084 // It is unspecified whether subobjects representing virtual base classes 10085 // are assigned more than once by the implicitly-defined copy assignment 10086 // operator. 10087 // FIXME: Do not assign to a vbase that will be assigned by some other base 10088 // class. For a move-assignment, this can result in the vbase being moved 10089 // multiple times. 10090 10091 // Form the assignment: 10092 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10093 QualType BaseType = Base.getType().getUnqualifiedType(); 10094 if (!BaseType->isRecordType()) { 10095 Invalid = true; 10096 continue; 10097 } 10098 10099 CXXCastPath BasePath; 10100 BasePath.push_back(&Base); 10101 10102 // Construct the "from" expression, which is an implicit cast to the 10103 // appropriately-qualified base type. 10104 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10105 10106 // Dereference "this". 10107 DerefBuilder DerefThis(This); 10108 10109 // Implicitly cast "this" to the appropriately-qualified base type. 10110 CastBuilder To(DerefThis, 10111 Context.getCVRQualifiedType( 10112 BaseType, MoveAssignOperator->getTypeQualifiers()), 10113 VK_LValue, BasePath); 10114 10115 // Build the move. 10116 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10117 To, From, 10118 /*CopyingBaseSubobject=*/true, 10119 /*Copying=*/false); 10120 if (Move.isInvalid()) { 10121 Diag(CurrentLocation, diag::note_member_synthesized_at) 10122 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10123 MoveAssignOperator->setInvalidDecl(); 10124 return; 10125 } 10126 10127 // Success! Record the move. 10128 Statements.push_back(Move.getAs<Expr>()); 10129 } 10130 10131 // Assign non-static members. 10132 for (auto *Field : ClassDecl->fields()) { 10133 if (Field->isUnnamedBitfield()) 10134 continue; 10135 10136 if (Field->isInvalidDecl()) { 10137 Invalid = true; 10138 continue; 10139 } 10140 10141 // Check for members of reference type; we can't move those. 10142 if (Field->getType()->isReferenceType()) { 10143 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10144 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10145 Diag(Field->getLocation(), diag::note_declared_at); 10146 Diag(CurrentLocation, diag::note_member_synthesized_at) 10147 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10148 Invalid = true; 10149 continue; 10150 } 10151 10152 // Check for members of const-qualified, non-class type. 10153 QualType BaseType = Context.getBaseElementType(Field->getType()); 10154 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10155 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10156 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10157 Diag(Field->getLocation(), diag::note_declared_at); 10158 Diag(CurrentLocation, diag::note_member_synthesized_at) 10159 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10160 Invalid = true; 10161 continue; 10162 } 10163 10164 // Suppress assigning zero-width bitfields. 10165 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10166 continue; 10167 10168 QualType FieldType = Field->getType().getNonReferenceType(); 10169 if (FieldType->isIncompleteArrayType()) { 10170 assert(ClassDecl->hasFlexibleArrayMember() && 10171 "Incomplete array type is not valid"); 10172 continue; 10173 } 10174 10175 // Build references to the field in the object we're copying from and to. 10176 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10177 LookupMemberName); 10178 MemberLookup.addDecl(Field); 10179 MemberLookup.resolveKind(); 10180 MemberBuilder From(MoveOther, OtherRefType, 10181 /*IsArrow=*/false, MemberLookup); 10182 MemberBuilder To(This, getCurrentThisType(), 10183 /*IsArrow=*/true, MemberLookup); 10184 10185 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10186 "Member reference with rvalue base must be rvalue except for reference " 10187 "members, which aren't allowed for move assignment."); 10188 10189 // Build the move of this field. 10190 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10191 To, From, 10192 /*CopyingBaseSubobject=*/false, 10193 /*Copying=*/false); 10194 if (Move.isInvalid()) { 10195 Diag(CurrentLocation, diag::note_member_synthesized_at) 10196 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10197 MoveAssignOperator->setInvalidDecl(); 10198 return; 10199 } 10200 10201 // Success! Record the copy. 10202 Statements.push_back(Move.getAs<Stmt>()); 10203 } 10204 10205 if (!Invalid) { 10206 // Add a "return *this;" 10207 ExprResult ThisObj = 10208 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10209 10210 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10211 if (Return.isInvalid()) 10212 Invalid = true; 10213 else { 10214 Statements.push_back(Return.getAs<Stmt>()); 10215 10216 if (Trap.hasErrorOccurred()) { 10217 Diag(CurrentLocation, diag::note_member_synthesized_at) 10218 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10219 Invalid = true; 10220 } 10221 } 10222 } 10223 10224 if (Invalid) { 10225 MoveAssignOperator->setInvalidDecl(); 10226 return; 10227 } 10228 10229 StmtResult Body; 10230 { 10231 CompoundScopeRAII CompoundScope(*this); 10232 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10233 /*isStmtExpr=*/false); 10234 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10235 } 10236 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10237 10238 if (ASTMutationListener *L = getASTMutationListener()) { 10239 L->CompletedImplicitDefinition(MoveAssignOperator); 10240 } 10241 } 10242 10243 Sema::ImplicitExceptionSpecification 10244 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10245 CXXRecordDecl *ClassDecl = MD->getParent(); 10246 10247 ImplicitExceptionSpecification ExceptSpec(*this); 10248 if (ClassDecl->isInvalidDecl()) 10249 return ExceptSpec; 10250 10251 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10252 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10253 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10254 10255 // C++ [except.spec]p14: 10256 // An implicitly declared special member function (Clause 12) shall have an 10257 // exception-specification. [...] 10258 for (const auto &Base : ClassDecl->bases()) { 10259 // Virtual bases are handled below. 10260 if (Base.isVirtual()) 10261 continue; 10262 10263 CXXRecordDecl *BaseClassDecl 10264 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10265 if (CXXConstructorDecl *CopyConstructor = 10266 LookupCopyingConstructor(BaseClassDecl, Quals)) 10267 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10268 } 10269 for (const auto &Base : ClassDecl->vbases()) { 10270 CXXRecordDecl *BaseClassDecl 10271 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10272 if (CXXConstructorDecl *CopyConstructor = 10273 LookupCopyingConstructor(BaseClassDecl, Quals)) 10274 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10275 } 10276 for (const auto *Field : ClassDecl->fields()) { 10277 QualType FieldType = Context.getBaseElementType(Field->getType()); 10278 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10279 if (CXXConstructorDecl *CopyConstructor = 10280 LookupCopyingConstructor(FieldClassDecl, 10281 Quals | FieldType.getCVRQualifiers())) 10282 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10283 } 10284 } 10285 10286 return ExceptSpec; 10287 } 10288 10289 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10290 CXXRecordDecl *ClassDecl) { 10291 // C++ [class.copy]p4: 10292 // If the class definition does not explicitly declare a copy 10293 // constructor, one is declared implicitly. 10294 assert(ClassDecl->needsImplicitCopyConstructor()); 10295 10296 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10297 if (DSM.isAlreadyBeingDeclared()) 10298 return nullptr; 10299 10300 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10301 QualType ArgType = ClassType; 10302 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10303 if (Const) 10304 ArgType = ArgType.withConst(); 10305 ArgType = Context.getLValueReferenceType(ArgType); 10306 10307 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10308 CXXCopyConstructor, 10309 Const); 10310 10311 DeclarationName Name 10312 = Context.DeclarationNames.getCXXConstructorName( 10313 Context.getCanonicalType(ClassType)); 10314 SourceLocation ClassLoc = ClassDecl->getLocation(); 10315 DeclarationNameInfo NameInfo(Name, ClassLoc); 10316 10317 // An implicitly-declared copy constructor is an inline public 10318 // member of its class. 10319 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10320 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10321 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10322 Constexpr); 10323 CopyConstructor->setAccess(AS_public); 10324 CopyConstructor->setDefaulted(); 10325 10326 // Build an exception specification pointing back at this member. 10327 FunctionProtoType::ExtProtoInfo EPI = 10328 getImplicitMethodEPI(*this, CopyConstructor); 10329 CopyConstructor->setType( 10330 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10331 10332 // Add the parameter to the constructor. 10333 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10334 ClassLoc, ClassLoc, 10335 /*IdentifierInfo=*/nullptr, 10336 ArgType, /*TInfo=*/nullptr, 10337 SC_None, nullptr); 10338 CopyConstructor->setParams(FromParam); 10339 10340 CopyConstructor->setTrivial( 10341 ClassDecl->needsOverloadResolutionForCopyConstructor() 10342 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10343 : ClassDecl->hasTrivialCopyConstructor()); 10344 10345 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10346 SetDeclDeleted(CopyConstructor, ClassLoc); 10347 10348 // Note that we have declared this constructor. 10349 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10350 10351 if (Scope *S = getScopeForContext(ClassDecl)) 10352 PushOnScopeChains(CopyConstructor, S, false); 10353 ClassDecl->addDecl(CopyConstructor); 10354 10355 return CopyConstructor; 10356 } 10357 10358 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10359 CXXConstructorDecl *CopyConstructor) { 10360 assert((CopyConstructor->isDefaulted() && 10361 CopyConstructor->isCopyConstructor() && 10362 !CopyConstructor->doesThisDeclarationHaveABody() && 10363 !CopyConstructor->isDeleted()) && 10364 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10365 10366 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10367 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10368 10369 // C++11 [class.copy]p7: 10370 // The [definition of an implicitly declared copy constructor] is 10371 // deprecated if the class has a user-declared copy assignment operator 10372 // or a user-declared destructor. 10373 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10374 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10375 10376 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10377 DiagnosticErrorTrap Trap(Diags); 10378 10379 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10380 Trap.hasErrorOccurred()) { 10381 Diag(CurrentLocation, diag::note_member_synthesized_at) 10382 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10383 CopyConstructor->setInvalidDecl(); 10384 } else { 10385 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10386 ? CopyConstructor->getLocEnd() 10387 : CopyConstructor->getLocation(); 10388 Sema::CompoundScopeRAII CompoundScope(*this); 10389 CopyConstructor->setBody( 10390 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10391 } 10392 10393 CopyConstructor->markUsed(Context); 10394 MarkVTableUsed(CurrentLocation, ClassDecl); 10395 10396 if (ASTMutationListener *L = getASTMutationListener()) { 10397 L->CompletedImplicitDefinition(CopyConstructor); 10398 } 10399 } 10400 10401 Sema::ImplicitExceptionSpecification 10402 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10403 CXXRecordDecl *ClassDecl = MD->getParent(); 10404 10405 // C++ [except.spec]p14: 10406 // An implicitly declared special member function (Clause 12) shall have an 10407 // exception-specification. [...] 10408 ImplicitExceptionSpecification ExceptSpec(*this); 10409 if (ClassDecl->isInvalidDecl()) 10410 return ExceptSpec; 10411 10412 // Direct base-class constructors. 10413 for (const auto &B : ClassDecl->bases()) { 10414 if (B.isVirtual()) // Handled below. 10415 continue; 10416 10417 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10418 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10419 CXXConstructorDecl *Constructor = 10420 LookupMovingConstructor(BaseClassDecl, 0); 10421 // If this is a deleted function, add it anyway. This might be conformant 10422 // with the standard. This might not. I'm not sure. It might not matter. 10423 if (Constructor) 10424 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10425 } 10426 } 10427 10428 // Virtual base-class constructors. 10429 for (const auto &B : ClassDecl->vbases()) { 10430 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10431 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10432 CXXConstructorDecl *Constructor = 10433 LookupMovingConstructor(BaseClassDecl, 0); 10434 // If this is a deleted function, add it anyway. This might be conformant 10435 // with the standard. This might not. I'm not sure. It might not matter. 10436 if (Constructor) 10437 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10438 } 10439 } 10440 10441 // Field constructors. 10442 for (const auto *F : ClassDecl->fields()) { 10443 QualType FieldType = Context.getBaseElementType(F->getType()); 10444 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10445 CXXConstructorDecl *Constructor = 10446 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10447 // If this is a deleted function, add it anyway. This might be conformant 10448 // with the standard. This might not. I'm not sure. It might not matter. 10449 // In particular, the problem is that this function never gets called. It 10450 // might just be ill-formed because this function attempts to refer to 10451 // a deleted function here. 10452 if (Constructor) 10453 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10454 } 10455 } 10456 10457 return ExceptSpec; 10458 } 10459 10460 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10461 CXXRecordDecl *ClassDecl) { 10462 assert(ClassDecl->needsImplicitMoveConstructor()); 10463 10464 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10465 if (DSM.isAlreadyBeingDeclared()) 10466 return nullptr; 10467 10468 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10469 QualType ArgType = Context.getRValueReferenceType(ClassType); 10470 10471 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10472 CXXMoveConstructor, 10473 false); 10474 10475 DeclarationName Name 10476 = Context.DeclarationNames.getCXXConstructorName( 10477 Context.getCanonicalType(ClassType)); 10478 SourceLocation ClassLoc = ClassDecl->getLocation(); 10479 DeclarationNameInfo NameInfo(Name, ClassLoc); 10480 10481 // C++11 [class.copy]p11: 10482 // An implicitly-declared copy/move constructor is an inline public 10483 // member of its class. 10484 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10485 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10486 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10487 Constexpr); 10488 MoveConstructor->setAccess(AS_public); 10489 MoveConstructor->setDefaulted(); 10490 10491 // Build an exception specification pointing back at this member. 10492 FunctionProtoType::ExtProtoInfo EPI = 10493 getImplicitMethodEPI(*this, MoveConstructor); 10494 MoveConstructor->setType( 10495 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10496 10497 // Add the parameter to the constructor. 10498 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10499 ClassLoc, ClassLoc, 10500 /*IdentifierInfo=*/nullptr, 10501 ArgType, /*TInfo=*/nullptr, 10502 SC_None, nullptr); 10503 MoveConstructor->setParams(FromParam); 10504 10505 MoveConstructor->setTrivial( 10506 ClassDecl->needsOverloadResolutionForMoveConstructor() 10507 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10508 : ClassDecl->hasTrivialMoveConstructor()); 10509 10510 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10511 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10512 SetDeclDeleted(MoveConstructor, ClassLoc); 10513 } 10514 10515 // Note that we have declared this constructor. 10516 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10517 10518 if (Scope *S = getScopeForContext(ClassDecl)) 10519 PushOnScopeChains(MoveConstructor, S, false); 10520 ClassDecl->addDecl(MoveConstructor); 10521 10522 return MoveConstructor; 10523 } 10524 10525 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10526 CXXConstructorDecl *MoveConstructor) { 10527 assert((MoveConstructor->isDefaulted() && 10528 MoveConstructor->isMoveConstructor() && 10529 !MoveConstructor->doesThisDeclarationHaveABody() && 10530 !MoveConstructor->isDeleted()) && 10531 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10532 10533 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10534 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10535 10536 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10537 DiagnosticErrorTrap Trap(Diags); 10538 10539 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10540 Trap.hasErrorOccurred()) { 10541 Diag(CurrentLocation, diag::note_member_synthesized_at) 10542 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10543 MoveConstructor->setInvalidDecl(); 10544 } else { 10545 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10546 ? MoveConstructor->getLocEnd() 10547 : MoveConstructor->getLocation(); 10548 Sema::CompoundScopeRAII CompoundScope(*this); 10549 MoveConstructor->setBody(ActOnCompoundStmt( 10550 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10551 } 10552 10553 MoveConstructor->markUsed(Context); 10554 MarkVTableUsed(CurrentLocation, ClassDecl); 10555 10556 if (ASTMutationListener *L = getASTMutationListener()) { 10557 L->CompletedImplicitDefinition(MoveConstructor); 10558 } 10559 } 10560 10561 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10562 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10563 } 10564 10565 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10566 SourceLocation CurrentLocation, 10567 CXXConversionDecl *Conv) { 10568 CXXRecordDecl *Lambda = Conv->getParent(); 10569 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10570 // If we are defining a specialization of a conversion to function-ptr 10571 // cache the deduced template arguments for this specialization 10572 // so that we can use them to retrieve the corresponding call-operator 10573 // and static-invoker. 10574 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10575 10576 // Retrieve the corresponding call-operator specialization. 10577 if (Lambda->isGenericLambda()) { 10578 assert(Conv->isFunctionTemplateSpecialization()); 10579 FunctionTemplateDecl *CallOpTemplate = 10580 CallOp->getDescribedFunctionTemplate(); 10581 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10582 void *InsertPos = nullptr; 10583 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10584 DeducedTemplateArgs->asArray(), 10585 InsertPos); 10586 assert(CallOpSpec && 10587 "Conversion operator must have a corresponding call operator"); 10588 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10589 } 10590 // Mark the call operator referenced (and add to pending instantiations 10591 // if necessary). 10592 // For both the conversion and static-invoker template specializations 10593 // we construct their body's in this function, so no need to add them 10594 // to the PendingInstantiations. 10595 MarkFunctionReferenced(CurrentLocation, CallOp); 10596 10597 SynthesizedFunctionScope Scope(*this, Conv); 10598 DiagnosticErrorTrap Trap(Diags); 10599 10600 // Retrieve the static invoker... 10601 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10602 // ... and get the corresponding specialization for a generic lambda. 10603 if (Lambda->isGenericLambda()) { 10604 assert(DeducedTemplateArgs && 10605 "Must have deduced template arguments from Conversion Operator"); 10606 FunctionTemplateDecl *InvokeTemplate = 10607 Invoker->getDescribedFunctionTemplate(); 10608 void *InsertPos = nullptr; 10609 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10610 DeducedTemplateArgs->asArray(), 10611 InsertPos); 10612 assert(InvokeSpec && 10613 "Must have a corresponding static invoker specialization"); 10614 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10615 } 10616 // Construct the body of the conversion function { return __invoke; }. 10617 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10618 VK_LValue, Conv->getLocation()).get(); 10619 assert(FunctionRef && "Can't refer to __invoke function?"); 10620 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10621 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10622 Conv->getLocation(), 10623 Conv->getLocation())); 10624 10625 Conv->markUsed(Context); 10626 Conv->setReferenced(); 10627 10628 // Fill in the __invoke function with a dummy implementation. IR generation 10629 // will fill in the actual details. 10630 Invoker->markUsed(Context); 10631 Invoker->setReferenced(); 10632 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10633 10634 if (ASTMutationListener *L = getASTMutationListener()) { 10635 L->CompletedImplicitDefinition(Conv); 10636 L->CompletedImplicitDefinition(Invoker); 10637 } 10638 } 10639 10640 10641 10642 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10643 SourceLocation CurrentLocation, 10644 CXXConversionDecl *Conv) 10645 { 10646 assert(!Conv->getParent()->isGenericLambda()); 10647 10648 Conv->markUsed(Context); 10649 10650 SynthesizedFunctionScope Scope(*this, Conv); 10651 DiagnosticErrorTrap Trap(Diags); 10652 10653 // Copy-initialize the lambda object as needed to capture it. 10654 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10655 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10656 10657 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10658 Conv->getLocation(), 10659 Conv, DerefThis); 10660 10661 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10662 // behavior. Note that only the general conversion function does this 10663 // (since it's unusable otherwise); in the case where we inline the 10664 // block literal, it has block literal lifetime semantics. 10665 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10666 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10667 CK_CopyAndAutoreleaseBlockObject, 10668 BuildBlock.get(), nullptr, VK_RValue); 10669 10670 if (BuildBlock.isInvalid()) { 10671 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10672 Conv->setInvalidDecl(); 10673 return; 10674 } 10675 10676 // Create the return statement that returns the block from the conversion 10677 // function. 10678 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 10679 if (Return.isInvalid()) { 10680 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10681 Conv->setInvalidDecl(); 10682 return; 10683 } 10684 10685 // Set the body of the conversion function. 10686 Stmt *ReturnS = Return.get(); 10687 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10688 Conv->getLocation(), 10689 Conv->getLocation())); 10690 10691 // We're done; notify the mutation listener, if any. 10692 if (ASTMutationListener *L = getASTMutationListener()) { 10693 L->CompletedImplicitDefinition(Conv); 10694 } 10695 } 10696 10697 /// \brief Determine whether the given list arguments contains exactly one 10698 /// "real" (non-default) argument. 10699 static bool hasOneRealArgument(MultiExprArg Args) { 10700 switch (Args.size()) { 10701 case 0: 10702 return false; 10703 10704 default: 10705 if (!Args[1]->isDefaultArgument()) 10706 return false; 10707 10708 // fall through 10709 case 1: 10710 return !Args[0]->isDefaultArgument(); 10711 } 10712 10713 return false; 10714 } 10715 10716 ExprResult 10717 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10718 CXXConstructorDecl *Constructor, 10719 MultiExprArg ExprArgs, 10720 bool HadMultipleCandidates, 10721 bool IsListInitialization, 10722 bool IsStdInitListInitialization, 10723 bool RequiresZeroInit, 10724 unsigned ConstructKind, 10725 SourceRange ParenRange) { 10726 bool Elidable = false; 10727 10728 // C++0x [class.copy]p34: 10729 // When certain criteria are met, an implementation is allowed to 10730 // omit the copy/move construction of a class object, even if the 10731 // copy/move constructor and/or destructor for the object have 10732 // side effects. [...] 10733 // - when a temporary class object that has not been bound to a 10734 // reference (12.2) would be copied/moved to a class object 10735 // with the same cv-unqualified type, the copy/move operation 10736 // can be omitted by constructing the temporary object 10737 // directly into the target of the omitted copy/move 10738 if (ConstructKind == CXXConstructExpr::CK_Complete && 10739 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10740 Expr *SubExpr = ExprArgs[0]; 10741 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10742 } 10743 10744 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10745 Elidable, ExprArgs, HadMultipleCandidates, 10746 IsListInitialization, 10747 IsStdInitListInitialization, RequiresZeroInit, 10748 ConstructKind, ParenRange); 10749 } 10750 10751 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10752 /// including handling of its default argument expressions. 10753 ExprResult 10754 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10755 CXXConstructorDecl *Constructor, bool Elidable, 10756 MultiExprArg ExprArgs, 10757 bool HadMultipleCandidates, 10758 bool IsListInitialization, 10759 bool IsStdInitListInitialization, 10760 bool RequiresZeroInit, 10761 unsigned ConstructKind, 10762 SourceRange ParenRange) { 10763 MarkFunctionReferenced(ConstructLoc, Constructor); 10764 return CXXConstructExpr::Create( 10765 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 10766 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 10767 RequiresZeroInit, 10768 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10769 ParenRange); 10770 } 10771 10772 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10773 if (VD->isInvalidDecl()) return; 10774 10775 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10776 if (ClassDecl->isInvalidDecl()) return; 10777 if (ClassDecl->hasIrrelevantDestructor()) return; 10778 if (ClassDecl->isDependentContext()) return; 10779 10780 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10781 MarkFunctionReferenced(VD->getLocation(), Destructor); 10782 CheckDestructorAccess(VD->getLocation(), Destructor, 10783 PDiag(diag::err_access_dtor_var) 10784 << VD->getDeclName() 10785 << VD->getType()); 10786 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10787 10788 if (Destructor->isTrivial()) return; 10789 if (!VD->hasGlobalStorage()) return; 10790 10791 // Emit warning for non-trivial dtor in global scope (a real global, 10792 // class-static, function-static). 10793 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10794 10795 // TODO: this should be re-enabled for static locals by !CXAAtExit 10796 if (!VD->isStaticLocal()) 10797 Diag(VD->getLocation(), diag::warn_global_destructor); 10798 } 10799 10800 /// \brief Given a constructor and the set of arguments provided for the 10801 /// constructor, convert the arguments and add any required default arguments 10802 /// to form a proper call to this constructor. 10803 /// 10804 /// \returns true if an error occurred, false otherwise. 10805 bool 10806 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10807 MultiExprArg ArgsPtr, 10808 SourceLocation Loc, 10809 SmallVectorImpl<Expr*> &ConvertedArgs, 10810 bool AllowExplicit, 10811 bool IsListInitialization) { 10812 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10813 unsigned NumArgs = ArgsPtr.size(); 10814 Expr **Args = ArgsPtr.data(); 10815 10816 const FunctionProtoType *Proto 10817 = Constructor->getType()->getAs<FunctionProtoType>(); 10818 assert(Proto && "Constructor without a prototype?"); 10819 unsigned NumParams = Proto->getNumParams(); 10820 10821 // If too few arguments are available, we'll fill in the rest with defaults. 10822 if (NumArgs < NumParams) 10823 ConvertedArgs.reserve(NumParams); 10824 else 10825 ConvertedArgs.reserve(NumArgs); 10826 10827 VariadicCallType CallType = 10828 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10829 SmallVector<Expr *, 8> AllArgs; 10830 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10831 Proto, 0, 10832 llvm::makeArrayRef(Args, NumArgs), 10833 AllArgs, 10834 CallType, AllowExplicit, 10835 IsListInitialization); 10836 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10837 10838 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10839 10840 CheckConstructorCall(Constructor, 10841 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10842 AllArgs.size()), 10843 Proto, Loc); 10844 10845 return Invalid; 10846 } 10847 10848 static inline bool 10849 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10850 const FunctionDecl *FnDecl) { 10851 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10852 if (isa<NamespaceDecl>(DC)) { 10853 return SemaRef.Diag(FnDecl->getLocation(), 10854 diag::err_operator_new_delete_declared_in_namespace) 10855 << FnDecl->getDeclName(); 10856 } 10857 10858 if (isa<TranslationUnitDecl>(DC) && 10859 FnDecl->getStorageClass() == SC_Static) { 10860 return SemaRef.Diag(FnDecl->getLocation(), 10861 diag::err_operator_new_delete_declared_static) 10862 << FnDecl->getDeclName(); 10863 } 10864 10865 return false; 10866 } 10867 10868 static inline bool 10869 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10870 CanQualType ExpectedResultType, 10871 CanQualType ExpectedFirstParamType, 10872 unsigned DependentParamTypeDiag, 10873 unsigned InvalidParamTypeDiag) { 10874 QualType ResultType = 10875 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10876 10877 // Check that the result type is not dependent. 10878 if (ResultType->isDependentType()) 10879 return SemaRef.Diag(FnDecl->getLocation(), 10880 diag::err_operator_new_delete_dependent_result_type) 10881 << FnDecl->getDeclName() << ExpectedResultType; 10882 10883 // Check that the result type is what we expect. 10884 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10885 return SemaRef.Diag(FnDecl->getLocation(), 10886 diag::err_operator_new_delete_invalid_result_type) 10887 << FnDecl->getDeclName() << ExpectedResultType; 10888 10889 // A function template must have at least 2 parameters. 10890 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10891 return SemaRef.Diag(FnDecl->getLocation(), 10892 diag::err_operator_new_delete_template_too_few_parameters) 10893 << FnDecl->getDeclName(); 10894 10895 // The function decl must have at least 1 parameter. 10896 if (FnDecl->getNumParams() == 0) 10897 return SemaRef.Diag(FnDecl->getLocation(), 10898 diag::err_operator_new_delete_too_few_parameters) 10899 << FnDecl->getDeclName(); 10900 10901 // Check the first parameter type is not dependent. 10902 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10903 if (FirstParamType->isDependentType()) 10904 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10905 << FnDecl->getDeclName() << ExpectedFirstParamType; 10906 10907 // Check that the first parameter type is what we expect. 10908 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10909 ExpectedFirstParamType) 10910 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10911 << FnDecl->getDeclName() << ExpectedFirstParamType; 10912 10913 return false; 10914 } 10915 10916 static bool 10917 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10918 // C++ [basic.stc.dynamic.allocation]p1: 10919 // A program is ill-formed if an allocation function is declared in a 10920 // namespace scope other than global scope or declared static in global 10921 // scope. 10922 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10923 return true; 10924 10925 CanQualType SizeTy = 10926 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10927 10928 // C++ [basic.stc.dynamic.allocation]p1: 10929 // The return type shall be void*. The first parameter shall have type 10930 // std::size_t. 10931 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10932 SizeTy, 10933 diag::err_operator_new_dependent_param_type, 10934 diag::err_operator_new_param_type)) 10935 return true; 10936 10937 // C++ [basic.stc.dynamic.allocation]p1: 10938 // The first parameter shall not have an associated default argument. 10939 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10940 return SemaRef.Diag(FnDecl->getLocation(), 10941 diag::err_operator_new_default_arg) 10942 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10943 10944 return false; 10945 } 10946 10947 static bool 10948 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10949 // C++ [basic.stc.dynamic.deallocation]p1: 10950 // A program is ill-formed if deallocation functions are declared in a 10951 // namespace scope other than global scope or declared static in global 10952 // scope. 10953 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10954 return true; 10955 10956 // C++ [basic.stc.dynamic.deallocation]p2: 10957 // Each deallocation function shall return void and its first parameter 10958 // shall be void*. 10959 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10960 SemaRef.Context.VoidPtrTy, 10961 diag::err_operator_delete_dependent_param_type, 10962 diag::err_operator_delete_param_type)) 10963 return true; 10964 10965 return false; 10966 } 10967 10968 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10969 /// of this overloaded operator is well-formed. If so, returns false; 10970 /// otherwise, emits appropriate diagnostics and returns true. 10971 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10972 assert(FnDecl && FnDecl->isOverloadedOperator() && 10973 "Expected an overloaded operator declaration"); 10974 10975 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10976 10977 // C++ [over.oper]p5: 10978 // The allocation and deallocation functions, operator new, 10979 // operator new[], operator delete and operator delete[], are 10980 // described completely in 3.7.3. The attributes and restrictions 10981 // found in the rest of this subclause do not apply to them unless 10982 // explicitly stated in 3.7.3. 10983 if (Op == OO_Delete || Op == OO_Array_Delete) 10984 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10985 10986 if (Op == OO_New || Op == OO_Array_New) 10987 return CheckOperatorNewDeclaration(*this, FnDecl); 10988 10989 // C++ [over.oper]p6: 10990 // An operator function shall either be a non-static member 10991 // function or be a non-member function and have at least one 10992 // parameter whose type is a class, a reference to a class, an 10993 // enumeration, or a reference to an enumeration. 10994 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10995 if (MethodDecl->isStatic()) 10996 return Diag(FnDecl->getLocation(), 10997 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10998 } else { 10999 bool ClassOrEnumParam = false; 11000 for (auto Param : FnDecl->params()) { 11001 QualType ParamType = Param->getType().getNonReferenceType(); 11002 if (ParamType->isDependentType() || ParamType->isRecordType() || 11003 ParamType->isEnumeralType()) { 11004 ClassOrEnumParam = true; 11005 break; 11006 } 11007 } 11008 11009 if (!ClassOrEnumParam) 11010 return Diag(FnDecl->getLocation(), 11011 diag::err_operator_overload_needs_class_or_enum) 11012 << FnDecl->getDeclName(); 11013 } 11014 11015 // C++ [over.oper]p8: 11016 // An operator function cannot have default arguments (8.3.6), 11017 // except where explicitly stated below. 11018 // 11019 // Only the function-call operator allows default arguments 11020 // (C++ [over.call]p1). 11021 if (Op != OO_Call) { 11022 for (auto Param : FnDecl->params()) { 11023 if (Param->hasDefaultArg()) 11024 return Diag(Param->getLocation(), 11025 diag::err_operator_overload_default_arg) 11026 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11027 } 11028 } 11029 11030 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11031 { false, false, false } 11032 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11033 , { Unary, Binary, MemberOnly } 11034 #include "clang/Basic/OperatorKinds.def" 11035 }; 11036 11037 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11038 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11039 bool MustBeMemberOperator = OperatorUses[Op][2]; 11040 11041 // C++ [over.oper]p8: 11042 // [...] Operator functions cannot have more or fewer parameters 11043 // than the number required for the corresponding operator, as 11044 // described in the rest of this subclause. 11045 unsigned NumParams = FnDecl->getNumParams() 11046 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11047 if (Op != OO_Call && 11048 ((NumParams == 1 && !CanBeUnaryOperator) || 11049 (NumParams == 2 && !CanBeBinaryOperator) || 11050 (NumParams < 1) || (NumParams > 2))) { 11051 // We have the wrong number of parameters. 11052 unsigned ErrorKind; 11053 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11054 ErrorKind = 2; // 2 -> unary or binary. 11055 } else if (CanBeUnaryOperator) { 11056 ErrorKind = 0; // 0 -> unary 11057 } else { 11058 assert(CanBeBinaryOperator && 11059 "All non-call overloaded operators are unary or binary!"); 11060 ErrorKind = 1; // 1 -> binary 11061 } 11062 11063 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11064 << FnDecl->getDeclName() << NumParams << ErrorKind; 11065 } 11066 11067 // Overloaded operators other than operator() cannot be variadic. 11068 if (Op != OO_Call && 11069 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11070 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11071 << FnDecl->getDeclName(); 11072 } 11073 11074 // Some operators must be non-static member functions. 11075 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11076 return Diag(FnDecl->getLocation(), 11077 diag::err_operator_overload_must_be_member) 11078 << FnDecl->getDeclName(); 11079 } 11080 11081 // C++ [over.inc]p1: 11082 // The user-defined function called operator++ implements the 11083 // prefix and postfix ++ operator. If this function is a member 11084 // function with no parameters, or a non-member function with one 11085 // parameter of class or enumeration type, it defines the prefix 11086 // increment operator ++ for objects of that type. If the function 11087 // is a member function with one parameter (which shall be of type 11088 // int) or a non-member function with two parameters (the second 11089 // of which shall be of type int), it defines the postfix 11090 // increment operator ++ for objects of that type. 11091 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11092 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11093 QualType ParamType = LastParam->getType(); 11094 11095 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11096 !ParamType->isDependentType()) 11097 return Diag(LastParam->getLocation(), 11098 diag::err_operator_overload_post_incdec_must_be_int) 11099 << LastParam->getType() << (Op == OO_MinusMinus); 11100 } 11101 11102 return false; 11103 } 11104 11105 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11106 /// of this literal operator function is well-formed. If so, returns 11107 /// false; otherwise, emits appropriate diagnostics and returns true. 11108 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11109 if (isa<CXXMethodDecl>(FnDecl)) { 11110 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11111 << FnDecl->getDeclName(); 11112 return true; 11113 } 11114 11115 if (FnDecl->isExternC()) { 11116 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11117 return true; 11118 } 11119 11120 bool Valid = false; 11121 11122 // This might be the definition of a literal operator template. 11123 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11124 // This might be a specialization of a literal operator template. 11125 if (!TpDecl) 11126 TpDecl = FnDecl->getPrimaryTemplate(); 11127 11128 // template <char...> type operator "" name() and 11129 // template <class T, T...> type operator "" name() are the only valid 11130 // template signatures, and the only valid signatures with no parameters. 11131 if (TpDecl) { 11132 if (FnDecl->param_size() == 0) { 11133 // Must have one or two template parameters 11134 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11135 if (Params->size() == 1) { 11136 NonTypeTemplateParmDecl *PmDecl = 11137 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11138 11139 // The template parameter must be a char parameter pack. 11140 if (PmDecl && PmDecl->isTemplateParameterPack() && 11141 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11142 Valid = true; 11143 } else if (Params->size() == 2) { 11144 TemplateTypeParmDecl *PmType = 11145 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11146 NonTypeTemplateParmDecl *PmArgs = 11147 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11148 11149 // The second template parameter must be a parameter pack with the 11150 // first template parameter as its type. 11151 if (PmType && PmArgs && 11152 !PmType->isTemplateParameterPack() && 11153 PmArgs->isTemplateParameterPack()) { 11154 const TemplateTypeParmType *TArgs = 11155 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11156 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11157 TArgs->getIndex() == PmType->getIndex()) { 11158 Valid = true; 11159 if (ActiveTemplateInstantiations.empty()) 11160 Diag(FnDecl->getLocation(), 11161 diag::ext_string_literal_operator_template); 11162 } 11163 } 11164 } 11165 } 11166 } else if (FnDecl->param_size()) { 11167 // Check the first parameter 11168 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11169 11170 QualType T = (*Param)->getType().getUnqualifiedType(); 11171 11172 // unsigned long long int, long double, and any character type are allowed 11173 // as the only parameters. 11174 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11175 Context.hasSameType(T, Context.LongDoubleTy) || 11176 Context.hasSameType(T, Context.CharTy) || 11177 Context.hasSameType(T, Context.WideCharTy) || 11178 Context.hasSameType(T, Context.Char16Ty) || 11179 Context.hasSameType(T, Context.Char32Ty)) { 11180 if (++Param == FnDecl->param_end()) 11181 Valid = true; 11182 goto FinishedParams; 11183 } 11184 11185 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11186 const PointerType *PT = T->getAs<PointerType>(); 11187 if (!PT) 11188 goto FinishedParams; 11189 T = PT->getPointeeType(); 11190 if (!T.isConstQualified() || T.isVolatileQualified()) 11191 goto FinishedParams; 11192 T = T.getUnqualifiedType(); 11193 11194 // Move on to the second parameter; 11195 ++Param; 11196 11197 // If there is no second parameter, the first must be a const char * 11198 if (Param == FnDecl->param_end()) { 11199 if (Context.hasSameType(T, Context.CharTy)) 11200 Valid = true; 11201 goto FinishedParams; 11202 } 11203 11204 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11205 // are allowed as the first parameter to a two-parameter function 11206 if (!(Context.hasSameType(T, Context.CharTy) || 11207 Context.hasSameType(T, Context.WideCharTy) || 11208 Context.hasSameType(T, Context.Char16Ty) || 11209 Context.hasSameType(T, Context.Char32Ty))) 11210 goto FinishedParams; 11211 11212 // The second and final parameter must be an std::size_t 11213 T = (*Param)->getType().getUnqualifiedType(); 11214 if (Context.hasSameType(T, Context.getSizeType()) && 11215 ++Param == FnDecl->param_end()) 11216 Valid = true; 11217 } 11218 11219 // FIXME: This diagnostic is absolutely terrible. 11220 FinishedParams: 11221 if (!Valid) { 11222 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11223 << FnDecl->getDeclName(); 11224 return true; 11225 } 11226 11227 // A parameter-declaration-clause containing a default argument is not 11228 // equivalent to any of the permitted forms. 11229 for (auto Param : FnDecl->params()) { 11230 if (Param->hasDefaultArg()) { 11231 Diag(Param->getDefaultArgRange().getBegin(), 11232 diag::err_literal_operator_default_argument) 11233 << Param->getDefaultArgRange(); 11234 break; 11235 } 11236 } 11237 11238 StringRef LiteralName 11239 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11240 if (LiteralName[0] != '_') { 11241 // C++11 [usrlit.suffix]p1: 11242 // Literal suffix identifiers that do not start with an underscore 11243 // are reserved for future standardization. 11244 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11245 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11246 } 11247 11248 return false; 11249 } 11250 11251 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11252 /// linkage specification, including the language and (if present) 11253 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11254 /// language string literal. LBraceLoc, if valid, provides the location of 11255 /// the '{' brace. Otherwise, this linkage specification does not 11256 /// have any braces. 11257 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11258 Expr *LangStr, 11259 SourceLocation LBraceLoc) { 11260 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11261 if (!Lit->isAscii()) { 11262 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11263 << LangStr->getSourceRange(); 11264 return nullptr; 11265 } 11266 11267 StringRef Lang = Lit->getString(); 11268 LinkageSpecDecl::LanguageIDs Language; 11269 if (Lang == "C") 11270 Language = LinkageSpecDecl::lang_c; 11271 else if (Lang == "C++") 11272 Language = LinkageSpecDecl::lang_cxx; 11273 else { 11274 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11275 << LangStr->getSourceRange(); 11276 return nullptr; 11277 } 11278 11279 // FIXME: Add all the various semantics of linkage specifications 11280 11281 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11282 LangStr->getExprLoc(), Language, 11283 LBraceLoc.isValid()); 11284 CurContext->addDecl(D); 11285 PushDeclContext(S, D); 11286 return D; 11287 } 11288 11289 /// ActOnFinishLinkageSpecification - Complete the definition of 11290 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11291 /// valid, it's the position of the closing '}' brace in a linkage 11292 /// specification that uses braces. 11293 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11294 Decl *LinkageSpec, 11295 SourceLocation RBraceLoc) { 11296 if (RBraceLoc.isValid()) { 11297 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11298 LSDecl->setRBraceLoc(RBraceLoc); 11299 } 11300 PopDeclContext(); 11301 return LinkageSpec; 11302 } 11303 11304 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11305 AttributeList *AttrList, 11306 SourceLocation SemiLoc) { 11307 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11308 // Attribute declarations appertain to empty declaration so we handle 11309 // them here. 11310 if (AttrList) 11311 ProcessDeclAttributeList(S, ED, AttrList); 11312 11313 CurContext->addDecl(ED); 11314 return ED; 11315 } 11316 11317 /// \brief Perform semantic analysis for the variable declaration that 11318 /// occurs within a C++ catch clause, returning the newly-created 11319 /// variable. 11320 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11321 TypeSourceInfo *TInfo, 11322 SourceLocation StartLoc, 11323 SourceLocation Loc, 11324 IdentifierInfo *Name) { 11325 bool Invalid = false; 11326 QualType ExDeclType = TInfo->getType(); 11327 11328 // Arrays and functions decay. 11329 if (ExDeclType->isArrayType()) 11330 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11331 else if (ExDeclType->isFunctionType()) 11332 ExDeclType = Context.getPointerType(ExDeclType); 11333 11334 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11335 // The exception-declaration shall not denote a pointer or reference to an 11336 // incomplete type, other than [cv] void*. 11337 // N2844 forbids rvalue references. 11338 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11339 Diag(Loc, diag::err_catch_rvalue_ref); 11340 Invalid = true; 11341 } 11342 11343 QualType BaseType = ExDeclType; 11344 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11345 unsigned DK = diag::err_catch_incomplete; 11346 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11347 BaseType = Ptr->getPointeeType(); 11348 Mode = 1; 11349 DK = diag::err_catch_incomplete_ptr; 11350 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11351 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11352 BaseType = Ref->getPointeeType(); 11353 Mode = 2; 11354 DK = diag::err_catch_incomplete_ref; 11355 } 11356 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11357 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11358 Invalid = true; 11359 11360 if (!Invalid && !ExDeclType->isDependentType() && 11361 RequireNonAbstractType(Loc, ExDeclType, 11362 diag::err_abstract_type_in_decl, 11363 AbstractVariableType)) 11364 Invalid = true; 11365 11366 // Only the non-fragile NeXT runtime currently supports C++ catches 11367 // of ObjC types, and no runtime supports catching ObjC types by value. 11368 if (!Invalid && getLangOpts().ObjC1) { 11369 QualType T = ExDeclType; 11370 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11371 T = RT->getPointeeType(); 11372 11373 if (T->isObjCObjectType()) { 11374 Diag(Loc, diag::err_objc_object_catch); 11375 Invalid = true; 11376 } else if (T->isObjCObjectPointerType()) { 11377 // FIXME: should this be a test for macosx-fragile specifically? 11378 if (getLangOpts().ObjCRuntime.isFragile()) 11379 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11380 } 11381 } 11382 11383 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11384 ExDeclType, TInfo, SC_None); 11385 ExDecl->setExceptionVariable(true); 11386 11387 // In ARC, infer 'retaining' for variables of retainable type. 11388 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11389 Invalid = true; 11390 11391 if (!Invalid && !ExDeclType->isDependentType()) { 11392 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11393 // Insulate this from anything else we might currently be parsing. 11394 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11395 11396 // C++ [except.handle]p16: 11397 // The object declared in an exception-declaration or, if the 11398 // exception-declaration does not specify a name, a temporary (12.2) is 11399 // copy-initialized (8.5) from the exception object. [...] 11400 // The object is destroyed when the handler exits, after the destruction 11401 // of any automatic objects initialized within the handler. 11402 // 11403 // We just pretend to initialize the object with itself, then make sure 11404 // it can be destroyed later. 11405 QualType initType = ExDeclType; 11406 11407 InitializedEntity entity = 11408 InitializedEntity::InitializeVariable(ExDecl); 11409 InitializationKind initKind = 11410 InitializationKind::CreateCopy(Loc, SourceLocation()); 11411 11412 Expr *opaqueValue = 11413 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11414 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11415 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11416 if (result.isInvalid()) 11417 Invalid = true; 11418 else { 11419 // If the constructor used was non-trivial, set this as the 11420 // "initializer". 11421 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11422 if (!construct->getConstructor()->isTrivial()) { 11423 Expr *init = MaybeCreateExprWithCleanups(construct); 11424 ExDecl->setInit(init); 11425 } 11426 11427 // And make sure it's destructable. 11428 FinalizeVarWithDestructor(ExDecl, recordType); 11429 } 11430 } 11431 } 11432 11433 if (Invalid) 11434 ExDecl->setInvalidDecl(); 11435 11436 return ExDecl; 11437 } 11438 11439 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11440 /// handler. 11441 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11442 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11443 bool Invalid = D.isInvalidType(); 11444 11445 // Check for unexpanded parameter packs. 11446 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11447 UPPC_ExceptionType)) { 11448 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11449 D.getIdentifierLoc()); 11450 Invalid = true; 11451 } 11452 11453 IdentifierInfo *II = D.getIdentifier(); 11454 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11455 LookupOrdinaryName, 11456 ForRedeclaration)) { 11457 // The scope should be freshly made just for us. There is just no way 11458 // it contains any previous declaration, except for function parameters in 11459 // a function-try-block's catch statement. 11460 assert(!S->isDeclScope(PrevDecl)); 11461 if (isDeclInScope(PrevDecl, CurContext, S)) { 11462 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11463 << D.getIdentifier(); 11464 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11465 Invalid = true; 11466 } else if (PrevDecl->isTemplateParameter()) 11467 // Maybe we will complain about the shadowed template parameter. 11468 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11469 } 11470 11471 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11472 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11473 << D.getCXXScopeSpec().getRange(); 11474 Invalid = true; 11475 } 11476 11477 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11478 D.getLocStart(), 11479 D.getIdentifierLoc(), 11480 D.getIdentifier()); 11481 if (Invalid) 11482 ExDecl->setInvalidDecl(); 11483 11484 // Add the exception declaration into this scope. 11485 if (II) 11486 PushOnScopeChains(ExDecl, S); 11487 else 11488 CurContext->addDecl(ExDecl); 11489 11490 ProcessDeclAttributes(S, ExDecl, D); 11491 return ExDecl; 11492 } 11493 11494 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11495 Expr *AssertExpr, 11496 Expr *AssertMessageExpr, 11497 SourceLocation RParenLoc) { 11498 StringLiteral *AssertMessage = 11499 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11500 11501 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11502 return nullptr; 11503 11504 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11505 AssertMessage, RParenLoc, false); 11506 } 11507 11508 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11509 Expr *AssertExpr, 11510 StringLiteral *AssertMessage, 11511 SourceLocation RParenLoc, 11512 bool Failed) { 11513 assert(AssertExpr != nullptr && "Expected non-null condition"); 11514 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11515 !Failed) { 11516 // In a static_assert-declaration, the constant-expression shall be a 11517 // constant expression that can be contextually converted to bool. 11518 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11519 if (Converted.isInvalid()) 11520 Failed = true; 11521 11522 llvm::APSInt Cond; 11523 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11524 diag::err_static_assert_expression_is_not_constant, 11525 /*AllowFold=*/false).isInvalid()) 11526 Failed = true; 11527 11528 if (!Failed && !Cond) { 11529 SmallString<256> MsgBuffer; 11530 llvm::raw_svector_ostream Msg(MsgBuffer); 11531 if (AssertMessage) 11532 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11533 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11534 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11535 Failed = true; 11536 } 11537 } 11538 11539 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11540 AssertExpr, AssertMessage, RParenLoc, 11541 Failed); 11542 11543 CurContext->addDecl(Decl); 11544 return Decl; 11545 } 11546 11547 /// \brief Perform semantic analysis of the given friend type declaration. 11548 /// 11549 /// \returns A friend declaration that. 11550 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11551 SourceLocation FriendLoc, 11552 TypeSourceInfo *TSInfo) { 11553 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11554 11555 QualType T = TSInfo->getType(); 11556 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11557 11558 // C++03 [class.friend]p2: 11559 // An elaborated-type-specifier shall be used in a friend declaration 11560 // for a class.* 11561 // 11562 // * The class-key of the elaborated-type-specifier is required. 11563 if (!ActiveTemplateInstantiations.empty()) { 11564 // Do not complain about the form of friend template types during 11565 // template instantiation; we will already have complained when the 11566 // template was declared. 11567 } else { 11568 if (!T->isElaboratedTypeSpecifier()) { 11569 // If we evaluated the type to a record type, suggest putting 11570 // a tag in front. 11571 if (const RecordType *RT = T->getAs<RecordType>()) { 11572 RecordDecl *RD = RT->getDecl(); 11573 11574 SmallString<16> InsertionText(" "); 11575 InsertionText += RD->getKindName(); 11576 11577 Diag(TypeRange.getBegin(), 11578 getLangOpts().CPlusPlus11 ? 11579 diag::warn_cxx98_compat_unelaborated_friend_type : 11580 diag::ext_unelaborated_friend_type) 11581 << (unsigned) RD->getTagKind() 11582 << T 11583 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11584 InsertionText); 11585 } else { 11586 Diag(FriendLoc, 11587 getLangOpts().CPlusPlus11 ? 11588 diag::warn_cxx98_compat_nonclass_type_friend : 11589 diag::ext_nonclass_type_friend) 11590 << T 11591 << TypeRange; 11592 } 11593 } else if (T->getAs<EnumType>()) { 11594 Diag(FriendLoc, 11595 getLangOpts().CPlusPlus11 ? 11596 diag::warn_cxx98_compat_enum_friend : 11597 diag::ext_enum_friend) 11598 << T 11599 << TypeRange; 11600 } 11601 11602 // C++11 [class.friend]p3: 11603 // A friend declaration that does not declare a function shall have one 11604 // of the following forms: 11605 // friend elaborated-type-specifier ; 11606 // friend simple-type-specifier ; 11607 // friend typename-specifier ; 11608 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11609 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11610 } 11611 11612 // If the type specifier in a friend declaration designates a (possibly 11613 // cv-qualified) class type, that class is declared as a friend; otherwise, 11614 // the friend declaration is ignored. 11615 return FriendDecl::Create(Context, CurContext, 11616 TSInfo->getTypeLoc().getLocStart(), TSInfo, 11617 FriendLoc); 11618 } 11619 11620 /// Handle a friend tag declaration where the scope specifier was 11621 /// templated. 11622 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11623 unsigned TagSpec, SourceLocation TagLoc, 11624 CXXScopeSpec &SS, 11625 IdentifierInfo *Name, 11626 SourceLocation NameLoc, 11627 AttributeList *Attr, 11628 MultiTemplateParamsArg TempParamLists) { 11629 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11630 11631 bool isExplicitSpecialization = false; 11632 bool Invalid = false; 11633 11634 if (TemplateParameterList *TemplateParams = 11635 MatchTemplateParametersToScopeSpecifier( 11636 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 11637 isExplicitSpecialization, Invalid)) { 11638 if (TemplateParams->size() > 0) { 11639 // This is a declaration of a class template. 11640 if (Invalid) 11641 return nullptr; 11642 11643 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 11644 NameLoc, Attr, TemplateParams, AS_public, 11645 /*ModulePrivateLoc=*/SourceLocation(), 11646 FriendLoc, TempParamLists.size() - 1, 11647 TempParamLists.data()).get(); 11648 } else { 11649 // The "template<>" header is extraneous. 11650 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11651 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11652 isExplicitSpecialization = true; 11653 } 11654 } 11655 11656 if (Invalid) return nullptr; 11657 11658 bool isAllExplicitSpecializations = true; 11659 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11660 if (TempParamLists[I]->size()) { 11661 isAllExplicitSpecializations = false; 11662 break; 11663 } 11664 } 11665 11666 // FIXME: don't ignore attributes. 11667 11668 // If it's explicit specializations all the way down, just forget 11669 // about the template header and build an appropriate non-templated 11670 // friend. TODO: for source fidelity, remember the headers. 11671 if (isAllExplicitSpecializations) { 11672 if (SS.isEmpty()) { 11673 bool Owned = false; 11674 bool IsDependent = false; 11675 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11676 Attr, AS_public, 11677 /*ModulePrivateLoc=*/SourceLocation(), 11678 MultiTemplateParamsArg(), Owned, IsDependent, 11679 /*ScopedEnumKWLoc=*/SourceLocation(), 11680 /*ScopedEnumUsesClassTag=*/false, 11681 /*UnderlyingType=*/TypeResult(), 11682 /*IsTypeSpecifier=*/false); 11683 } 11684 11685 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11686 ElaboratedTypeKeyword Keyword 11687 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11688 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11689 *Name, NameLoc); 11690 if (T.isNull()) 11691 return nullptr; 11692 11693 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11694 if (isa<DependentNameType>(T)) { 11695 DependentNameTypeLoc TL = 11696 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11697 TL.setElaboratedKeywordLoc(TagLoc); 11698 TL.setQualifierLoc(QualifierLoc); 11699 TL.setNameLoc(NameLoc); 11700 } else { 11701 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11702 TL.setElaboratedKeywordLoc(TagLoc); 11703 TL.setQualifierLoc(QualifierLoc); 11704 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11705 } 11706 11707 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11708 TSI, FriendLoc, TempParamLists); 11709 Friend->setAccess(AS_public); 11710 CurContext->addDecl(Friend); 11711 return Friend; 11712 } 11713 11714 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11715 11716 11717 11718 // Handle the case of a templated-scope friend class. e.g. 11719 // template <class T> class A<T>::B; 11720 // FIXME: we don't support these right now. 11721 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11722 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11723 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11724 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11725 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11726 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11727 TL.setElaboratedKeywordLoc(TagLoc); 11728 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11729 TL.setNameLoc(NameLoc); 11730 11731 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11732 TSI, FriendLoc, TempParamLists); 11733 Friend->setAccess(AS_public); 11734 Friend->setUnsupportedFriend(true); 11735 CurContext->addDecl(Friend); 11736 return Friend; 11737 } 11738 11739 11740 /// Handle a friend type declaration. This works in tandem with 11741 /// ActOnTag. 11742 /// 11743 /// Notes on friend class templates: 11744 /// 11745 /// We generally treat friend class declarations as if they were 11746 /// declaring a class. So, for example, the elaborated type specifier 11747 /// in a friend declaration is required to obey the restrictions of a 11748 /// class-head (i.e. no typedefs in the scope chain), template 11749 /// parameters are required to match up with simple template-ids, &c. 11750 /// However, unlike when declaring a template specialization, it's 11751 /// okay to refer to a template specialization without an empty 11752 /// template parameter declaration, e.g. 11753 /// friend class A<T>::B<unsigned>; 11754 /// We permit this as a special case; if there are any template 11755 /// parameters present at all, require proper matching, i.e. 11756 /// template <> template \<class T> friend class A<int>::B; 11757 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11758 MultiTemplateParamsArg TempParams) { 11759 SourceLocation Loc = DS.getLocStart(); 11760 11761 assert(DS.isFriendSpecified()); 11762 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11763 11764 // Try to convert the decl specifier to a type. This works for 11765 // friend templates because ActOnTag never produces a ClassTemplateDecl 11766 // for a TUK_Friend. 11767 Declarator TheDeclarator(DS, Declarator::MemberContext); 11768 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11769 QualType T = TSI->getType(); 11770 if (TheDeclarator.isInvalidType()) 11771 return nullptr; 11772 11773 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11774 return nullptr; 11775 11776 // This is definitely an error in C++98. It's probably meant to 11777 // be forbidden in C++0x, too, but the specification is just 11778 // poorly written. 11779 // 11780 // The problem is with declarations like the following: 11781 // template <T> friend A<T>::foo; 11782 // where deciding whether a class C is a friend or not now hinges 11783 // on whether there exists an instantiation of A that causes 11784 // 'foo' to equal C. There are restrictions on class-heads 11785 // (which we declare (by fiat) elaborated friend declarations to 11786 // be) that makes this tractable. 11787 // 11788 // FIXME: handle "template <> friend class A<T>;", which 11789 // is possibly well-formed? Who even knows? 11790 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11791 Diag(Loc, diag::err_tagless_friend_type_template) 11792 << DS.getSourceRange(); 11793 return nullptr; 11794 } 11795 11796 // C++98 [class.friend]p1: A friend of a class is a function 11797 // or class that is not a member of the class . . . 11798 // This is fixed in DR77, which just barely didn't make the C++03 11799 // deadline. It's also a very silly restriction that seriously 11800 // affects inner classes and which nobody else seems to implement; 11801 // thus we never diagnose it, not even in -pedantic. 11802 // 11803 // But note that we could warn about it: it's always useless to 11804 // friend one of your own members (it's not, however, worthless to 11805 // friend a member of an arbitrary specialization of your template). 11806 11807 Decl *D; 11808 if (unsigned NumTempParamLists = TempParams.size()) 11809 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11810 NumTempParamLists, 11811 TempParams.data(), 11812 TSI, 11813 DS.getFriendSpecLoc()); 11814 else 11815 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11816 11817 if (!D) 11818 return nullptr; 11819 11820 D->setAccess(AS_public); 11821 CurContext->addDecl(D); 11822 11823 return D; 11824 } 11825 11826 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11827 MultiTemplateParamsArg TemplateParams) { 11828 const DeclSpec &DS = D.getDeclSpec(); 11829 11830 assert(DS.isFriendSpecified()); 11831 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11832 11833 SourceLocation Loc = D.getIdentifierLoc(); 11834 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11835 11836 // C++ [class.friend]p1 11837 // A friend of a class is a function or class.... 11838 // Note that this sees through typedefs, which is intended. 11839 // It *doesn't* see through dependent types, which is correct 11840 // according to [temp.arg.type]p3: 11841 // If a declaration acquires a function type through a 11842 // type dependent on a template-parameter and this causes 11843 // a declaration that does not use the syntactic form of a 11844 // function declarator to have a function type, the program 11845 // is ill-formed. 11846 if (!TInfo->getType()->isFunctionType()) { 11847 Diag(Loc, diag::err_unexpected_friend); 11848 11849 // It might be worthwhile to try to recover by creating an 11850 // appropriate declaration. 11851 return nullptr; 11852 } 11853 11854 // C++ [namespace.memdef]p3 11855 // - If a friend declaration in a non-local class first declares a 11856 // class or function, the friend class or function is a member 11857 // of the innermost enclosing namespace. 11858 // - The name of the friend is not found by simple name lookup 11859 // until a matching declaration is provided in that namespace 11860 // scope (either before or after the class declaration granting 11861 // friendship). 11862 // - If a friend function is called, its name may be found by the 11863 // name lookup that considers functions from namespaces and 11864 // classes associated with the types of the function arguments. 11865 // - When looking for a prior declaration of a class or a function 11866 // declared as a friend, scopes outside the innermost enclosing 11867 // namespace scope are not considered. 11868 11869 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11870 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11871 DeclarationName Name = NameInfo.getName(); 11872 assert(Name); 11873 11874 // Check for unexpanded parameter packs. 11875 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11876 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11877 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11878 return nullptr; 11879 11880 // The context we found the declaration in, or in which we should 11881 // create the declaration. 11882 DeclContext *DC; 11883 Scope *DCScope = S; 11884 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11885 ForRedeclaration); 11886 11887 // There are five cases here. 11888 // - There's no scope specifier and we're in a local class. Only look 11889 // for functions declared in the immediately-enclosing block scope. 11890 // We recover from invalid scope qualifiers as if they just weren't there. 11891 FunctionDecl *FunctionContainingLocalClass = nullptr; 11892 if ((SS.isInvalid() || !SS.isSet()) && 11893 (FunctionContainingLocalClass = 11894 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11895 // C++11 [class.friend]p11: 11896 // If a friend declaration appears in a local class and the name 11897 // specified is an unqualified name, a prior declaration is 11898 // looked up without considering scopes that are outside the 11899 // innermost enclosing non-class scope. For a friend function 11900 // declaration, if there is no prior declaration, the program is 11901 // ill-formed. 11902 11903 // Find the innermost enclosing non-class scope. This is the block 11904 // scope containing the local class definition (or for a nested class, 11905 // the outer local class). 11906 DCScope = S->getFnParent(); 11907 11908 // Look up the function name in the scope. 11909 Previous.clear(LookupLocalFriendName); 11910 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11911 11912 if (!Previous.empty()) { 11913 // All possible previous declarations must have the same context: 11914 // either they were declared at block scope or they are members of 11915 // one of the enclosing local classes. 11916 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11917 } else { 11918 // This is ill-formed, but provide the context that we would have 11919 // declared the function in, if we were permitted to, for error recovery. 11920 DC = FunctionContainingLocalClass; 11921 } 11922 adjustContextForLocalExternDecl(DC); 11923 11924 // C++ [class.friend]p6: 11925 // A function can be defined in a friend declaration of a class if and 11926 // only if the class is a non-local class (9.8), the function name is 11927 // unqualified, and the function has namespace scope. 11928 if (D.isFunctionDefinition()) { 11929 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11930 } 11931 11932 // - There's no scope specifier, in which case we just go to the 11933 // appropriate scope and look for a function or function template 11934 // there as appropriate. 11935 } else if (SS.isInvalid() || !SS.isSet()) { 11936 // C++11 [namespace.memdef]p3: 11937 // If the name in a friend declaration is neither qualified nor 11938 // a template-id and the declaration is a function or an 11939 // elaborated-type-specifier, the lookup to determine whether 11940 // the entity has been previously declared shall not consider 11941 // any scopes outside the innermost enclosing namespace. 11942 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11943 11944 // Find the appropriate context according to the above. 11945 DC = CurContext; 11946 11947 // Skip class contexts. If someone can cite chapter and verse 11948 // for this behavior, that would be nice --- it's what GCC and 11949 // EDG do, and it seems like a reasonable intent, but the spec 11950 // really only says that checks for unqualified existing 11951 // declarations should stop at the nearest enclosing namespace, 11952 // not that they should only consider the nearest enclosing 11953 // namespace. 11954 while (DC->isRecord()) 11955 DC = DC->getParent(); 11956 11957 DeclContext *LookupDC = DC; 11958 while (LookupDC->isTransparentContext()) 11959 LookupDC = LookupDC->getParent(); 11960 11961 while (true) { 11962 LookupQualifiedName(Previous, LookupDC); 11963 11964 if (!Previous.empty()) { 11965 DC = LookupDC; 11966 break; 11967 } 11968 11969 if (isTemplateId) { 11970 if (isa<TranslationUnitDecl>(LookupDC)) break; 11971 } else { 11972 if (LookupDC->isFileContext()) break; 11973 } 11974 LookupDC = LookupDC->getParent(); 11975 } 11976 11977 DCScope = getScopeForDeclContext(S, DC); 11978 11979 // - There's a non-dependent scope specifier, in which case we 11980 // compute it and do a previous lookup there for a function 11981 // or function template. 11982 } else if (!SS.getScopeRep()->isDependent()) { 11983 DC = computeDeclContext(SS); 11984 if (!DC) return nullptr; 11985 11986 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 11987 11988 LookupQualifiedName(Previous, DC); 11989 11990 // Ignore things found implicitly in the wrong scope. 11991 // TODO: better diagnostics for this case. Suggesting the right 11992 // qualified scope would be nice... 11993 LookupResult::Filter F = Previous.makeFilter(); 11994 while (F.hasNext()) { 11995 NamedDecl *D = F.next(); 11996 if (!DC->InEnclosingNamespaceSetOf( 11997 D->getDeclContext()->getRedeclContext())) 11998 F.erase(); 11999 } 12000 F.done(); 12001 12002 if (Previous.empty()) { 12003 D.setInvalidType(); 12004 Diag(Loc, diag::err_qualified_friend_not_found) 12005 << Name << TInfo->getType(); 12006 return nullptr; 12007 } 12008 12009 // C++ [class.friend]p1: A friend of a class is a function or 12010 // class that is not a member of the class . . . 12011 if (DC->Equals(CurContext)) 12012 Diag(DS.getFriendSpecLoc(), 12013 getLangOpts().CPlusPlus11 ? 12014 diag::warn_cxx98_compat_friend_is_member : 12015 diag::err_friend_is_member); 12016 12017 if (D.isFunctionDefinition()) { 12018 // C++ [class.friend]p6: 12019 // A function can be defined in a friend declaration of a class if and 12020 // only if the class is a non-local class (9.8), the function name is 12021 // unqualified, and the function has namespace scope. 12022 SemaDiagnosticBuilder DB 12023 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12024 12025 DB << SS.getScopeRep(); 12026 if (DC->isFileContext()) 12027 DB << FixItHint::CreateRemoval(SS.getRange()); 12028 SS.clear(); 12029 } 12030 12031 // - There's a scope specifier that does not match any template 12032 // parameter lists, in which case we use some arbitrary context, 12033 // create a method or method template, and wait for instantiation. 12034 // - There's a scope specifier that does match some template 12035 // parameter lists, which we don't handle right now. 12036 } else { 12037 if (D.isFunctionDefinition()) { 12038 // C++ [class.friend]p6: 12039 // A function can be defined in a friend declaration of a class if and 12040 // only if the class is a non-local class (9.8), the function name is 12041 // unqualified, and the function has namespace scope. 12042 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12043 << SS.getScopeRep(); 12044 } 12045 12046 DC = CurContext; 12047 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12048 } 12049 12050 if (!DC->isRecord()) { 12051 // This implies that it has to be an operator or function. 12052 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12053 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12054 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12055 Diag(Loc, diag::err_introducing_special_friend) << 12056 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12057 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12058 return nullptr; 12059 } 12060 } 12061 12062 // FIXME: This is an egregious hack to cope with cases where the scope stack 12063 // does not contain the declaration context, i.e., in an out-of-line 12064 // definition of a class. 12065 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12066 if (!DCScope) { 12067 FakeDCScope.setEntity(DC); 12068 DCScope = &FakeDCScope; 12069 } 12070 12071 bool AddToScope = true; 12072 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12073 TemplateParams, AddToScope); 12074 if (!ND) return nullptr; 12075 12076 assert(ND->getLexicalDeclContext() == CurContext); 12077 12078 // If we performed typo correction, we might have added a scope specifier 12079 // and changed the decl context. 12080 DC = ND->getDeclContext(); 12081 12082 // Add the function declaration to the appropriate lookup tables, 12083 // adjusting the redeclarations list as necessary. We don't 12084 // want to do this yet if the friending class is dependent. 12085 // 12086 // Also update the scope-based lookup if the target context's 12087 // lookup context is in lexical scope. 12088 if (!CurContext->isDependentContext()) { 12089 DC = DC->getRedeclContext(); 12090 DC->makeDeclVisibleInContext(ND); 12091 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12092 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12093 } 12094 12095 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12096 D.getIdentifierLoc(), ND, 12097 DS.getFriendSpecLoc()); 12098 FrD->setAccess(AS_public); 12099 CurContext->addDecl(FrD); 12100 12101 if (ND->isInvalidDecl()) { 12102 FrD->setInvalidDecl(); 12103 } else { 12104 if (DC->isRecord()) CheckFriendAccess(ND); 12105 12106 FunctionDecl *FD; 12107 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12108 FD = FTD->getTemplatedDecl(); 12109 else 12110 FD = cast<FunctionDecl>(ND); 12111 12112 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12113 // default argument expression, that declaration shall be a definition 12114 // and shall be the only declaration of the function or function 12115 // template in the translation unit. 12116 if (functionDeclHasDefaultArgument(FD)) { 12117 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12118 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12119 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12120 } else if (!D.isFunctionDefinition()) 12121 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12122 } 12123 12124 // Mark templated-scope function declarations as unsupported. 12125 if (FD->getNumTemplateParameterLists()) 12126 FrD->setUnsupportedFriend(true); 12127 } 12128 12129 return ND; 12130 } 12131 12132 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12133 AdjustDeclIfTemplate(Dcl); 12134 12135 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12136 if (!Fn) { 12137 Diag(DelLoc, diag::err_deleted_non_function); 12138 return; 12139 } 12140 12141 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12142 // Don't consider the implicit declaration we generate for explicit 12143 // specializations. FIXME: Do not generate these implicit declarations. 12144 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12145 Prev->getPreviousDecl()) && 12146 !Prev->isDefined()) { 12147 Diag(DelLoc, diag::err_deleted_decl_not_first); 12148 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12149 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12150 : diag::note_previous_declaration); 12151 } 12152 // If the declaration wasn't the first, we delete the function anyway for 12153 // recovery. 12154 Fn = Fn->getCanonicalDecl(); 12155 } 12156 12157 // dllimport/dllexport cannot be deleted. 12158 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12159 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12160 Fn->setInvalidDecl(); 12161 } 12162 12163 if (Fn->isDeleted()) 12164 return; 12165 12166 // See if we're deleting a function which is already known to override a 12167 // non-deleted virtual function. 12168 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12169 bool IssuedDiagnostic = false; 12170 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12171 E = MD->end_overridden_methods(); 12172 I != E; ++I) { 12173 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12174 if (!IssuedDiagnostic) { 12175 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12176 IssuedDiagnostic = true; 12177 } 12178 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12179 } 12180 } 12181 } 12182 12183 // C++11 [basic.start.main]p3: 12184 // A program that defines main as deleted [...] is ill-formed. 12185 if (Fn->isMain()) 12186 Diag(DelLoc, diag::err_deleted_main); 12187 12188 Fn->setDeletedAsWritten(); 12189 } 12190 12191 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12192 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12193 12194 if (MD) { 12195 if (MD->getParent()->isDependentType()) { 12196 MD->setDefaulted(); 12197 MD->setExplicitlyDefaulted(); 12198 return; 12199 } 12200 12201 CXXSpecialMember Member = getSpecialMember(MD); 12202 if (Member == CXXInvalid) { 12203 if (!MD->isInvalidDecl()) 12204 Diag(DefaultLoc, diag::err_default_special_members); 12205 return; 12206 } 12207 12208 MD->setDefaulted(); 12209 MD->setExplicitlyDefaulted(); 12210 12211 // If this definition appears within the record, do the checking when 12212 // the record is complete. 12213 const FunctionDecl *Primary = MD; 12214 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12215 // Find the uninstantiated declaration that actually had the '= default' 12216 // on it. 12217 Pattern->isDefined(Primary); 12218 12219 // If the method was defaulted on its first declaration, we will have 12220 // already performed the checking in CheckCompletedCXXClass. Such a 12221 // declaration doesn't trigger an implicit definition. 12222 if (Primary == Primary->getCanonicalDecl()) 12223 return; 12224 12225 CheckExplicitlyDefaultedSpecialMember(MD); 12226 12227 // The exception specification is needed because we are defining the 12228 // function. 12229 ResolveExceptionSpec(DefaultLoc, 12230 MD->getType()->castAs<FunctionProtoType>()); 12231 12232 if (MD->isInvalidDecl()) 12233 return; 12234 12235 switch (Member) { 12236 case CXXDefaultConstructor: 12237 DefineImplicitDefaultConstructor(DefaultLoc, 12238 cast<CXXConstructorDecl>(MD)); 12239 break; 12240 case CXXCopyConstructor: 12241 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12242 break; 12243 case CXXCopyAssignment: 12244 DefineImplicitCopyAssignment(DefaultLoc, MD); 12245 break; 12246 case CXXDestructor: 12247 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12248 break; 12249 case CXXMoveConstructor: 12250 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12251 break; 12252 case CXXMoveAssignment: 12253 DefineImplicitMoveAssignment(DefaultLoc, MD); 12254 break; 12255 case CXXInvalid: 12256 llvm_unreachable("Invalid special member."); 12257 } 12258 } else { 12259 Diag(DefaultLoc, diag::err_default_special_members); 12260 } 12261 } 12262 12263 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12264 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12265 Stmt *SubStmt = *CI; 12266 if (!SubStmt) 12267 continue; 12268 if (isa<ReturnStmt>(SubStmt)) 12269 Self.Diag(SubStmt->getLocStart(), 12270 diag::err_return_in_constructor_handler); 12271 if (!isa<Expr>(SubStmt)) 12272 SearchForReturnInStmt(Self, SubStmt); 12273 } 12274 } 12275 12276 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12277 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12278 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12279 SearchForReturnInStmt(*this, Handler); 12280 } 12281 } 12282 12283 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12284 const CXXMethodDecl *Old) { 12285 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12286 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12287 12288 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12289 12290 // If the calling conventions match, everything is fine 12291 if (NewCC == OldCC) 12292 return false; 12293 12294 // If the calling conventions mismatch because the new function is static, 12295 // suppress the calling convention mismatch error; the error about static 12296 // function override (err_static_overrides_virtual from 12297 // Sema::CheckFunctionDeclaration) is more clear. 12298 if (New->getStorageClass() == SC_Static) 12299 return false; 12300 12301 Diag(New->getLocation(), 12302 diag::err_conflicting_overriding_cc_attributes) 12303 << New->getDeclName() << New->getType() << Old->getType(); 12304 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12305 return true; 12306 } 12307 12308 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12309 const CXXMethodDecl *Old) { 12310 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12311 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12312 12313 if (Context.hasSameType(NewTy, OldTy) || 12314 NewTy->isDependentType() || OldTy->isDependentType()) 12315 return false; 12316 12317 // Check if the return types are covariant 12318 QualType NewClassTy, OldClassTy; 12319 12320 /// Both types must be pointers or references to classes. 12321 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12322 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12323 NewClassTy = NewPT->getPointeeType(); 12324 OldClassTy = OldPT->getPointeeType(); 12325 } 12326 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12327 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12328 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12329 NewClassTy = NewRT->getPointeeType(); 12330 OldClassTy = OldRT->getPointeeType(); 12331 } 12332 } 12333 } 12334 12335 // The return types aren't either both pointers or references to a class type. 12336 if (NewClassTy.isNull()) { 12337 Diag(New->getLocation(), 12338 diag::err_different_return_type_for_overriding_virtual_function) 12339 << New->getDeclName() << NewTy << OldTy 12340 << New->getReturnTypeSourceRange(); 12341 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12342 << Old->getReturnTypeSourceRange(); 12343 12344 return true; 12345 } 12346 12347 // C++ [class.virtual]p6: 12348 // If the return type of D::f differs from the return type of B::f, the 12349 // class type in the return type of D::f shall be complete at the point of 12350 // declaration of D::f or shall be the class type D. 12351 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12352 if (!RT->isBeingDefined() && 12353 RequireCompleteType(New->getLocation(), NewClassTy, 12354 diag::err_covariant_return_incomplete, 12355 New->getDeclName())) 12356 return true; 12357 } 12358 12359 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12360 // Check if the new class derives from the old class. 12361 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12362 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12363 << New->getDeclName() << NewTy << OldTy 12364 << New->getReturnTypeSourceRange(); 12365 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12366 << Old->getReturnTypeSourceRange(); 12367 return true; 12368 } 12369 12370 // Check if we the conversion from derived to base is valid. 12371 if (CheckDerivedToBaseConversion( 12372 NewClassTy, OldClassTy, 12373 diag::err_covariant_return_inaccessible_base, 12374 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12375 New->getLocation(), New->getReturnTypeSourceRange(), 12376 New->getDeclName(), nullptr)) { 12377 // FIXME: this note won't trigger for delayed access control 12378 // diagnostics, and it's impossible to get an undelayed error 12379 // here from access control during the original parse because 12380 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12381 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12382 << Old->getReturnTypeSourceRange(); 12383 return true; 12384 } 12385 } 12386 12387 // The qualifiers of the return types must be the same. 12388 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12389 Diag(New->getLocation(), 12390 diag::err_covariant_return_type_different_qualifications) 12391 << New->getDeclName() << NewTy << OldTy 12392 << New->getReturnTypeSourceRange(); 12393 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12394 << Old->getReturnTypeSourceRange(); 12395 return true; 12396 }; 12397 12398 12399 // The new class type must have the same or less qualifiers as the old type. 12400 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12401 Diag(New->getLocation(), 12402 diag::err_covariant_return_type_class_type_more_qualified) 12403 << New->getDeclName() << NewTy << OldTy 12404 << New->getReturnTypeSourceRange(); 12405 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12406 << Old->getReturnTypeSourceRange(); 12407 return true; 12408 }; 12409 12410 return false; 12411 } 12412 12413 /// \brief Mark the given method pure. 12414 /// 12415 /// \param Method the method to be marked pure. 12416 /// 12417 /// \param InitRange the source range that covers the "0" initializer. 12418 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12419 SourceLocation EndLoc = InitRange.getEnd(); 12420 if (EndLoc.isValid()) 12421 Method->setRangeEnd(EndLoc); 12422 12423 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12424 Method->setPure(); 12425 return false; 12426 } 12427 12428 if (!Method->isInvalidDecl()) 12429 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12430 << Method->getDeclName() << InitRange; 12431 return true; 12432 } 12433 12434 /// \brief Determine whether the given declaration is a static data member. 12435 static bool isStaticDataMember(const Decl *D) { 12436 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12437 return Var->isStaticDataMember(); 12438 12439 return false; 12440 } 12441 12442 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12443 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12444 /// is a fresh scope pushed for just this purpose. 12445 /// 12446 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12447 /// static data member of class X, names should be looked up in the scope of 12448 /// class X. 12449 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12450 // If there is no declaration, there was an error parsing it. 12451 if (!D || D->isInvalidDecl()) 12452 return; 12453 12454 // We will always have a nested name specifier here, but this declaration 12455 // might not be out of line if the specifier names the current namespace: 12456 // extern int n; 12457 // int ::n = 0; 12458 if (D->isOutOfLine()) 12459 EnterDeclaratorContext(S, D->getDeclContext()); 12460 12461 // If we are parsing the initializer for a static data member, push a 12462 // new expression evaluation context that is associated with this static 12463 // data member. 12464 if (isStaticDataMember(D)) 12465 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12466 } 12467 12468 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12469 /// initializer for the out-of-line declaration 'D'. 12470 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12471 // If there is no declaration, there was an error parsing it. 12472 if (!D || D->isInvalidDecl()) 12473 return; 12474 12475 if (isStaticDataMember(D)) 12476 PopExpressionEvaluationContext(); 12477 12478 if (D->isOutOfLine()) 12479 ExitDeclaratorContext(S); 12480 } 12481 12482 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12483 /// C++ if/switch/while/for statement. 12484 /// e.g: "if (int x = f()) {...}" 12485 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12486 // C++ 6.4p2: 12487 // The declarator shall not specify a function or an array. 12488 // The type-specifier-seq shall not contain typedef and shall not declare a 12489 // new class or enumeration. 12490 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12491 "Parser allowed 'typedef' as storage class of condition decl."); 12492 12493 Decl *Dcl = ActOnDeclarator(S, D); 12494 if (!Dcl) 12495 return true; 12496 12497 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12498 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12499 << D.getSourceRange(); 12500 return true; 12501 } 12502 12503 return Dcl; 12504 } 12505 12506 void Sema::LoadExternalVTableUses() { 12507 if (!ExternalSource) 12508 return; 12509 12510 SmallVector<ExternalVTableUse, 4> VTables; 12511 ExternalSource->ReadUsedVTables(VTables); 12512 SmallVector<VTableUse, 4> NewUses; 12513 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12514 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12515 = VTablesUsed.find(VTables[I].Record); 12516 // Even if a definition wasn't required before, it may be required now. 12517 if (Pos != VTablesUsed.end()) { 12518 if (!Pos->second && VTables[I].DefinitionRequired) 12519 Pos->second = true; 12520 continue; 12521 } 12522 12523 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12524 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12525 } 12526 12527 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12528 } 12529 12530 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12531 bool DefinitionRequired) { 12532 // Ignore any vtable uses in unevaluated operands or for classes that do 12533 // not have a vtable. 12534 if (!Class->isDynamicClass() || Class->isDependentContext() || 12535 CurContext->isDependentContext() || isUnevaluatedContext()) 12536 return; 12537 12538 // Try to insert this class into the map. 12539 LoadExternalVTableUses(); 12540 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12541 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12542 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12543 if (!Pos.second) { 12544 // If we already had an entry, check to see if we are promoting this vtable 12545 // to required a definition. If so, we need to reappend to the VTableUses 12546 // list, since we may have already processed the first entry. 12547 if (DefinitionRequired && !Pos.first->second) { 12548 Pos.first->second = true; 12549 } else { 12550 // Otherwise, we can early exit. 12551 return; 12552 } 12553 } else { 12554 // The Microsoft ABI requires that we perform the destructor body 12555 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12556 // the deleting destructor is emitted with the vtable, not with the 12557 // destructor definition as in the Itanium ABI. 12558 // If it has a definition, we do the check at that point instead. 12559 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12560 Class->hasUserDeclaredDestructor() && 12561 !Class->getDestructor()->isDefined() && 12562 !Class->getDestructor()->isDeleted()) { 12563 CXXDestructorDecl *DD = Class->getDestructor(); 12564 ContextRAII SavedContext(*this, DD); 12565 CheckDestructor(DD); 12566 } 12567 } 12568 12569 // Local classes need to have their virtual members marked 12570 // immediately. For all other classes, we mark their virtual members 12571 // at the end of the translation unit. 12572 if (Class->isLocalClass()) 12573 MarkVirtualMembersReferenced(Loc, Class); 12574 else 12575 VTableUses.push_back(std::make_pair(Class, Loc)); 12576 } 12577 12578 bool Sema::DefineUsedVTables() { 12579 LoadExternalVTableUses(); 12580 if (VTableUses.empty()) 12581 return false; 12582 12583 // Note: The VTableUses vector could grow as a result of marking 12584 // the members of a class as "used", so we check the size each 12585 // time through the loop and prefer indices (which are stable) to 12586 // iterators (which are not). 12587 bool DefinedAnything = false; 12588 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12589 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12590 if (!Class) 12591 continue; 12592 12593 SourceLocation Loc = VTableUses[I].second; 12594 12595 bool DefineVTable = true; 12596 12597 // If this class has a key function, but that key function is 12598 // defined in another translation unit, we don't need to emit the 12599 // vtable even though we're using it. 12600 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12601 if (KeyFunction && !KeyFunction->hasBody()) { 12602 // The key function is in another translation unit. 12603 DefineVTable = false; 12604 TemplateSpecializationKind TSK = 12605 KeyFunction->getTemplateSpecializationKind(); 12606 assert(TSK != TSK_ExplicitInstantiationDefinition && 12607 TSK != TSK_ImplicitInstantiation && 12608 "Instantiations don't have key functions"); 12609 (void)TSK; 12610 } else if (!KeyFunction) { 12611 // If we have a class with no key function that is the subject 12612 // of an explicit instantiation declaration, suppress the 12613 // vtable; it will live with the explicit instantiation 12614 // definition. 12615 bool IsExplicitInstantiationDeclaration 12616 = Class->getTemplateSpecializationKind() 12617 == TSK_ExplicitInstantiationDeclaration; 12618 for (auto R : Class->redecls()) { 12619 TemplateSpecializationKind TSK 12620 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12621 if (TSK == TSK_ExplicitInstantiationDeclaration) 12622 IsExplicitInstantiationDeclaration = true; 12623 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12624 IsExplicitInstantiationDeclaration = false; 12625 break; 12626 } 12627 } 12628 12629 if (IsExplicitInstantiationDeclaration) 12630 DefineVTable = false; 12631 } 12632 12633 // The exception specifications for all virtual members may be needed even 12634 // if we are not providing an authoritative form of the vtable in this TU. 12635 // We may choose to emit it available_externally anyway. 12636 if (!DefineVTable) { 12637 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12638 continue; 12639 } 12640 12641 // Mark all of the virtual members of this class as referenced, so 12642 // that we can build a vtable. Then, tell the AST consumer that a 12643 // vtable for this class is required. 12644 DefinedAnything = true; 12645 MarkVirtualMembersReferenced(Loc, Class); 12646 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12647 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12648 12649 // Optionally warn if we're emitting a weak vtable. 12650 if (Class->isExternallyVisible() && 12651 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12652 const FunctionDecl *KeyFunctionDef = nullptr; 12653 if (!KeyFunction || 12654 (KeyFunction->hasBody(KeyFunctionDef) && 12655 KeyFunctionDef->isInlined())) 12656 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12657 TSK_ExplicitInstantiationDefinition 12658 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12659 << Class; 12660 } 12661 } 12662 VTableUses.clear(); 12663 12664 return DefinedAnything; 12665 } 12666 12667 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12668 const CXXRecordDecl *RD) { 12669 for (const auto *I : RD->methods()) 12670 if (I->isVirtual() && !I->isPure()) 12671 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12672 } 12673 12674 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12675 const CXXRecordDecl *RD) { 12676 // Mark all functions which will appear in RD's vtable as used. 12677 CXXFinalOverriderMap FinalOverriders; 12678 RD->getFinalOverriders(FinalOverriders); 12679 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12680 E = FinalOverriders.end(); 12681 I != E; ++I) { 12682 for (OverridingMethods::const_iterator OI = I->second.begin(), 12683 OE = I->second.end(); 12684 OI != OE; ++OI) { 12685 assert(OI->second.size() > 0 && "no final overrider"); 12686 CXXMethodDecl *Overrider = OI->second.front().Method; 12687 12688 // C++ [basic.def.odr]p2: 12689 // [...] A virtual member function is used if it is not pure. [...] 12690 if (!Overrider->isPure()) 12691 MarkFunctionReferenced(Loc, Overrider); 12692 } 12693 } 12694 12695 // Only classes that have virtual bases need a VTT. 12696 if (RD->getNumVBases() == 0) 12697 return; 12698 12699 for (const auto &I : RD->bases()) { 12700 const CXXRecordDecl *Base = 12701 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12702 if (Base->getNumVBases() == 0) 12703 continue; 12704 MarkVirtualMembersReferenced(Loc, Base); 12705 } 12706 } 12707 12708 /// SetIvarInitializers - This routine builds initialization ASTs for the 12709 /// Objective-C implementation whose ivars need be initialized. 12710 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12711 if (!getLangOpts().CPlusPlus) 12712 return; 12713 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12714 SmallVector<ObjCIvarDecl*, 8> ivars; 12715 CollectIvarsToConstructOrDestruct(OID, ivars); 12716 if (ivars.empty()) 12717 return; 12718 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12719 for (unsigned i = 0; i < ivars.size(); i++) { 12720 FieldDecl *Field = ivars[i]; 12721 if (Field->isInvalidDecl()) 12722 continue; 12723 12724 CXXCtorInitializer *Member; 12725 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12726 InitializationKind InitKind = 12727 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12728 12729 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12730 ExprResult MemberInit = 12731 InitSeq.Perform(*this, InitEntity, InitKind, None); 12732 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12733 // Note, MemberInit could actually come back empty if no initialization 12734 // is required (e.g., because it would call a trivial default constructor) 12735 if (!MemberInit.get() || MemberInit.isInvalid()) 12736 continue; 12737 12738 Member = 12739 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12740 SourceLocation(), 12741 MemberInit.getAs<Expr>(), 12742 SourceLocation()); 12743 AllToInit.push_back(Member); 12744 12745 // Be sure that the destructor is accessible and is marked as referenced. 12746 if (const RecordType *RecordTy 12747 = Context.getBaseElementType(Field->getType()) 12748 ->getAs<RecordType>()) { 12749 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12750 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12751 MarkFunctionReferenced(Field->getLocation(), Destructor); 12752 CheckDestructorAccess(Field->getLocation(), Destructor, 12753 PDiag(diag::err_access_dtor_ivar) 12754 << Context.getBaseElementType(Field->getType())); 12755 } 12756 } 12757 } 12758 ObjCImplementation->setIvarInitializers(Context, 12759 AllToInit.data(), AllToInit.size()); 12760 } 12761 } 12762 12763 static 12764 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12765 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12766 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12767 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12768 Sema &S) { 12769 if (Ctor->isInvalidDecl()) 12770 return; 12771 12772 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12773 12774 // Target may not be determinable yet, for instance if this is a dependent 12775 // call in an uninstantiated template. 12776 if (Target) { 12777 const FunctionDecl *FNTarget = nullptr; 12778 (void)Target->hasBody(FNTarget); 12779 Target = const_cast<CXXConstructorDecl*>( 12780 cast_or_null<CXXConstructorDecl>(FNTarget)); 12781 } 12782 12783 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12784 // Avoid dereferencing a null pointer here. 12785 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 12786 12787 if (!Current.insert(Canonical)) 12788 return; 12789 12790 // We know that beyond here, we aren't chaining into a cycle. 12791 if (!Target || !Target->isDelegatingConstructor() || 12792 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12793 Valid.insert(Current.begin(), Current.end()); 12794 Current.clear(); 12795 // We've hit a cycle. 12796 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12797 Current.count(TCanonical)) { 12798 // If we haven't diagnosed this cycle yet, do so now. 12799 if (!Invalid.count(TCanonical)) { 12800 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12801 diag::warn_delegating_ctor_cycle) 12802 << Ctor; 12803 12804 // Don't add a note for a function delegating directly to itself. 12805 if (TCanonical != Canonical) 12806 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12807 12808 CXXConstructorDecl *C = Target; 12809 while (C->getCanonicalDecl() != Canonical) { 12810 const FunctionDecl *FNTarget = nullptr; 12811 (void)C->getTargetConstructor()->hasBody(FNTarget); 12812 assert(FNTarget && "Ctor cycle through bodiless function"); 12813 12814 C = const_cast<CXXConstructorDecl*>( 12815 cast<CXXConstructorDecl>(FNTarget)); 12816 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12817 } 12818 } 12819 12820 Invalid.insert(Current.begin(), Current.end()); 12821 Current.clear(); 12822 } else { 12823 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12824 } 12825 } 12826 12827 12828 void Sema::CheckDelegatingCtorCycles() { 12829 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12830 12831 for (DelegatingCtorDeclsType::iterator 12832 I = DelegatingCtorDecls.begin(ExternalSource), 12833 E = DelegatingCtorDecls.end(); 12834 I != E; ++I) 12835 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12836 12837 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12838 CE = Invalid.end(); 12839 CI != CE; ++CI) 12840 (*CI)->setInvalidDecl(); 12841 } 12842 12843 namespace { 12844 /// \brief AST visitor that finds references to the 'this' expression. 12845 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12846 Sema &S; 12847 12848 public: 12849 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12850 12851 bool VisitCXXThisExpr(CXXThisExpr *E) { 12852 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12853 << E->isImplicit(); 12854 return false; 12855 } 12856 }; 12857 } 12858 12859 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12860 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12861 if (!TSInfo) 12862 return false; 12863 12864 TypeLoc TL = TSInfo->getTypeLoc(); 12865 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12866 if (!ProtoTL) 12867 return false; 12868 12869 // C++11 [expr.prim.general]p3: 12870 // [The expression this] shall not appear before the optional 12871 // cv-qualifier-seq and it shall not appear within the declaration of a 12872 // static member function (although its type and value category are defined 12873 // within a static member function as they are within a non-static member 12874 // function). [ Note: this is because declaration matching does not occur 12875 // until the complete declarator is known. - end note ] 12876 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12877 FindCXXThisExpr Finder(*this); 12878 12879 // If the return type came after the cv-qualifier-seq, check it now. 12880 if (Proto->hasTrailingReturn() && 12881 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12882 return true; 12883 12884 // Check the exception specification. 12885 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12886 return true; 12887 12888 return checkThisInStaticMemberFunctionAttributes(Method); 12889 } 12890 12891 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12892 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12893 if (!TSInfo) 12894 return false; 12895 12896 TypeLoc TL = TSInfo->getTypeLoc(); 12897 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12898 if (!ProtoTL) 12899 return false; 12900 12901 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12902 FindCXXThisExpr Finder(*this); 12903 12904 switch (Proto->getExceptionSpecType()) { 12905 case EST_Uninstantiated: 12906 case EST_Unevaluated: 12907 case EST_BasicNoexcept: 12908 case EST_DynamicNone: 12909 case EST_MSAny: 12910 case EST_None: 12911 break; 12912 12913 case EST_ComputedNoexcept: 12914 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12915 return true; 12916 12917 case EST_Dynamic: 12918 for (const auto &E : Proto->exceptions()) { 12919 if (!Finder.TraverseType(E)) 12920 return true; 12921 } 12922 break; 12923 } 12924 12925 return false; 12926 } 12927 12928 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12929 FindCXXThisExpr Finder(*this); 12930 12931 // Check attributes. 12932 for (const auto *A : Method->attrs()) { 12933 // FIXME: This should be emitted by tblgen. 12934 Expr *Arg = nullptr; 12935 ArrayRef<Expr *> Args; 12936 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12937 Arg = G->getArg(); 12938 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12939 Arg = G->getArg(); 12940 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12941 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12942 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12943 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12944 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12945 Arg = ETLF->getSuccessValue(); 12946 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12947 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12948 Arg = STLF->getSuccessValue(); 12949 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12950 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12951 Arg = LR->getArg(); 12952 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12953 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12954 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12955 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12956 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12957 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12958 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12959 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12960 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12961 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12962 12963 if (Arg && !Finder.TraverseStmt(Arg)) 12964 return true; 12965 12966 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12967 if (!Finder.TraverseStmt(Args[I])) 12968 return true; 12969 } 12970 } 12971 12972 return false; 12973 } 12974 12975 void 12976 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12977 ArrayRef<ParsedType> DynamicExceptions, 12978 ArrayRef<SourceRange> DynamicExceptionRanges, 12979 Expr *NoexceptExpr, 12980 SmallVectorImpl<QualType> &Exceptions, 12981 FunctionProtoType::ExceptionSpecInfo &ESI) { 12982 Exceptions.clear(); 12983 ESI.Type = EST; 12984 if (EST == EST_Dynamic) { 12985 Exceptions.reserve(DynamicExceptions.size()); 12986 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12987 // FIXME: Preserve type source info. 12988 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12989 12990 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12991 collectUnexpandedParameterPacks(ET, Unexpanded); 12992 if (!Unexpanded.empty()) { 12993 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12994 UPPC_ExceptionType, 12995 Unexpanded); 12996 continue; 12997 } 12998 12999 // Check that the type is valid for an exception spec, and 13000 // drop it if not. 13001 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13002 Exceptions.push_back(ET); 13003 } 13004 ESI.Exceptions = Exceptions; 13005 return; 13006 } 13007 13008 if (EST == EST_ComputedNoexcept) { 13009 // If an error occurred, there's no expression here. 13010 if (NoexceptExpr) { 13011 assert((NoexceptExpr->isTypeDependent() || 13012 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13013 Context.BoolTy) && 13014 "Parser should have made sure that the expression is boolean"); 13015 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13016 ESI.Type = EST_BasicNoexcept; 13017 return; 13018 } 13019 13020 if (!NoexceptExpr->isValueDependent()) 13021 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13022 diag::err_noexcept_needs_constant_expression, 13023 /*AllowFold*/ false).get(); 13024 ESI.NoexceptExpr = NoexceptExpr; 13025 } 13026 return; 13027 } 13028 } 13029 13030 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 13031 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 13032 // Implicitly declared functions (e.g. copy constructors) are 13033 // __host__ __device__ 13034 if (D->isImplicit()) 13035 return CFT_HostDevice; 13036 13037 if (D->hasAttr<CUDAGlobalAttr>()) 13038 return CFT_Global; 13039 13040 if (D->hasAttr<CUDADeviceAttr>()) { 13041 if (D->hasAttr<CUDAHostAttr>()) 13042 return CFT_HostDevice; 13043 return CFT_Device; 13044 } 13045 13046 return CFT_Host; 13047 } 13048 13049 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 13050 CUDAFunctionTarget CalleeTarget) { 13051 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 13052 // Callable from the device only." 13053 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 13054 return true; 13055 13056 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 13057 // Callable from the host only." 13058 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 13059 // Callable from the host only." 13060 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 13061 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 13062 return true; 13063 13064 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 13065 return true; 13066 13067 return false; 13068 } 13069 13070 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13071 /// 13072 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13073 SourceLocation DeclStart, 13074 Declarator &D, Expr *BitWidth, 13075 InClassInitStyle InitStyle, 13076 AccessSpecifier AS, 13077 AttributeList *MSPropertyAttr) { 13078 IdentifierInfo *II = D.getIdentifier(); 13079 if (!II) { 13080 Diag(DeclStart, diag::err_anonymous_property); 13081 return nullptr; 13082 } 13083 SourceLocation Loc = D.getIdentifierLoc(); 13084 13085 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13086 QualType T = TInfo->getType(); 13087 if (getLangOpts().CPlusPlus) { 13088 CheckExtraCXXDefaultArguments(D); 13089 13090 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13091 UPPC_DataMemberType)) { 13092 D.setInvalidType(); 13093 T = Context.IntTy; 13094 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13095 } 13096 } 13097 13098 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13099 13100 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13101 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13102 diag::err_invalid_thread) 13103 << DeclSpec::getSpecifierName(TSCS); 13104 13105 // Check to see if this name was declared as a member previously 13106 NamedDecl *PrevDecl = nullptr; 13107 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13108 LookupName(Previous, S); 13109 switch (Previous.getResultKind()) { 13110 case LookupResult::Found: 13111 case LookupResult::FoundUnresolvedValue: 13112 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13113 break; 13114 13115 case LookupResult::FoundOverloaded: 13116 PrevDecl = Previous.getRepresentativeDecl(); 13117 break; 13118 13119 case LookupResult::NotFound: 13120 case LookupResult::NotFoundInCurrentInstantiation: 13121 case LookupResult::Ambiguous: 13122 break; 13123 } 13124 13125 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13126 // Maybe we will complain about the shadowed template parameter. 13127 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13128 // Just pretend that we didn't see the previous declaration. 13129 PrevDecl = nullptr; 13130 } 13131 13132 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13133 PrevDecl = nullptr; 13134 13135 SourceLocation TSSL = D.getLocStart(); 13136 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13137 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13138 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13139 ProcessDeclAttributes(TUScope, NewPD, D); 13140 NewPD->setAccess(AS); 13141 13142 if (NewPD->isInvalidDecl()) 13143 Record->setInvalidDecl(); 13144 13145 if (D.getDeclSpec().isModulePrivateSpecified()) 13146 NewPD->setModulePrivate(); 13147 13148 if (NewPD->isInvalidDecl() && PrevDecl) { 13149 // Don't introduce NewFD into scope; there's already something 13150 // with the same name in the same scope. 13151 } else if (II) { 13152 PushOnScopeChains(NewPD, S); 13153 } else 13154 Record->addDecl(NewPD); 13155 13156 return NewPD; 13157 } 13158