1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.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 "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param, 258 Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new(Context) 385 OpaqueValueExpr(EqualLoc, 386 Param->getType().getNonReferenceType(), 387 VK_RValue)); 388 } 389 390 /// CheckExtraCXXDefaultArguments - Check for any extra default 391 /// arguments in the declarator, which is not a function declaration 392 /// or definition and therefore is not permitted to have default 393 /// arguments. This routine should be invoked for every declarator 394 /// that is not a function declaration or definition. 395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 396 // C++ [dcl.fct.default]p3 397 // A default argument expression shall be specified only in the 398 // parameter-declaration-clause of a function declaration or in a 399 // template-parameter (14.1). It shall not be specified for a 400 // parameter pack. If it is specified in a 401 // parameter-declaration-clause, it shall not occur within a 402 // declarator or abstract-declarator of a parameter-declaration. 403 bool MightBeFunction = D.isFunctionDeclarationContext(); 404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 405 DeclaratorChunk &chunk = D.getTypeObject(i); 406 if (chunk.Kind == DeclaratorChunk::Function) { 407 if (MightBeFunction) { 408 // This is a function declaration. It can have default arguments, but 409 // keep looking in case its return type is a function type with default 410 // arguments. 411 MightBeFunction = false; 412 continue; 413 } 414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 415 ++argIdx) { 416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 417 if (Param->hasUnparsedDefaultArg()) { 418 std::unique_ptr<CachedTokens> Toks = 419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 420 SourceRange SR; 421 if (Toks->size() > 1) 422 SR = SourceRange((*Toks)[1].getLocation(), 423 Toks->back().getLocation()); 424 else 425 SR = UnparsedDefaultArgLocs[Param]; 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << SR; 428 } else if (Param->getDefaultArg()) { 429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 430 << Param->getDefaultArg()->getSourceRange(); 431 Param->setDefaultArg(nullptr); 432 } 433 } 434 } else if (chunk.Kind != DeclaratorChunk::Paren) { 435 MightBeFunction = false; 436 } 437 } 438 } 439 440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 443 }); 444 } 445 446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 447 /// function, once we already know that they have the same 448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 449 /// error, false otherwise. 450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 451 Scope *S) { 452 bool Invalid = false; 453 454 // The declaration context corresponding to the scope is the semantic 455 // parent, unless this is a local function declaration, in which case 456 // it is that surrounding function. 457 DeclContext *ScopeDC = New->isLocalExternDecl() 458 ? New->getLexicalDeclContext() 459 : New->getDeclContext(); 460 461 // Find the previous declaration for the purpose of default arguments. 462 FunctionDecl *PrevForDefaultArgs = Old; 463 for (/**/; PrevForDefaultArgs; 464 // Don't bother looking back past the latest decl if this is a local 465 // extern declaration; nothing else could work. 466 PrevForDefaultArgs = New->isLocalExternDecl() 467 ? nullptr 468 : PrevForDefaultArgs->getPreviousDecl()) { 469 // Ignore hidden declarations. 470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 471 continue; 472 473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 474 !New->isCXXClassMember()) { 475 // Ignore default arguments of old decl if they are not in 476 // the same scope and this is not an out-of-line definition of 477 // a member function. 478 continue; 479 } 480 481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 482 // If only one of these is a local function declaration, then they are 483 // declared in different scopes, even though isDeclInScope may think 484 // they're in the same scope. (If both are local, the scope check is 485 // sufficient, and if neither is local, then they are in the same scope.) 486 continue; 487 } 488 489 // We found the right previous declaration. 490 break; 491 } 492 493 // C++ [dcl.fct.default]p4: 494 // For non-template functions, default arguments can be added in 495 // later declarations of a function in the same 496 // scope. Declarations in different scopes have completely 497 // distinct sets of default arguments. That is, declarations in 498 // inner scopes do not acquire default arguments from 499 // declarations in outer scopes, and vice versa. In a given 500 // function declaration, all parameters subsequent to a 501 // parameter with a default argument shall have default 502 // arguments supplied in this or previous declarations. A 503 // default argument shall not be redefined by a later 504 // declaration (not even to the same value). 505 // 506 // C++ [dcl.fct.default]p6: 507 // Except for member functions of class templates, the default arguments 508 // in a member function definition that appears outside of the class 509 // definition are added to the set of default arguments provided by the 510 // member function declaration in the class definition. 511 for (unsigned p = 0, NumParams = PrevForDefaultArgs 512 ? PrevForDefaultArgs->getNumParams() 513 : 0; 514 p < NumParams; ++p) { 515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 516 ParmVarDecl *NewParam = New->getParamDecl(p); 517 518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 519 bool NewParamHasDfl = NewParam->hasDefaultArg(); 520 521 if (OldParamHasDfl && NewParamHasDfl) { 522 unsigned DiagDefaultParamID = 523 diag::err_param_default_argument_redefinition; 524 525 // MSVC accepts that default parameters be redefined for member functions 526 // of template class. The new default parameter's value is ignored. 527 Invalid = true; 528 if (getLangOpts().MicrosoftExt) { 529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 530 if (MD && MD->getParent()->getDescribedClassTemplate()) { 531 // Merge the old default argument into the new parameter. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUninstantiatedDefaultArg()) 534 NewParam->setUninstantiatedDefaultArg( 535 OldParam->getUninstantiatedDefaultArg()); 536 else 537 NewParam->setDefaultArg(OldParam->getInit()); 538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 539 Invalid = false; 540 } 541 } 542 543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 544 // hint here. Alternatively, we could walk the type-source information 545 // for NewParam to find the last source location in the type... but it 546 // isn't worth the effort right now. This is the kind of test case that 547 // is hard to get right: 548 // int f(int); 549 // void g(int (*fp)(int) = f); 550 // void g(int (*fp)(int) = &f); 551 Diag(NewParam->getLocation(), DiagDefaultParamID) 552 << NewParam->getDefaultArgRange(); 553 554 // Look for the function declaration where the default argument was 555 // actually written, which may be a declaration prior to Old. 556 for (auto Older = PrevForDefaultArgs; 557 OldParam->hasInheritedDefaultArg(); /**/) { 558 Older = Older->getPreviousDecl(); 559 OldParam = Older->getParamDecl(p); 560 } 561 562 Diag(OldParam->getLocation(), diag::note_previous_definition) 563 << OldParam->getDefaultArgRange(); 564 } else if (OldParamHasDfl) { 565 // Merge the old default argument into the new parameter unless the new 566 // function is a friend declaration in a template class. In the latter 567 // case the default arguments will be inherited when the friend 568 // declaration will be instantiated. 569 if (New->getFriendObjectKind() == Decl::FOK_None || 570 !New->getLexicalDeclContext()->isDependentContext()) { 571 // It's important to use getInit() here; getDefaultArg() 572 // strips off any top-level ExprWithCleanups. 573 NewParam->setHasInheritedDefaultArg(); 574 if (OldParam->hasUnparsedDefaultArg()) 575 NewParam->setUnparsedDefaultArg(); 576 else if (OldParam->hasUninstantiatedDefaultArg()) 577 NewParam->setUninstantiatedDefaultArg( 578 OldParam->getUninstantiatedDefaultArg()); 579 else 580 NewParam->setDefaultArg(OldParam->getInit()); 581 } 582 } else if (NewParamHasDfl) { 583 if (New->getDescribedFunctionTemplate()) { 584 // Paragraph 4, quoted above, only applies to non-template functions. 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_template_redecl) 587 << NewParam->getDefaultArgRange(); 588 Diag(PrevForDefaultArgs->getLocation(), 589 diag::note_template_prev_declaration) 590 << false; 591 } else if (New->getTemplateSpecializationKind() 592 != TSK_ImplicitInstantiation && 593 New->getTemplateSpecializationKind() != TSK_Undeclared) { 594 // C++ [temp.expr.spec]p21: 595 // Default function arguments shall not be specified in a declaration 596 // or a definition for one of the following explicit specializations: 597 // - the explicit specialization of a function template; 598 // - the explicit specialization of a member function template; 599 // - the explicit specialization of a member function of a class 600 // template where the class template specialization to which the 601 // member function specialization belongs is implicitly 602 // instantiated. 603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 605 << New->getDeclName() 606 << NewParam->getDefaultArgRange(); 607 } else if (New->getDeclContext()->isDependentContext()) { 608 // C++ [dcl.fct.default]p6 (DR217): 609 // Default arguments for a member function of a class template shall 610 // be specified on the initial declaration of the member function 611 // within the class template. 612 // 613 // Reading the tea leaves a bit in DR217 and its reference to DR205 614 // leads me to the conclusion that one cannot add default function 615 // arguments for an out-of-line definition of a member function of a 616 // dependent type. 617 int WhichKind = 2; 618 if (CXXRecordDecl *Record 619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 620 if (Record->getDescribedClassTemplate()) 621 WhichKind = 0; 622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 623 WhichKind = 1; 624 else 625 WhichKind = 2; 626 } 627 628 Diag(NewParam->getLocation(), 629 diag::err_param_default_argument_member_template_redecl) 630 << WhichKind 631 << NewParam->getDefaultArgRange(); 632 } 633 } 634 } 635 636 // DR1344: If a default argument is added outside a class definition and that 637 // default argument makes the function a special member function, the program 638 // is ill-formed. This can only happen for constructors. 639 if (isa<CXXConstructorDecl>(New) && 640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 643 if (NewSM != OldSM) { 644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 645 assert(NewParam->hasDefaultArg()); 646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 647 << NewParam->getDefaultArgRange() << NewSM; 648 Diag(Old->getLocation(), diag::note_previous_declaration); 649 } 650 } 651 652 const FunctionDecl *Def; 653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 654 // template has a constexpr specifier then all its declarations shall 655 // contain the constexpr specifier. 656 if (New->getConstexprKind() != Old->getConstexprKind()) { 657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 658 << New << New->getConstexprKind() << Old->getConstexprKind(); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 662 Old->isDefined(Def) && 663 // If a friend function is inlined but does not have 'inline' 664 // specifier, it is a definition. Do not report attribute conflict 665 // in this case, redefinition will be diagnosed later. 666 (New->isInlineSpecified() || 667 New->getFriendObjectKind() == Decl::FOK_None)) { 668 // C++11 [dcl.fcn.spec]p4: 669 // If the definition of a function appears in a translation unit before its 670 // first declaration as inline, the program is ill-formed. 671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 672 Diag(Def->getLocation(), diag::note_previous_definition); 673 Invalid = true; 674 } 675 676 // C++17 [temp.deduct.guide]p3: 677 // Two deduction guide declarations in the same translation unit 678 // for the same class template shall not have equivalent 679 // parameter-declaration-clauses. 680 if (isa<CXXDeductionGuideDecl>(New) && 681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 683 Diag(Old->getLocation(), diag::note_previous_declaration); 684 } 685 686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 687 // argument expression, that declaration shall be a definition and shall be 688 // the only declaration of the function or function template in the 689 // translation unit. 690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 691 functionDeclHasDefaultArgument(Old)) { 692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 693 Diag(Old->getLocation(), diag::note_previous_declaration); 694 Invalid = true; 695 } 696 697 return Invalid; 698 } 699 700 NamedDecl * 701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 702 MultiTemplateParamsArg TemplateParamLists) { 703 assert(D.isDecompositionDeclarator()); 704 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 705 706 // The syntax only allows a decomposition declarator as a simple-declaration, 707 // a for-range-declaration, or a condition in Clang, but we parse it in more 708 // cases than that. 709 if (!D.mayHaveDecompositionDeclarator()) { 710 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 711 << Decomp.getSourceRange(); 712 return nullptr; 713 } 714 715 if (!TemplateParamLists.empty()) { 716 // FIXME: There's no rule against this, but there are also no rules that 717 // would actually make it usable, so we reject it for now. 718 Diag(TemplateParamLists.front()->getTemplateLoc(), 719 diag::err_decomp_decl_template); 720 return nullptr; 721 } 722 723 Diag(Decomp.getLSquareLoc(), 724 !getLangOpts().CPlusPlus17 725 ? diag::ext_decomp_decl 726 : D.getContext() == DeclaratorContext::ConditionContext 727 ? diag::ext_decomp_decl_cond 728 : diag::warn_cxx14_compat_decomp_decl) 729 << Decomp.getSourceRange(); 730 731 // The semantic context is always just the current context. 732 DeclContext *const DC = CurContext; 733 734 // C++17 [dcl.dcl]/8: 735 // The decl-specifier-seq shall contain only the type-specifier auto 736 // and cv-qualifiers. 737 // C++2a [dcl.dcl]/8: 738 // If decl-specifier-seq contains any decl-specifier other than static, 739 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 740 auto &DS = D.getDeclSpec(); 741 { 742 SmallVector<StringRef, 8> BadSpecifiers; 743 SmallVector<SourceLocation, 8> BadSpecifierLocs; 744 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 745 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 746 if (auto SCS = DS.getStorageClassSpec()) { 747 if (SCS == DeclSpec::SCS_static) { 748 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 749 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 750 } else { 751 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 752 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 753 } 754 } 755 if (auto TSCS = DS.getThreadStorageClassSpec()) { 756 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 757 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 758 } 759 if (DS.hasConstexprSpecifier()) { 760 BadSpecifiers.push_back( 761 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 762 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 763 } 764 if (DS.isInlineSpecified()) { 765 BadSpecifiers.push_back("inline"); 766 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 767 } 768 if (!BadSpecifiers.empty()) { 769 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 770 Err << (int)BadSpecifiers.size() 771 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 772 // Don't add FixItHints to remove the specifiers; we do still respect 773 // them when building the underlying variable. 774 for (auto Loc : BadSpecifierLocs) 775 Err << SourceRange(Loc, Loc); 776 } else if (!CPlusPlus20Specifiers.empty()) { 777 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 778 getLangOpts().CPlusPlus20 779 ? diag::warn_cxx17_compat_decomp_decl_spec 780 : diag::ext_decomp_decl_spec); 781 Warn << (int)CPlusPlus20Specifiers.size() 782 << llvm::join(CPlusPlus20Specifiers.begin(), 783 CPlusPlus20Specifiers.end(), " "); 784 for (auto Loc : CPlusPlus20SpecifierLocs) 785 Warn << SourceRange(Loc, Loc); 786 } 787 // We can't recover from it being declared as a typedef. 788 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 789 return nullptr; 790 } 791 792 // C++2a [dcl.struct.bind]p1: 793 // A cv that includes volatile is deprecated 794 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 795 getLangOpts().CPlusPlus20) 796 Diag(DS.getVolatileSpecLoc(), 797 diag::warn_deprecated_volatile_structured_binding); 798 799 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 800 QualType R = TInfo->getType(); 801 802 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 803 UPPC_DeclarationType)) 804 D.setInvalidType(); 805 806 // The syntax only allows a single ref-qualifier prior to the decomposition 807 // declarator. No other declarator chunks are permitted. Also check the type 808 // specifier here. 809 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 810 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 811 (D.getNumTypeObjects() == 1 && 812 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 813 Diag(Decomp.getLSquareLoc(), 814 (D.hasGroupingParens() || 815 (D.getNumTypeObjects() && 816 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 817 ? diag::err_decomp_decl_parens 818 : diag::err_decomp_decl_type) 819 << R; 820 821 // In most cases, there's no actual problem with an explicitly-specified 822 // type, but a function type won't work here, and ActOnVariableDeclarator 823 // shouldn't be called for such a type. 824 if (R->isFunctionType()) 825 D.setInvalidType(); 826 } 827 828 // Build the BindingDecls. 829 SmallVector<BindingDecl*, 8> Bindings; 830 831 // Build the BindingDecls. 832 for (auto &B : D.getDecompositionDeclarator().bindings()) { 833 // Check for name conflicts. 834 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 835 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 836 ForVisibleRedeclaration); 837 LookupName(Previous, S, 838 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 839 840 // It's not permitted to shadow a template parameter name. 841 if (Previous.isSingleResult() && 842 Previous.getFoundDecl()->isTemplateParameter()) { 843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 844 Previous.getFoundDecl()); 845 Previous.clear(); 846 } 847 848 bool ConsiderLinkage = DC->isFunctionOrMethod() && 849 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 850 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 851 /*AllowInlineNamespace*/false); 852 if (!Previous.empty()) { 853 auto *Old = Previous.getRepresentativeDecl(); 854 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 855 Diag(Old->getLocation(), diag::note_previous_definition); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 PushOnScopeChains(BD, S, true); 860 Bindings.push_back(BD); 861 ParsingInitForAutoVars.insert(BD); 862 } 863 864 // There are no prior lookup results for the variable itself, because it 865 // is unnamed. 866 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 867 Decomp.getLSquareLoc()); 868 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 869 ForVisibleRedeclaration); 870 871 // Build the variable that holds the non-decomposed object. 872 bool AddToScope = true; 873 NamedDecl *New = 874 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 875 MultiTemplateParamsArg(), AddToScope, Bindings); 876 if (AddToScope) { 877 S->AddDecl(New); 878 CurContext->addHiddenDecl(New); 879 } 880 881 if (isInOpenMPDeclareTargetContext()) 882 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 883 884 return New; 885 } 886 887 static bool checkSimpleDecomposition( 888 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 889 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 890 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 891 if ((int64_t)Bindings.size() != NumElems) { 892 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 893 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 894 << (NumElems < Bindings.size()); 895 return true; 896 } 897 898 unsigned I = 0; 899 for (auto *B : Bindings) { 900 SourceLocation Loc = B->getLocation(); 901 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 902 if (E.isInvalid()) 903 return true; 904 E = GetInit(Loc, E.get(), I++); 905 if (E.isInvalid()) 906 return true; 907 B->setBinding(ElemType, E.get()); 908 } 909 910 return false; 911 } 912 913 static bool checkArrayLikeDecomposition(Sema &S, 914 ArrayRef<BindingDecl *> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const llvm::APSInt &NumElems, 917 QualType ElemType) { 918 return checkSimpleDecomposition( 919 S, Bindings, Src, DecompType, NumElems, ElemType, 920 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 921 ExprResult E = S.ActOnIntegerConstant(Loc, I); 922 if (E.isInvalid()) 923 return ExprError(); 924 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 925 }); 926 } 927 928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 929 ValueDecl *Src, QualType DecompType, 930 const ConstantArrayType *CAT) { 931 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 932 llvm::APSInt(CAT->getSize()), 933 CAT->getElementType()); 934 } 935 936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 937 ValueDecl *Src, QualType DecompType, 938 const VectorType *VT) { 939 return checkArrayLikeDecomposition( 940 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 941 S.Context.getQualifiedType(VT->getElementType(), 942 DecompType.getQualifiers())); 943 } 944 945 static bool checkComplexDecomposition(Sema &S, 946 ArrayRef<BindingDecl *> Bindings, 947 ValueDecl *Src, QualType DecompType, 948 const ComplexType *CT) { 949 return checkSimpleDecomposition( 950 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 951 S.Context.getQualifiedType(CT->getElementType(), 952 DecompType.getQualifiers()), 953 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 954 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 955 }); 956 } 957 958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 959 TemplateArgumentListInfo &Args) { 960 SmallString<128> SS; 961 llvm::raw_svector_ostream OS(SS); 962 bool First = true; 963 for (auto &Arg : Args.arguments()) { 964 if (!First) 965 OS << ", "; 966 Arg.getArgument().print(PrintingPolicy, OS); 967 First = false; 968 } 969 return std::string(OS.str()); 970 } 971 972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 973 SourceLocation Loc, StringRef Trait, 974 TemplateArgumentListInfo &Args, 975 unsigned DiagID) { 976 auto DiagnoseMissing = [&] { 977 if (DiagID) 978 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 979 Args); 980 return true; 981 }; 982 983 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 984 NamespaceDecl *Std = S.getStdNamespace(); 985 if (!Std) 986 return DiagnoseMissing(); 987 988 // Look up the trait itself, within namespace std. We can diagnose various 989 // problems with this lookup even if we've been asked to not diagnose a 990 // missing specialization, because this can only fail if the user has been 991 // declaring their own names in namespace std or we don't support the 992 // standard library implementation in use. 993 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 994 Loc, Sema::LookupOrdinaryName); 995 if (!S.LookupQualifiedName(Result, Std)) 996 return DiagnoseMissing(); 997 if (Result.isAmbiguous()) 998 return true; 999 1000 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1001 if (!TraitTD) { 1002 Result.suppressDiagnostics(); 1003 NamedDecl *Found = *Result.begin(); 1004 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1005 S.Diag(Found->getLocation(), diag::note_declared_at); 1006 return true; 1007 } 1008 1009 // Build the template-id. 1010 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1011 if (TraitTy.isNull()) 1012 return true; 1013 if (!S.isCompleteType(Loc, TraitTy)) { 1014 if (DiagID) 1015 S.RequireCompleteType( 1016 Loc, TraitTy, DiagID, 1017 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1018 return true; 1019 } 1020 1021 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1022 assert(RD && "specialization of class template is not a class?"); 1023 1024 // Look up the member of the trait type. 1025 S.LookupQualifiedName(TraitMemberLookup, RD); 1026 return TraitMemberLookup.isAmbiguous(); 1027 } 1028 1029 static TemplateArgumentLoc 1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1031 uint64_t I) { 1032 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1033 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1034 } 1035 1036 static TemplateArgumentLoc 1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1038 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1039 } 1040 1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1042 1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1044 llvm::APSInt &Size) { 1045 EnterExpressionEvaluationContext ContextRAII( 1046 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1047 1048 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1049 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1050 1051 // Form template argument list for tuple_size<T>. 1052 TemplateArgumentListInfo Args(Loc, Loc); 1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1054 1055 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1056 // it's not tuple-like. 1057 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1058 R.empty()) 1059 return IsTupleLike::NotTupleLike; 1060 1061 // If we get this far, we've committed to the tuple interpretation, but 1062 // we can still fail if there actually isn't a usable ::value. 1063 1064 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1065 LookupResult &R; 1066 TemplateArgumentListInfo &Args; 1067 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1068 : R(R), Args(Args) {} 1069 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1070 SourceLocation Loc) override { 1071 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1072 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1073 } 1074 } Diagnoser(R, Args); 1075 1076 ExprResult E = 1077 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1078 if (E.isInvalid()) 1079 return IsTupleLike::Error; 1080 1081 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1082 if (E.isInvalid()) 1083 return IsTupleLike::Error; 1084 1085 return IsTupleLike::TupleLike; 1086 } 1087 1088 /// \return std::tuple_element<I, T>::type. 1089 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1090 unsigned I, QualType T) { 1091 // Form template argument list for tuple_element<I, T>. 1092 TemplateArgumentListInfo Args(Loc, Loc); 1093 Args.addArgument( 1094 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1095 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1096 1097 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1098 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1099 if (lookupStdTypeTraitMember( 1100 S, R, Loc, "tuple_element", Args, 1101 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1102 return QualType(); 1103 1104 auto *TD = R.getAsSingle<TypeDecl>(); 1105 if (!TD) { 1106 R.suppressDiagnostics(); 1107 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1108 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1109 if (!R.empty()) 1110 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1111 return QualType(); 1112 } 1113 1114 return S.Context.getTypeDeclType(TD); 1115 } 1116 1117 namespace { 1118 struct InitializingBinding { 1119 Sema &S; 1120 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1121 Sema::CodeSynthesisContext Ctx; 1122 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1123 Ctx.PointOfInstantiation = BD->getLocation(); 1124 Ctx.Entity = BD; 1125 S.pushCodeSynthesisContext(Ctx); 1126 } 1127 ~InitializingBinding() { 1128 S.popCodeSynthesisContext(); 1129 } 1130 }; 1131 } 1132 1133 static bool checkTupleLikeDecomposition(Sema &S, 1134 ArrayRef<BindingDecl *> Bindings, 1135 VarDecl *Src, QualType DecompType, 1136 const llvm::APSInt &TupleSize) { 1137 if ((int64_t)Bindings.size() != TupleSize) { 1138 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1139 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1140 << (TupleSize < Bindings.size()); 1141 return true; 1142 } 1143 1144 if (Bindings.empty()) 1145 return false; 1146 1147 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1148 1149 // [dcl.decomp]p3: 1150 // The unqualified-id get is looked up in the scope of E by class member 1151 // access lookup ... 1152 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1153 bool UseMemberGet = false; 1154 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1155 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1156 S.LookupQualifiedName(MemberGet, RD); 1157 if (MemberGet.isAmbiguous()) 1158 return true; 1159 // ... and if that finds at least one declaration that is a function 1160 // template whose first template parameter is a non-type parameter ... 1161 for (NamedDecl *D : MemberGet) { 1162 if (FunctionTemplateDecl *FTD = 1163 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1164 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1165 if (TPL->size() != 0 && 1166 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1167 // ... the initializer is e.get<i>(). 1168 UseMemberGet = true; 1169 break; 1170 } 1171 } 1172 } 1173 } 1174 1175 unsigned I = 0; 1176 for (auto *B : Bindings) { 1177 InitializingBinding InitContext(S, B); 1178 SourceLocation Loc = B->getLocation(); 1179 1180 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1181 if (E.isInvalid()) 1182 return true; 1183 1184 // e is an lvalue if the type of the entity is an lvalue reference and 1185 // an xvalue otherwise 1186 if (!Src->getType()->isLValueReferenceType()) 1187 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1188 E.get(), nullptr, VK_XValue, 1189 FPOptionsOverride()); 1190 1191 TemplateArgumentListInfo Args(Loc, Loc); 1192 Args.addArgument( 1193 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1194 1195 if (UseMemberGet) { 1196 // if [lookup of member get] finds at least one declaration, the 1197 // initializer is e.get<i-1>(). 1198 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1199 CXXScopeSpec(), SourceLocation(), nullptr, 1200 MemberGet, &Args, nullptr); 1201 if (E.isInvalid()) 1202 return true; 1203 1204 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1205 } else { 1206 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1207 // in the associated namespaces. 1208 Expr *Get = UnresolvedLookupExpr::Create( 1209 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1210 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1211 UnresolvedSetIterator(), UnresolvedSetIterator()); 1212 1213 Expr *Arg = E.get(); 1214 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1215 } 1216 if (E.isInvalid()) 1217 return true; 1218 Expr *Init = E.get(); 1219 1220 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1221 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1222 if (T.isNull()) 1223 return true; 1224 1225 // each vi is a variable of type "reference to T" initialized with the 1226 // initializer, where the reference is an lvalue reference if the 1227 // initializer is an lvalue and an rvalue reference otherwise 1228 QualType RefType = 1229 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1230 if (RefType.isNull()) 1231 return true; 1232 auto *RefVD = VarDecl::Create( 1233 S.Context, Src->getDeclContext(), Loc, Loc, 1234 B->getDeclName().getAsIdentifierInfo(), RefType, 1235 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1236 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1237 RefVD->setTSCSpec(Src->getTSCSpec()); 1238 RefVD->setImplicit(); 1239 if (Src->isInlineSpecified()) 1240 RefVD->setInlineSpecified(); 1241 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1242 1243 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1244 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1245 InitializationSequence Seq(S, Entity, Kind, Init); 1246 E = Seq.Perform(S, Entity, Kind, Init); 1247 if (E.isInvalid()) 1248 return true; 1249 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1250 if (E.isInvalid()) 1251 return true; 1252 RefVD->setInit(E.get()); 1253 if (!E.get()->isValueDependent()) 1254 RefVD->checkInitIsICE(); 1255 1256 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1257 DeclarationNameInfo(B->getDeclName(), Loc), 1258 RefVD); 1259 if (E.isInvalid()) 1260 return true; 1261 1262 B->setBinding(T, E.get()); 1263 I++; 1264 } 1265 1266 return false; 1267 } 1268 1269 /// Find the base class to decompose in a built-in decomposition of a class type. 1270 /// This base class search is, unfortunately, not quite like any other that we 1271 /// perform anywhere else in C++. 1272 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1273 const CXXRecordDecl *RD, 1274 CXXCastPath &BasePath) { 1275 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1276 CXXBasePath &Path) { 1277 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1278 }; 1279 1280 const CXXRecordDecl *ClassWithFields = nullptr; 1281 AccessSpecifier AS = AS_public; 1282 if (RD->hasDirectFields()) 1283 // [dcl.decomp]p4: 1284 // Otherwise, all of E's non-static data members shall be public direct 1285 // members of E ... 1286 ClassWithFields = RD; 1287 else { 1288 // ... or of ... 1289 CXXBasePaths Paths; 1290 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1291 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1292 // If no classes have fields, just decompose RD itself. (This will work 1293 // if and only if zero bindings were provided.) 1294 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1295 } 1296 1297 CXXBasePath *BestPath = nullptr; 1298 for (auto &P : Paths) { 1299 if (!BestPath) 1300 BestPath = &P; 1301 else if (!S.Context.hasSameType(P.back().Base->getType(), 1302 BestPath->back().Base->getType())) { 1303 // ... the same ... 1304 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1305 << false << RD << BestPath->back().Base->getType() 1306 << P.back().Base->getType(); 1307 return DeclAccessPair(); 1308 } else if (P.Access < BestPath->Access) { 1309 BestPath = &P; 1310 } 1311 } 1312 1313 // ... unambiguous ... 1314 QualType BaseType = BestPath->back().Base->getType(); 1315 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1316 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1317 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1318 return DeclAccessPair(); 1319 } 1320 1321 // ... [accessible, implied by other rules] base class of E. 1322 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1323 *BestPath, diag::err_decomp_decl_inaccessible_base); 1324 AS = BestPath->Access; 1325 1326 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1327 S.BuildBasePathArray(Paths, BasePath); 1328 } 1329 1330 // The above search did not check whether the selected class itself has base 1331 // classes with fields, so check that now. 1332 CXXBasePaths Paths; 1333 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1334 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1335 << (ClassWithFields == RD) << RD << ClassWithFields 1336 << Paths.front().back().Base->getType(); 1337 return DeclAccessPair(); 1338 } 1339 1340 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1341 } 1342 1343 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1344 ValueDecl *Src, QualType DecompType, 1345 const CXXRecordDecl *OrigRD) { 1346 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1347 diag::err_incomplete_type)) 1348 return true; 1349 1350 CXXCastPath BasePath; 1351 DeclAccessPair BasePair = 1352 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1353 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1354 if (!RD) 1355 return true; 1356 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1357 DecompType.getQualifiers()); 1358 1359 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1360 unsigned NumFields = 1361 std::count_if(RD->field_begin(), RD->field_end(), 1362 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1363 assert(Bindings.size() != NumFields); 1364 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1365 << DecompType << (unsigned)Bindings.size() << NumFields 1366 << (NumFields < Bindings.size()); 1367 return true; 1368 }; 1369 1370 // all of E's non-static data members shall be [...] well-formed 1371 // when named as e.name in the context of the structured binding, 1372 // E shall not have an anonymous union member, ... 1373 unsigned I = 0; 1374 for (auto *FD : RD->fields()) { 1375 if (FD->isUnnamedBitfield()) 1376 continue; 1377 1378 if (FD->isAnonymousStructOrUnion()) { 1379 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1380 << DecompType << FD->getType()->isUnionType(); 1381 S.Diag(FD->getLocation(), diag::note_declared_at); 1382 return true; 1383 } 1384 1385 // We have a real field to bind. 1386 if (I >= Bindings.size()) 1387 return DiagnoseBadNumberOfBindings(); 1388 auto *B = Bindings[I++]; 1389 SourceLocation Loc = B->getLocation(); 1390 1391 // The field must be accessible in the context of the structured binding. 1392 // We already checked that the base class is accessible. 1393 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1394 // const_cast here. 1395 S.CheckStructuredBindingMemberAccess( 1396 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1397 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1398 BasePair.getAccess(), FD->getAccess()))); 1399 1400 // Initialize the binding to Src.FD. 1401 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1402 if (E.isInvalid()) 1403 return true; 1404 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1405 VK_LValue, &BasePath); 1406 if (E.isInvalid()) 1407 return true; 1408 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1409 CXXScopeSpec(), FD, 1410 DeclAccessPair::make(FD, FD->getAccess()), 1411 DeclarationNameInfo(FD->getDeclName(), Loc)); 1412 if (E.isInvalid()) 1413 return true; 1414 1415 // If the type of the member is T, the referenced type is cv T, where cv is 1416 // the cv-qualification of the decomposition expression. 1417 // 1418 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1419 // 'const' to the type of the field. 1420 Qualifiers Q = DecompType.getQualifiers(); 1421 if (FD->isMutable()) 1422 Q.removeConst(); 1423 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1424 } 1425 1426 if (I != Bindings.size()) 1427 return DiagnoseBadNumberOfBindings(); 1428 1429 return false; 1430 } 1431 1432 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1433 QualType DecompType = DD->getType(); 1434 1435 // If the type of the decomposition is dependent, then so is the type of 1436 // each binding. 1437 if (DecompType->isDependentType()) { 1438 for (auto *B : DD->bindings()) 1439 B->setType(Context.DependentTy); 1440 return; 1441 } 1442 1443 DecompType = DecompType.getNonReferenceType(); 1444 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1445 1446 // C++1z [dcl.decomp]/2: 1447 // If E is an array type [...] 1448 // As an extension, we also support decomposition of built-in complex and 1449 // vector types. 1450 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1451 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1452 DD->setInvalidDecl(); 1453 return; 1454 } 1455 if (auto *VT = DecompType->getAs<VectorType>()) { 1456 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1457 DD->setInvalidDecl(); 1458 return; 1459 } 1460 if (auto *CT = DecompType->getAs<ComplexType>()) { 1461 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1462 DD->setInvalidDecl(); 1463 return; 1464 } 1465 1466 // C++1z [dcl.decomp]/3: 1467 // if the expression std::tuple_size<E>::value is a well-formed integral 1468 // constant expression, [...] 1469 llvm::APSInt TupleSize(32); 1470 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1471 case IsTupleLike::Error: 1472 DD->setInvalidDecl(); 1473 return; 1474 1475 case IsTupleLike::TupleLike: 1476 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1477 DD->setInvalidDecl(); 1478 return; 1479 1480 case IsTupleLike::NotTupleLike: 1481 break; 1482 } 1483 1484 // C++1z [dcl.dcl]/8: 1485 // [E shall be of array or non-union class type] 1486 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1487 if (!RD || RD->isUnion()) { 1488 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1489 << DD << !RD << DecompType; 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 1494 // C++1z [dcl.decomp]/4: 1495 // all of E's non-static data members shall be [...] direct members of 1496 // E or of the same unambiguous public base class of E, ... 1497 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1498 DD->setInvalidDecl(); 1499 } 1500 1501 /// Merge the exception specifications of two variable declarations. 1502 /// 1503 /// This is called when there's a redeclaration of a VarDecl. The function 1504 /// checks if the redeclaration might have an exception specification and 1505 /// validates compatibility and merges the specs if necessary. 1506 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1507 // Shortcut if exceptions are disabled. 1508 if (!getLangOpts().CXXExceptions) 1509 return; 1510 1511 assert(Context.hasSameType(New->getType(), Old->getType()) && 1512 "Should only be called if types are otherwise the same."); 1513 1514 QualType NewType = New->getType(); 1515 QualType OldType = Old->getType(); 1516 1517 // We're only interested in pointers and references to functions, as well 1518 // as pointers to member functions. 1519 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1520 NewType = R->getPointeeType(); 1521 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1522 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1523 NewType = P->getPointeeType(); 1524 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1525 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1526 NewType = M->getPointeeType(); 1527 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1528 } 1529 1530 if (!NewType->isFunctionProtoType()) 1531 return; 1532 1533 // There's lots of special cases for functions. For function pointers, system 1534 // libraries are hopefully not as broken so that we don't need these 1535 // workarounds. 1536 if (CheckEquivalentExceptionSpec( 1537 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1538 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1539 New->setInvalidDecl(); 1540 } 1541 } 1542 1543 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1544 /// function declaration are well-formed according to C++ 1545 /// [dcl.fct.default]. 1546 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1547 unsigned NumParams = FD->getNumParams(); 1548 unsigned ParamIdx = 0; 1549 1550 // This checking doesn't make sense for explicit specializations; their 1551 // default arguments are determined by the declaration we're specializing, 1552 // not by FD. 1553 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1554 return; 1555 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1556 if (FTD->isMemberSpecialization()) 1557 return; 1558 1559 // Find first parameter with a default argument 1560 for (; ParamIdx < NumParams; ++ParamIdx) { 1561 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1562 if (Param->hasDefaultArg()) 1563 break; 1564 } 1565 1566 // C++20 [dcl.fct.default]p4: 1567 // In a given function declaration, each parameter subsequent to a parameter 1568 // with a default argument shall have a default argument supplied in this or 1569 // a previous declaration, unless the parameter was expanded from a 1570 // parameter pack, or shall be a function parameter pack. 1571 for (; ParamIdx < NumParams; ++ParamIdx) { 1572 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1573 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1574 !(CurrentInstantiationScope && 1575 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1576 if (Param->isInvalidDecl()) 1577 /* We already complained about this parameter. */; 1578 else if (Param->getIdentifier()) 1579 Diag(Param->getLocation(), 1580 diag::err_param_default_argument_missing_name) 1581 << Param->getIdentifier(); 1582 else 1583 Diag(Param->getLocation(), 1584 diag::err_param_default_argument_missing); 1585 } 1586 } 1587 } 1588 1589 /// Check that the given type is a literal type. Issue a diagnostic if not, 1590 /// if Kind is Diagnose. 1591 /// \return \c true if a problem has been found (and optionally diagnosed). 1592 template <typename... Ts> 1593 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1594 SourceLocation Loc, QualType T, unsigned DiagID, 1595 Ts &&...DiagArgs) { 1596 if (T->isDependentType()) 1597 return false; 1598 1599 switch (Kind) { 1600 case Sema::CheckConstexprKind::Diagnose: 1601 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1602 std::forward<Ts>(DiagArgs)...); 1603 1604 case Sema::CheckConstexprKind::CheckValid: 1605 return !T->isLiteralType(SemaRef.Context); 1606 } 1607 1608 llvm_unreachable("unknown CheckConstexprKind"); 1609 } 1610 1611 /// Determine whether a destructor cannot be constexpr due to 1612 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1613 const CXXDestructorDecl *DD, 1614 Sema::CheckConstexprKind Kind) { 1615 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1616 const CXXRecordDecl *RD = 1617 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1618 if (!RD || RD->hasConstexprDestructor()) 1619 return true; 1620 1621 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1622 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1623 << DD->getConstexprKind() << !FD 1624 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1625 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1626 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1627 } 1628 return false; 1629 }; 1630 1631 const CXXRecordDecl *RD = DD->getParent(); 1632 for (const CXXBaseSpecifier &B : RD->bases()) 1633 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1634 return false; 1635 for (const FieldDecl *FD : RD->fields()) 1636 if (!Check(FD->getLocation(), FD->getType(), FD)) 1637 return false; 1638 return true; 1639 } 1640 1641 /// Check whether a function's parameter types are all literal types. If so, 1642 /// return true. If not, produce a suitable diagnostic and return false. 1643 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1644 const FunctionDecl *FD, 1645 Sema::CheckConstexprKind Kind) { 1646 unsigned ArgIndex = 0; 1647 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1648 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1649 e = FT->param_type_end(); 1650 i != e; ++i, ++ArgIndex) { 1651 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1652 SourceLocation ParamLoc = PD->getLocation(); 1653 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1654 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1655 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1656 FD->isConsteval())) 1657 return false; 1658 } 1659 return true; 1660 } 1661 1662 /// Check whether a function's return type is a literal type. If so, return 1663 /// true. If not, produce a suitable diagnostic and return false. 1664 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1665 Sema::CheckConstexprKind Kind) { 1666 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1667 diag::err_constexpr_non_literal_return, 1668 FD->isConsteval())) 1669 return false; 1670 return true; 1671 } 1672 1673 /// Get diagnostic %select index for tag kind for 1674 /// record diagnostic message. 1675 /// WARNING: Indexes apply to particular diagnostics only! 1676 /// 1677 /// \returns diagnostic %select index. 1678 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1679 switch (Tag) { 1680 case TTK_Struct: return 0; 1681 case TTK_Interface: return 1; 1682 case TTK_Class: return 2; 1683 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1684 } 1685 } 1686 1687 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1688 Stmt *Body, 1689 Sema::CheckConstexprKind Kind); 1690 1691 // Check whether a function declaration satisfies the requirements of a 1692 // constexpr function definition or a constexpr constructor definition. If so, 1693 // return true. If not, produce appropriate diagnostics (unless asked not to by 1694 // Kind) and return false. 1695 // 1696 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1697 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1698 CheckConstexprKind Kind) { 1699 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1700 if (MD && MD->isInstance()) { 1701 // C++11 [dcl.constexpr]p4: 1702 // The definition of a constexpr constructor shall satisfy the following 1703 // constraints: 1704 // - the class shall not have any virtual base classes; 1705 // 1706 // FIXME: This only applies to constructors and destructors, not arbitrary 1707 // member functions. 1708 const CXXRecordDecl *RD = MD->getParent(); 1709 if (RD->getNumVBases()) { 1710 if (Kind == CheckConstexprKind::CheckValid) 1711 return false; 1712 1713 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1714 << isa<CXXConstructorDecl>(NewFD) 1715 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1716 for (const auto &I : RD->vbases()) 1717 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1718 << I.getSourceRange(); 1719 return false; 1720 } 1721 } 1722 1723 if (!isa<CXXConstructorDecl>(NewFD)) { 1724 // C++11 [dcl.constexpr]p3: 1725 // The definition of a constexpr function shall satisfy the following 1726 // constraints: 1727 // - it shall not be virtual; (removed in C++20) 1728 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1729 if (Method && Method->isVirtual()) { 1730 if (getLangOpts().CPlusPlus20) { 1731 if (Kind == CheckConstexprKind::Diagnose) 1732 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1733 } else { 1734 if (Kind == CheckConstexprKind::CheckValid) 1735 return false; 1736 1737 Method = Method->getCanonicalDecl(); 1738 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1739 1740 // If it's not obvious why this function is virtual, find an overridden 1741 // function which uses the 'virtual' keyword. 1742 const CXXMethodDecl *WrittenVirtual = Method; 1743 while (!WrittenVirtual->isVirtualAsWritten()) 1744 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1745 if (WrittenVirtual != Method) 1746 Diag(WrittenVirtual->getLocation(), 1747 diag::note_overridden_virtual_function); 1748 return false; 1749 } 1750 } 1751 1752 // - its return type shall be a literal type; 1753 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1754 return false; 1755 } 1756 1757 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1758 // A destructor can be constexpr only if the defaulted destructor could be; 1759 // we don't need to check the members and bases if we already know they all 1760 // have constexpr destructors. 1761 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1762 if (Kind == CheckConstexprKind::CheckValid) 1763 return false; 1764 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1765 return false; 1766 } 1767 } 1768 1769 // - each of its parameter types shall be a literal type; 1770 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1771 return false; 1772 1773 Stmt *Body = NewFD->getBody(); 1774 assert(Body && 1775 "CheckConstexprFunctionDefinition called on function with no body"); 1776 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1777 } 1778 1779 /// Check the given declaration statement is legal within a constexpr function 1780 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1781 /// 1782 /// \return true if the body is OK (maybe only as an extension), false if we 1783 /// have diagnosed a problem. 1784 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1785 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1786 Sema::CheckConstexprKind Kind) { 1787 // C++11 [dcl.constexpr]p3 and p4: 1788 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1789 // contain only 1790 for (const auto *DclIt : DS->decls()) { 1791 switch (DclIt->getKind()) { 1792 case Decl::StaticAssert: 1793 case Decl::Using: 1794 case Decl::UsingShadow: 1795 case Decl::UsingDirective: 1796 case Decl::UnresolvedUsingTypename: 1797 case Decl::UnresolvedUsingValue: 1798 // - static_assert-declarations 1799 // - using-declarations, 1800 // - using-directives, 1801 continue; 1802 1803 case Decl::Typedef: 1804 case Decl::TypeAlias: { 1805 // - typedef declarations and alias-declarations that do not define 1806 // classes or enumerations, 1807 const auto *TN = cast<TypedefNameDecl>(DclIt); 1808 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1809 // Don't allow variably-modified types in constexpr functions. 1810 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1811 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1812 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1813 << TL.getSourceRange() << TL.getType() 1814 << isa<CXXConstructorDecl>(Dcl); 1815 } 1816 return false; 1817 } 1818 continue; 1819 } 1820 1821 case Decl::Enum: 1822 case Decl::CXXRecord: 1823 // C++1y allows types to be defined, not just declared. 1824 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1825 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1826 SemaRef.Diag(DS->getBeginLoc(), 1827 SemaRef.getLangOpts().CPlusPlus14 1828 ? diag::warn_cxx11_compat_constexpr_type_definition 1829 : diag::ext_constexpr_type_definition) 1830 << isa<CXXConstructorDecl>(Dcl); 1831 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1832 return false; 1833 } 1834 } 1835 continue; 1836 1837 case Decl::EnumConstant: 1838 case Decl::IndirectField: 1839 case Decl::ParmVar: 1840 // These can only appear with other declarations which are banned in 1841 // C++11 and permitted in C++1y, so ignore them. 1842 continue; 1843 1844 case Decl::Var: 1845 case Decl::Decomposition: { 1846 // C++1y [dcl.constexpr]p3 allows anything except: 1847 // a definition of a variable of non-literal type or of static or 1848 // thread storage duration or [before C++2a] for which no 1849 // initialization is performed. 1850 const auto *VD = cast<VarDecl>(DclIt); 1851 if (VD->isThisDeclarationADefinition()) { 1852 if (VD->isStaticLocal()) { 1853 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1854 SemaRef.Diag(VD->getLocation(), 1855 diag::err_constexpr_local_var_static) 1856 << isa<CXXConstructorDecl>(Dcl) 1857 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1858 } 1859 return false; 1860 } 1861 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1862 diag::err_constexpr_local_var_non_literal_type, 1863 isa<CXXConstructorDecl>(Dcl))) 1864 return false; 1865 if (!VD->getType()->isDependentType() && 1866 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1867 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1868 SemaRef.Diag( 1869 VD->getLocation(), 1870 SemaRef.getLangOpts().CPlusPlus20 1871 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1872 : diag::ext_constexpr_local_var_no_init) 1873 << isa<CXXConstructorDecl>(Dcl); 1874 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1875 return false; 1876 } 1877 continue; 1878 } 1879 } 1880 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1881 SemaRef.Diag(VD->getLocation(), 1882 SemaRef.getLangOpts().CPlusPlus14 1883 ? diag::warn_cxx11_compat_constexpr_local_var 1884 : diag::ext_constexpr_local_var) 1885 << isa<CXXConstructorDecl>(Dcl); 1886 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1887 return false; 1888 } 1889 continue; 1890 } 1891 1892 case Decl::NamespaceAlias: 1893 case Decl::Function: 1894 // These are disallowed in C++11 and permitted in C++1y. Allow them 1895 // everywhere as an extension. 1896 if (!Cxx1yLoc.isValid()) 1897 Cxx1yLoc = DS->getBeginLoc(); 1898 continue; 1899 1900 default: 1901 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1902 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1903 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1904 } 1905 return false; 1906 } 1907 } 1908 1909 return true; 1910 } 1911 1912 /// Check that the given field is initialized within a constexpr constructor. 1913 /// 1914 /// \param Dcl The constexpr constructor being checked. 1915 /// \param Field The field being checked. This may be a member of an anonymous 1916 /// struct or union nested within the class being checked. 1917 /// \param Inits All declarations, including anonymous struct/union members and 1918 /// indirect members, for which any initialization was provided. 1919 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1920 /// multiple notes for different members to the same error. 1921 /// \param Kind Whether we're diagnosing a constructor as written or determining 1922 /// whether the formal requirements are satisfied. 1923 /// \return \c false if we're checking for validity and the constructor does 1924 /// not satisfy the requirements on a constexpr constructor. 1925 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1926 const FunctionDecl *Dcl, 1927 FieldDecl *Field, 1928 llvm::SmallSet<Decl*, 16> &Inits, 1929 bool &Diagnosed, 1930 Sema::CheckConstexprKind Kind) { 1931 // In C++20 onwards, there's nothing to check for validity. 1932 if (Kind == Sema::CheckConstexprKind::CheckValid && 1933 SemaRef.getLangOpts().CPlusPlus20) 1934 return true; 1935 1936 if (Field->isInvalidDecl()) 1937 return true; 1938 1939 if (Field->isUnnamedBitfield()) 1940 return true; 1941 1942 // Anonymous unions with no variant members and empty anonymous structs do not 1943 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1944 // indirect fields don't need initializing. 1945 if (Field->isAnonymousStructOrUnion() && 1946 (Field->getType()->isUnionType() 1947 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1948 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1949 return true; 1950 1951 if (!Inits.count(Field)) { 1952 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1953 if (!Diagnosed) { 1954 SemaRef.Diag(Dcl->getLocation(), 1955 SemaRef.getLangOpts().CPlusPlus20 1956 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1957 : diag::ext_constexpr_ctor_missing_init); 1958 Diagnosed = true; 1959 } 1960 SemaRef.Diag(Field->getLocation(), 1961 diag::note_constexpr_ctor_missing_init); 1962 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1963 return false; 1964 } 1965 } else if (Field->isAnonymousStructOrUnion()) { 1966 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1967 for (auto *I : RD->fields()) 1968 // If an anonymous union contains an anonymous struct of which any member 1969 // is initialized, all members must be initialized. 1970 if (!RD->isUnion() || Inits.count(I)) 1971 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1972 Kind)) 1973 return false; 1974 } 1975 return true; 1976 } 1977 1978 /// Check the provided statement is allowed in a constexpr function 1979 /// definition. 1980 static bool 1981 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1982 SmallVectorImpl<SourceLocation> &ReturnStmts, 1983 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1984 Sema::CheckConstexprKind Kind) { 1985 // - its function-body shall be [...] a compound-statement that contains only 1986 switch (S->getStmtClass()) { 1987 case Stmt::NullStmtClass: 1988 // - null statements, 1989 return true; 1990 1991 case Stmt::DeclStmtClass: 1992 // - static_assert-declarations 1993 // - using-declarations, 1994 // - using-directives, 1995 // - typedef declarations and alias-declarations that do not define 1996 // classes or enumerations, 1997 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1998 return false; 1999 return true; 2000 2001 case Stmt::ReturnStmtClass: 2002 // - and exactly one return statement; 2003 if (isa<CXXConstructorDecl>(Dcl)) { 2004 // C++1y allows return statements in constexpr constructors. 2005 if (!Cxx1yLoc.isValid()) 2006 Cxx1yLoc = S->getBeginLoc(); 2007 return true; 2008 } 2009 2010 ReturnStmts.push_back(S->getBeginLoc()); 2011 return true; 2012 2013 case Stmt::CompoundStmtClass: { 2014 // C++1y allows compound-statements. 2015 if (!Cxx1yLoc.isValid()) 2016 Cxx1yLoc = S->getBeginLoc(); 2017 2018 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2019 for (auto *BodyIt : CompStmt->body()) { 2020 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2021 Cxx1yLoc, Cxx2aLoc, Kind)) 2022 return false; 2023 } 2024 return true; 2025 } 2026 2027 case Stmt::AttributedStmtClass: 2028 if (!Cxx1yLoc.isValid()) 2029 Cxx1yLoc = S->getBeginLoc(); 2030 return true; 2031 2032 case Stmt::IfStmtClass: { 2033 // C++1y allows if-statements. 2034 if (!Cxx1yLoc.isValid()) 2035 Cxx1yLoc = S->getBeginLoc(); 2036 2037 IfStmt *If = cast<IfStmt>(S); 2038 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2039 Cxx1yLoc, Cxx2aLoc, Kind)) 2040 return false; 2041 if (If->getElse() && 2042 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2043 Cxx1yLoc, Cxx2aLoc, Kind)) 2044 return false; 2045 return true; 2046 } 2047 2048 case Stmt::WhileStmtClass: 2049 case Stmt::DoStmtClass: 2050 case Stmt::ForStmtClass: 2051 case Stmt::CXXForRangeStmtClass: 2052 case Stmt::ContinueStmtClass: 2053 // C++1y allows all of these. We don't allow them as extensions in C++11, 2054 // because they don't make sense without variable mutation. 2055 if (!SemaRef.getLangOpts().CPlusPlus14) 2056 break; 2057 if (!Cxx1yLoc.isValid()) 2058 Cxx1yLoc = S->getBeginLoc(); 2059 for (Stmt *SubStmt : S->children()) 2060 if (SubStmt && 2061 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2062 Cxx1yLoc, Cxx2aLoc, Kind)) 2063 return false; 2064 return true; 2065 2066 case Stmt::SwitchStmtClass: 2067 case Stmt::CaseStmtClass: 2068 case Stmt::DefaultStmtClass: 2069 case Stmt::BreakStmtClass: 2070 // C++1y allows switch-statements, and since they don't need variable 2071 // mutation, we can reasonably allow them in C++11 as an extension. 2072 if (!Cxx1yLoc.isValid()) 2073 Cxx1yLoc = S->getBeginLoc(); 2074 for (Stmt *SubStmt : S->children()) 2075 if (SubStmt && 2076 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2077 Cxx1yLoc, Cxx2aLoc, Kind)) 2078 return false; 2079 return true; 2080 2081 case Stmt::GCCAsmStmtClass: 2082 case Stmt::MSAsmStmtClass: 2083 // C++2a allows inline assembly statements. 2084 case Stmt::CXXTryStmtClass: 2085 if (Cxx2aLoc.isInvalid()) 2086 Cxx2aLoc = S->getBeginLoc(); 2087 for (Stmt *SubStmt : S->children()) { 2088 if (SubStmt && 2089 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2090 Cxx1yLoc, Cxx2aLoc, Kind)) 2091 return false; 2092 } 2093 return true; 2094 2095 case Stmt::CXXCatchStmtClass: 2096 // Do not bother checking the language mode (already covered by the 2097 // try block check). 2098 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2099 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2100 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2101 return false; 2102 return true; 2103 2104 default: 2105 if (!isa<Expr>(S)) 2106 break; 2107 2108 // C++1y allows expression-statements. 2109 if (!Cxx1yLoc.isValid()) 2110 Cxx1yLoc = S->getBeginLoc(); 2111 return true; 2112 } 2113 2114 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2115 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2116 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2117 } 2118 return false; 2119 } 2120 2121 /// Check the body for the given constexpr function declaration only contains 2122 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2123 /// 2124 /// \return true if the body is OK, false if we have found or diagnosed a 2125 /// problem. 2126 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2127 Stmt *Body, 2128 Sema::CheckConstexprKind Kind) { 2129 SmallVector<SourceLocation, 4> ReturnStmts; 2130 2131 if (isa<CXXTryStmt>(Body)) { 2132 // C++11 [dcl.constexpr]p3: 2133 // The definition of a constexpr function shall satisfy the following 2134 // constraints: [...] 2135 // - its function-body shall be = delete, = default, or a 2136 // compound-statement 2137 // 2138 // C++11 [dcl.constexpr]p4: 2139 // In the definition of a constexpr constructor, [...] 2140 // - its function-body shall not be a function-try-block; 2141 // 2142 // This restriction is lifted in C++2a, as long as inner statements also 2143 // apply the general constexpr rules. 2144 switch (Kind) { 2145 case Sema::CheckConstexprKind::CheckValid: 2146 if (!SemaRef.getLangOpts().CPlusPlus20) 2147 return false; 2148 break; 2149 2150 case Sema::CheckConstexprKind::Diagnose: 2151 SemaRef.Diag(Body->getBeginLoc(), 2152 !SemaRef.getLangOpts().CPlusPlus20 2153 ? diag::ext_constexpr_function_try_block_cxx20 2154 : diag::warn_cxx17_compat_constexpr_function_try_block) 2155 << isa<CXXConstructorDecl>(Dcl); 2156 break; 2157 } 2158 } 2159 2160 // - its function-body shall be [...] a compound-statement that contains only 2161 // [... list of cases ...] 2162 // 2163 // Note that walking the children here is enough to properly check for 2164 // CompoundStmt and CXXTryStmt body. 2165 SourceLocation Cxx1yLoc, Cxx2aLoc; 2166 for (Stmt *SubStmt : Body->children()) { 2167 if (SubStmt && 2168 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2169 Cxx1yLoc, Cxx2aLoc, Kind)) 2170 return false; 2171 } 2172 2173 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2174 // If this is only valid as an extension, report that we don't satisfy the 2175 // constraints of the current language. 2176 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2177 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2178 return false; 2179 } else if (Cxx2aLoc.isValid()) { 2180 SemaRef.Diag(Cxx2aLoc, 2181 SemaRef.getLangOpts().CPlusPlus20 2182 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2183 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2184 << isa<CXXConstructorDecl>(Dcl); 2185 } else if (Cxx1yLoc.isValid()) { 2186 SemaRef.Diag(Cxx1yLoc, 2187 SemaRef.getLangOpts().CPlusPlus14 2188 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2189 : diag::ext_constexpr_body_invalid_stmt) 2190 << isa<CXXConstructorDecl>(Dcl); 2191 } 2192 2193 if (const CXXConstructorDecl *Constructor 2194 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2195 const CXXRecordDecl *RD = Constructor->getParent(); 2196 // DR1359: 2197 // - every non-variant non-static data member and base class sub-object 2198 // shall be initialized; 2199 // DR1460: 2200 // - if the class is a union having variant members, exactly one of them 2201 // shall be initialized; 2202 if (RD->isUnion()) { 2203 if (Constructor->getNumCtorInitializers() == 0 && 2204 RD->hasVariantMembers()) { 2205 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2206 SemaRef.Diag( 2207 Dcl->getLocation(), 2208 SemaRef.getLangOpts().CPlusPlus20 2209 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2210 : diag::ext_constexpr_union_ctor_no_init); 2211 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2212 return false; 2213 } 2214 } 2215 } else if (!Constructor->isDependentContext() && 2216 !Constructor->isDelegatingConstructor()) { 2217 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2218 2219 // Skip detailed checking if we have enough initializers, and we would 2220 // allow at most one initializer per member. 2221 bool AnyAnonStructUnionMembers = false; 2222 unsigned Fields = 0; 2223 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2224 E = RD->field_end(); I != E; ++I, ++Fields) { 2225 if (I->isAnonymousStructOrUnion()) { 2226 AnyAnonStructUnionMembers = true; 2227 break; 2228 } 2229 } 2230 // DR1460: 2231 // - if the class is a union-like class, but is not a union, for each of 2232 // its anonymous union members having variant members, exactly one of 2233 // them shall be initialized; 2234 if (AnyAnonStructUnionMembers || 2235 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2236 // Check initialization of non-static data members. Base classes are 2237 // always initialized so do not need to be checked. Dependent bases 2238 // might not have initializers in the member initializer list. 2239 llvm::SmallSet<Decl*, 16> Inits; 2240 for (const auto *I: Constructor->inits()) { 2241 if (FieldDecl *FD = I->getMember()) 2242 Inits.insert(FD); 2243 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2244 Inits.insert(ID->chain_begin(), ID->chain_end()); 2245 } 2246 2247 bool Diagnosed = false; 2248 for (auto *I : RD->fields()) 2249 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2250 Kind)) 2251 return false; 2252 } 2253 } 2254 } else { 2255 if (ReturnStmts.empty()) { 2256 // C++1y doesn't require constexpr functions to contain a 'return' 2257 // statement. We still do, unless the return type might be void, because 2258 // otherwise if there's no return statement, the function cannot 2259 // be used in a core constant expression. 2260 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2261 (Dcl->getReturnType()->isVoidType() || 2262 Dcl->getReturnType()->isDependentType()); 2263 switch (Kind) { 2264 case Sema::CheckConstexprKind::Diagnose: 2265 SemaRef.Diag(Dcl->getLocation(), 2266 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2267 : diag::err_constexpr_body_no_return) 2268 << Dcl->isConsteval(); 2269 if (!OK) 2270 return false; 2271 break; 2272 2273 case Sema::CheckConstexprKind::CheckValid: 2274 // The formal requirements don't include this rule in C++14, even 2275 // though the "must be able to produce a constant expression" rules 2276 // still imply it in some cases. 2277 if (!SemaRef.getLangOpts().CPlusPlus14) 2278 return false; 2279 break; 2280 } 2281 } else if (ReturnStmts.size() > 1) { 2282 switch (Kind) { 2283 case Sema::CheckConstexprKind::Diagnose: 2284 SemaRef.Diag( 2285 ReturnStmts.back(), 2286 SemaRef.getLangOpts().CPlusPlus14 2287 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2288 : diag::ext_constexpr_body_multiple_return); 2289 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2290 SemaRef.Diag(ReturnStmts[I], 2291 diag::note_constexpr_body_previous_return); 2292 break; 2293 2294 case Sema::CheckConstexprKind::CheckValid: 2295 if (!SemaRef.getLangOpts().CPlusPlus14) 2296 return false; 2297 break; 2298 } 2299 } 2300 } 2301 2302 // C++11 [dcl.constexpr]p5: 2303 // if no function argument values exist such that the function invocation 2304 // substitution would produce a constant expression, the program is 2305 // ill-formed; no diagnostic required. 2306 // C++11 [dcl.constexpr]p3: 2307 // - every constructor call and implicit conversion used in initializing the 2308 // return value shall be one of those allowed in a constant expression. 2309 // C++11 [dcl.constexpr]p4: 2310 // - every constructor involved in initializing non-static data members and 2311 // base class sub-objects shall be a constexpr constructor. 2312 // 2313 // Note that this rule is distinct from the "requirements for a constexpr 2314 // function", so is not checked in CheckValid mode. 2315 SmallVector<PartialDiagnosticAt, 8> Diags; 2316 if (Kind == Sema::CheckConstexprKind::Diagnose && 2317 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2318 SemaRef.Diag(Dcl->getLocation(), 2319 diag::ext_constexpr_function_never_constant_expr) 2320 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2321 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2322 SemaRef.Diag(Diags[I].first, Diags[I].second); 2323 // Don't return false here: we allow this for compatibility in 2324 // system headers. 2325 } 2326 2327 return true; 2328 } 2329 2330 /// Get the class that is directly named by the current context. This is the 2331 /// class for which an unqualified-id in this scope could name a constructor 2332 /// or destructor. 2333 /// 2334 /// If the scope specifier denotes a class, this will be that class. 2335 /// If the scope specifier is empty, this will be the class whose 2336 /// member-specification we are currently within. Otherwise, there 2337 /// is no such class. 2338 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2339 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2340 2341 if (SS && SS->isInvalid()) 2342 return nullptr; 2343 2344 if (SS && SS->isNotEmpty()) { 2345 DeclContext *DC = computeDeclContext(*SS, true); 2346 return dyn_cast_or_null<CXXRecordDecl>(DC); 2347 } 2348 2349 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2350 } 2351 2352 /// isCurrentClassName - Determine whether the identifier II is the 2353 /// name of the class type currently being defined. In the case of 2354 /// nested classes, this will only return true if II is the name of 2355 /// the innermost class. 2356 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2357 const CXXScopeSpec *SS) { 2358 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2359 return CurDecl && &II == CurDecl->getIdentifier(); 2360 } 2361 2362 /// Determine whether the identifier II is a typo for the name of 2363 /// the class type currently being defined. If so, update it to the identifier 2364 /// that should have been used. 2365 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2366 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2367 2368 if (!getLangOpts().SpellChecking) 2369 return false; 2370 2371 CXXRecordDecl *CurDecl; 2372 if (SS && SS->isSet() && !SS->isInvalid()) { 2373 DeclContext *DC = computeDeclContext(*SS, true); 2374 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2375 } else 2376 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2377 2378 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2379 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2380 < II->getLength()) { 2381 II = CurDecl->getIdentifier(); 2382 return true; 2383 } 2384 2385 return false; 2386 } 2387 2388 /// Determine whether the given class is a base class of the given 2389 /// class, including looking at dependent bases. 2390 static bool findCircularInheritance(const CXXRecordDecl *Class, 2391 const CXXRecordDecl *Current) { 2392 SmallVector<const CXXRecordDecl*, 8> Queue; 2393 2394 Class = Class->getCanonicalDecl(); 2395 while (true) { 2396 for (const auto &I : Current->bases()) { 2397 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2398 if (!Base) 2399 continue; 2400 2401 Base = Base->getDefinition(); 2402 if (!Base) 2403 continue; 2404 2405 if (Base->getCanonicalDecl() == Class) 2406 return true; 2407 2408 Queue.push_back(Base); 2409 } 2410 2411 if (Queue.empty()) 2412 return false; 2413 2414 Current = Queue.pop_back_val(); 2415 } 2416 2417 return false; 2418 } 2419 2420 /// Check the validity of a C++ base class specifier. 2421 /// 2422 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2423 /// and returns NULL otherwise. 2424 CXXBaseSpecifier * 2425 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2426 SourceRange SpecifierRange, 2427 bool Virtual, AccessSpecifier Access, 2428 TypeSourceInfo *TInfo, 2429 SourceLocation EllipsisLoc) { 2430 QualType BaseType = TInfo->getType(); 2431 if (BaseType->containsErrors()) { 2432 // Already emitted a diagnostic when parsing the error type. 2433 return nullptr; 2434 } 2435 // C++ [class.union]p1: 2436 // A union shall not have base classes. 2437 if (Class->isUnion()) { 2438 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2439 << SpecifierRange; 2440 return nullptr; 2441 } 2442 2443 if (EllipsisLoc.isValid() && 2444 !TInfo->getType()->containsUnexpandedParameterPack()) { 2445 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2446 << TInfo->getTypeLoc().getSourceRange(); 2447 EllipsisLoc = SourceLocation(); 2448 } 2449 2450 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2451 2452 if (BaseType->isDependentType()) { 2453 // Make sure that we don't have circular inheritance among our dependent 2454 // bases. For non-dependent bases, the check for completeness below handles 2455 // this. 2456 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2457 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2458 ((BaseDecl = BaseDecl->getDefinition()) && 2459 findCircularInheritance(Class, BaseDecl))) { 2460 Diag(BaseLoc, diag::err_circular_inheritance) 2461 << BaseType << Context.getTypeDeclType(Class); 2462 2463 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2464 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2465 << BaseType; 2466 2467 return nullptr; 2468 } 2469 } 2470 2471 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2472 Class->getTagKind() == TTK_Class, 2473 Access, TInfo, EllipsisLoc); 2474 } 2475 2476 // Base specifiers must be record types. 2477 if (!BaseType->isRecordType()) { 2478 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2479 return nullptr; 2480 } 2481 2482 // C++ [class.union]p1: 2483 // A union shall not be used as a base class. 2484 if (BaseType->isUnionType()) { 2485 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2486 return nullptr; 2487 } 2488 2489 // For the MS ABI, propagate DLL attributes to base class templates. 2490 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2491 if (Attr *ClassAttr = getDLLAttr(Class)) { 2492 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2493 BaseType->getAsCXXRecordDecl())) { 2494 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2495 BaseLoc); 2496 } 2497 } 2498 } 2499 2500 // C++ [class.derived]p2: 2501 // The class-name in a base-specifier shall not be an incompletely 2502 // defined class. 2503 if (RequireCompleteType(BaseLoc, BaseType, 2504 diag::err_incomplete_base_class, SpecifierRange)) { 2505 Class->setInvalidDecl(); 2506 return nullptr; 2507 } 2508 2509 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2510 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2511 assert(BaseDecl && "Record type has no declaration"); 2512 BaseDecl = BaseDecl->getDefinition(); 2513 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2514 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2515 assert(CXXBaseDecl && "Base type is not a C++ type"); 2516 2517 // Microsoft docs say: 2518 // "If a base-class has a code_seg attribute, derived classes must have the 2519 // same attribute." 2520 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2521 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2522 if ((DerivedCSA || BaseCSA) && 2523 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2524 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2525 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2526 << CXXBaseDecl; 2527 return nullptr; 2528 } 2529 2530 // A class which contains a flexible array member is not suitable for use as a 2531 // base class: 2532 // - If the layout determines that a base comes before another base, 2533 // the flexible array member would index into the subsequent base. 2534 // - If the layout determines that base comes before the derived class, 2535 // the flexible array member would index into the derived class. 2536 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2537 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2538 << CXXBaseDecl->getDeclName(); 2539 return nullptr; 2540 } 2541 2542 // C++ [class]p3: 2543 // If a class is marked final and it appears as a base-type-specifier in 2544 // base-clause, the program is ill-formed. 2545 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2546 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2547 << CXXBaseDecl->getDeclName() 2548 << FA->isSpelledAsSealed(); 2549 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2550 << CXXBaseDecl->getDeclName() << FA->getRange(); 2551 return nullptr; 2552 } 2553 2554 if (BaseDecl->isInvalidDecl()) 2555 Class->setInvalidDecl(); 2556 2557 // Create the base specifier. 2558 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2559 Class->getTagKind() == TTK_Class, 2560 Access, TInfo, EllipsisLoc); 2561 } 2562 2563 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2564 /// one entry in the base class list of a class specifier, for 2565 /// example: 2566 /// class foo : public bar, virtual private baz { 2567 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2568 BaseResult 2569 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2570 ParsedAttributes &Attributes, 2571 bool Virtual, AccessSpecifier Access, 2572 ParsedType basetype, SourceLocation BaseLoc, 2573 SourceLocation EllipsisLoc) { 2574 if (!classdecl) 2575 return true; 2576 2577 AdjustDeclIfTemplate(classdecl); 2578 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2579 if (!Class) 2580 return true; 2581 2582 // We haven't yet attached the base specifiers. 2583 Class->setIsParsingBaseSpecifiers(); 2584 2585 // We do not support any C++11 attributes on base-specifiers yet. 2586 // Diagnose any attributes we see. 2587 for (const ParsedAttr &AL : Attributes) { 2588 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2589 continue; 2590 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2591 ? (unsigned)diag::warn_unknown_attribute_ignored 2592 : (unsigned)diag::err_base_specifier_attribute) 2593 << AL; 2594 } 2595 2596 TypeSourceInfo *TInfo = nullptr; 2597 GetTypeFromParser(basetype, &TInfo); 2598 2599 if (EllipsisLoc.isInvalid() && 2600 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2601 UPPC_BaseType)) 2602 return true; 2603 2604 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2605 Virtual, Access, TInfo, 2606 EllipsisLoc)) 2607 return BaseSpec; 2608 else 2609 Class->setInvalidDecl(); 2610 2611 return true; 2612 } 2613 2614 /// Use small set to collect indirect bases. As this is only used 2615 /// locally, there's no need to abstract the small size parameter. 2616 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2617 2618 /// Recursively add the bases of Type. Don't add Type itself. 2619 static void 2620 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2621 const QualType &Type) 2622 { 2623 // Even though the incoming type is a base, it might not be 2624 // a class -- it could be a template parm, for instance. 2625 if (auto Rec = Type->getAs<RecordType>()) { 2626 auto Decl = Rec->getAsCXXRecordDecl(); 2627 2628 // Iterate over its bases. 2629 for (const auto &BaseSpec : Decl->bases()) { 2630 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2631 .getUnqualifiedType(); 2632 if (Set.insert(Base).second) 2633 // If we've not already seen it, recurse. 2634 NoteIndirectBases(Context, Set, Base); 2635 } 2636 } 2637 } 2638 2639 /// Performs the actual work of attaching the given base class 2640 /// specifiers to a C++ class. 2641 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2642 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2643 if (Bases.empty()) 2644 return false; 2645 2646 // Used to keep track of which base types we have already seen, so 2647 // that we can properly diagnose redundant direct base types. Note 2648 // that the key is always the unqualified canonical type of the base 2649 // class. 2650 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2651 2652 // Used to track indirect bases so we can see if a direct base is 2653 // ambiguous. 2654 IndirectBaseSet IndirectBaseTypes; 2655 2656 // Copy non-redundant base specifiers into permanent storage. 2657 unsigned NumGoodBases = 0; 2658 bool Invalid = false; 2659 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2660 QualType NewBaseType 2661 = Context.getCanonicalType(Bases[idx]->getType()); 2662 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2663 2664 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2665 if (KnownBase) { 2666 // C++ [class.mi]p3: 2667 // A class shall not be specified as a direct base class of a 2668 // derived class more than once. 2669 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2670 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2671 2672 // Delete the duplicate base class specifier; we're going to 2673 // overwrite its pointer later. 2674 Context.Deallocate(Bases[idx]); 2675 2676 Invalid = true; 2677 } else { 2678 // Okay, add this new base class. 2679 KnownBase = Bases[idx]; 2680 Bases[NumGoodBases++] = Bases[idx]; 2681 2682 // Note this base's direct & indirect bases, if there could be ambiguity. 2683 if (Bases.size() > 1) 2684 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2685 2686 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2687 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2688 if (Class->isInterface() && 2689 (!RD->isInterfaceLike() || 2690 KnownBase->getAccessSpecifier() != AS_public)) { 2691 // The Microsoft extension __interface does not permit bases that 2692 // are not themselves public interfaces. 2693 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2694 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2695 << RD->getSourceRange(); 2696 Invalid = true; 2697 } 2698 if (RD->hasAttr<WeakAttr>()) 2699 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2700 } 2701 } 2702 } 2703 2704 // Attach the remaining base class specifiers to the derived class. 2705 Class->setBases(Bases.data(), NumGoodBases); 2706 2707 // Check that the only base classes that are duplicate are virtual. 2708 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2709 // Check whether this direct base is inaccessible due to ambiguity. 2710 QualType BaseType = Bases[idx]->getType(); 2711 2712 // Skip all dependent types in templates being used as base specifiers. 2713 // Checks below assume that the base specifier is a CXXRecord. 2714 if (BaseType->isDependentType()) 2715 continue; 2716 2717 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2718 .getUnqualifiedType(); 2719 2720 if (IndirectBaseTypes.count(CanonicalBase)) { 2721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2722 /*DetectVirtual=*/true); 2723 bool found 2724 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2725 assert(found); 2726 (void)found; 2727 2728 if (Paths.isAmbiguous(CanonicalBase)) 2729 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2730 << BaseType << getAmbiguousPathsDisplayString(Paths) 2731 << Bases[idx]->getSourceRange(); 2732 else 2733 assert(Bases[idx]->isVirtual()); 2734 } 2735 2736 // Delete the base class specifier, since its data has been copied 2737 // into the CXXRecordDecl. 2738 Context.Deallocate(Bases[idx]); 2739 } 2740 2741 return Invalid; 2742 } 2743 2744 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2745 /// class, after checking whether there are any duplicate base 2746 /// classes. 2747 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2748 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2749 if (!ClassDecl || Bases.empty()) 2750 return; 2751 2752 AdjustDeclIfTemplate(ClassDecl); 2753 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2754 } 2755 2756 /// Determine whether the type \p Derived is a C++ class that is 2757 /// derived from the type \p Base. 2758 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2759 if (!getLangOpts().CPlusPlus) 2760 return false; 2761 2762 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2763 if (!DerivedRD) 2764 return false; 2765 2766 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2767 if (!BaseRD) 2768 return false; 2769 2770 // If either the base or the derived type is invalid, don't try to 2771 // check whether one is derived from the other. 2772 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2773 return false; 2774 2775 // FIXME: In a modules build, do we need the entire path to be visible for us 2776 // to be able to use the inheritance relationship? 2777 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2778 return false; 2779 2780 return DerivedRD->isDerivedFrom(BaseRD); 2781 } 2782 2783 /// Determine whether the type \p Derived is a C++ class that is 2784 /// derived from the type \p Base. 2785 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2786 CXXBasePaths &Paths) { 2787 if (!getLangOpts().CPlusPlus) 2788 return false; 2789 2790 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2791 if (!DerivedRD) 2792 return false; 2793 2794 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2795 if (!BaseRD) 2796 return false; 2797 2798 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2799 return false; 2800 2801 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2802 } 2803 2804 static void BuildBasePathArray(const CXXBasePath &Path, 2805 CXXCastPath &BasePathArray) { 2806 // We first go backward and check if we have a virtual base. 2807 // FIXME: It would be better if CXXBasePath had the base specifier for 2808 // the nearest virtual base. 2809 unsigned Start = 0; 2810 for (unsigned I = Path.size(); I != 0; --I) { 2811 if (Path[I - 1].Base->isVirtual()) { 2812 Start = I - 1; 2813 break; 2814 } 2815 } 2816 2817 // Now add all bases. 2818 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2819 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2820 } 2821 2822 2823 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2824 CXXCastPath &BasePathArray) { 2825 assert(BasePathArray.empty() && "Base path array must be empty!"); 2826 assert(Paths.isRecordingPaths() && "Must record paths!"); 2827 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2828 } 2829 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2830 /// conversion (where Derived and Base are class types) is 2831 /// well-formed, meaning that the conversion is unambiguous (and 2832 /// that all of the base classes are accessible). Returns true 2833 /// and emits a diagnostic if the code is ill-formed, returns false 2834 /// otherwise. Loc is the location where this routine should point to 2835 /// if there is an error, and Range is the source range to highlight 2836 /// if there is an error. 2837 /// 2838 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2839 /// diagnostic for the respective type of error will be suppressed, but the 2840 /// check for ill-formed code will still be performed. 2841 bool 2842 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2843 unsigned InaccessibleBaseID, 2844 unsigned AmbiguousBaseConvID, 2845 SourceLocation Loc, SourceRange Range, 2846 DeclarationName Name, 2847 CXXCastPath *BasePath, 2848 bool IgnoreAccess) { 2849 // First, determine whether the path from Derived to Base is 2850 // ambiguous. This is slightly more expensive than checking whether 2851 // the Derived to Base conversion exists, because here we need to 2852 // explore multiple paths to determine if there is an ambiguity. 2853 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2854 /*DetectVirtual=*/false); 2855 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2856 if (!DerivationOkay) 2857 return true; 2858 2859 const CXXBasePath *Path = nullptr; 2860 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2861 Path = &Paths.front(); 2862 2863 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2864 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2865 // user to access such bases. 2866 if (!Path && getLangOpts().MSVCCompat) { 2867 for (const CXXBasePath &PossiblePath : Paths) { 2868 if (PossiblePath.size() == 1) { 2869 Path = &PossiblePath; 2870 if (AmbiguousBaseConvID) 2871 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2872 << Base << Derived << Range; 2873 break; 2874 } 2875 } 2876 } 2877 2878 if (Path) { 2879 if (!IgnoreAccess) { 2880 // Check that the base class can be accessed. 2881 switch ( 2882 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2883 case AR_inaccessible: 2884 return true; 2885 case AR_accessible: 2886 case AR_dependent: 2887 case AR_delayed: 2888 break; 2889 } 2890 } 2891 2892 // Build a base path if necessary. 2893 if (BasePath) 2894 ::BuildBasePathArray(*Path, *BasePath); 2895 return false; 2896 } 2897 2898 if (AmbiguousBaseConvID) { 2899 // We know that the derived-to-base conversion is ambiguous, and 2900 // we're going to produce a diagnostic. Perform the derived-to-base 2901 // search just one more time to compute all of the possible paths so 2902 // that we can print them out. This is more expensive than any of 2903 // the previous derived-to-base checks we've done, but at this point 2904 // performance isn't as much of an issue. 2905 Paths.clear(); 2906 Paths.setRecordingPaths(true); 2907 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2908 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2909 (void)StillOkay; 2910 2911 // Build up a textual representation of the ambiguous paths, e.g., 2912 // D -> B -> A, that will be used to illustrate the ambiguous 2913 // conversions in the diagnostic. We only print one of the paths 2914 // to each base class subobject. 2915 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2916 2917 Diag(Loc, AmbiguousBaseConvID) 2918 << Derived << Base << PathDisplayStr << Range << Name; 2919 } 2920 return true; 2921 } 2922 2923 bool 2924 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2925 SourceLocation Loc, SourceRange Range, 2926 CXXCastPath *BasePath, 2927 bool IgnoreAccess) { 2928 return CheckDerivedToBaseConversion( 2929 Derived, Base, diag::err_upcast_to_inaccessible_base, 2930 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2931 BasePath, IgnoreAccess); 2932 } 2933 2934 2935 /// Builds a string representing ambiguous paths from a 2936 /// specific derived class to different subobjects of the same base 2937 /// class. 2938 /// 2939 /// This function builds a string that can be used in error messages 2940 /// to show the different paths that one can take through the 2941 /// inheritance hierarchy to go from the derived class to different 2942 /// subobjects of a base class. The result looks something like this: 2943 /// @code 2944 /// struct D -> struct B -> struct A 2945 /// struct D -> struct C -> struct A 2946 /// @endcode 2947 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2948 std::string PathDisplayStr; 2949 std::set<unsigned> DisplayedPaths; 2950 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2951 Path != Paths.end(); ++Path) { 2952 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2953 // We haven't displayed a path to this particular base 2954 // class subobject yet. 2955 PathDisplayStr += "\n "; 2956 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2957 for (CXXBasePath::const_iterator Element = Path->begin(); 2958 Element != Path->end(); ++Element) 2959 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2960 } 2961 } 2962 2963 return PathDisplayStr; 2964 } 2965 2966 //===----------------------------------------------------------------------===// 2967 // C++ class member Handling 2968 //===----------------------------------------------------------------------===// 2969 2970 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2971 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2972 SourceLocation ColonLoc, 2973 const ParsedAttributesView &Attrs) { 2974 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2975 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2976 ASLoc, ColonLoc); 2977 CurContext->addHiddenDecl(ASDecl); 2978 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2979 } 2980 2981 /// CheckOverrideControl - Check C++11 override control semantics. 2982 void Sema::CheckOverrideControl(NamedDecl *D) { 2983 if (D->isInvalidDecl()) 2984 return; 2985 2986 // We only care about "override" and "final" declarations. 2987 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2988 return; 2989 2990 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2991 2992 // We can't check dependent instance methods. 2993 if (MD && MD->isInstance() && 2994 (MD->getParent()->hasAnyDependentBases() || 2995 MD->getType()->isDependentType())) 2996 return; 2997 2998 if (MD && !MD->isVirtual()) { 2999 // If we have a non-virtual method, check if if hides a virtual method. 3000 // (In that case, it's most likely the method has the wrong type.) 3001 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3002 FindHiddenVirtualMethods(MD, OverloadedMethods); 3003 3004 if (!OverloadedMethods.empty()) { 3005 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3006 Diag(OA->getLocation(), 3007 diag::override_keyword_hides_virtual_member_function) 3008 << "override" << (OverloadedMethods.size() > 1); 3009 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3010 Diag(FA->getLocation(), 3011 diag::override_keyword_hides_virtual_member_function) 3012 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3013 << (OverloadedMethods.size() > 1); 3014 } 3015 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3016 MD->setInvalidDecl(); 3017 return; 3018 } 3019 // Fall through into the general case diagnostic. 3020 // FIXME: We might want to attempt typo correction here. 3021 } 3022 3023 if (!MD || !MD->isVirtual()) { 3024 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3025 Diag(OA->getLocation(), 3026 diag::override_keyword_only_allowed_on_virtual_member_functions) 3027 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3028 D->dropAttr<OverrideAttr>(); 3029 } 3030 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3031 Diag(FA->getLocation(), 3032 diag::override_keyword_only_allowed_on_virtual_member_functions) 3033 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3034 << FixItHint::CreateRemoval(FA->getLocation()); 3035 D->dropAttr<FinalAttr>(); 3036 } 3037 return; 3038 } 3039 3040 // C++11 [class.virtual]p5: 3041 // If a function is marked with the virt-specifier override and 3042 // does not override a member function of a base class, the program is 3043 // ill-formed. 3044 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3045 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3046 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3047 << MD->getDeclName(); 3048 } 3049 3050 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3051 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3052 return; 3053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3054 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3055 return; 3056 3057 SourceLocation Loc = MD->getLocation(); 3058 SourceLocation SpellingLoc = Loc; 3059 if (getSourceManager().isMacroArgExpansion(Loc)) 3060 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3061 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3062 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3063 return; 3064 3065 if (MD->size_overridden_methods() > 0) { 3066 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3067 unsigned DiagID = 3068 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3069 ? DiagInconsistent 3070 : DiagSuggest; 3071 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3072 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3073 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3074 }; 3075 if (isa<CXXDestructorDecl>(MD)) 3076 EmitDiag( 3077 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3078 diag::warn_suggest_destructor_marked_not_override_overriding); 3079 else 3080 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3081 diag::warn_suggest_function_marked_not_override_overriding); 3082 } 3083 } 3084 3085 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3086 /// function overrides a virtual member function marked 'final', according to 3087 /// C++11 [class.virtual]p4. 3088 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3089 const CXXMethodDecl *Old) { 3090 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3091 if (!FA) 3092 return false; 3093 3094 Diag(New->getLocation(), diag::err_final_function_overridden) 3095 << New->getDeclName() 3096 << FA->isSpelledAsSealed(); 3097 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3098 return true; 3099 } 3100 3101 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3102 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3103 // FIXME: Destruction of ObjC lifetime types has side-effects. 3104 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3105 return !RD->isCompleteDefinition() || 3106 !RD->hasTrivialDefaultConstructor() || 3107 !RD->hasTrivialDestructor(); 3108 return false; 3109 } 3110 3111 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3112 ParsedAttributesView::const_iterator Itr = 3113 llvm::find_if(list, [](const ParsedAttr &AL) { 3114 return AL.isDeclspecPropertyAttribute(); 3115 }); 3116 if (Itr != list.end()) 3117 return &*Itr; 3118 return nullptr; 3119 } 3120 3121 // Check if there is a field shadowing. 3122 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3123 DeclarationName FieldName, 3124 const CXXRecordDecl *RD, 3125 bool DeclIsField) { 3126 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3127 return; 3128 3129 // To record a shadowed field in a base 3130 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3131 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3132 CXXBasePath &Path) { 3133 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3134 // Record an ambiguous path directly 3135 if (Bases.find(Base) != Bases.end()) 3136 return true; 3137 for (const auto Field : Base->lookup(FieldName)) { 3138 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3139 Field->getAccess() != AS_private) { 3140 assert(Field->getAccess() != AS_none); 3141 assert(Bases.find(Base) == Bases.end()); 3142 Bases[Base] = Field; 3143 return true; 3144 } 3145 } 3146 return false; 3147 }; 3148 3149 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3150 /*DetectVirtual=*/true); 3151 if (!RD->lookupInBases(FieldShadowed, Paths)) 3152 return; 3153 3154 for (const auto &P : Paths) { 3155 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3156 auto It = Bases.find(Base); 3157 // Skip duplicated bases 3158 if (It == Bases.end()) 3159 continue; 3160 auto BaseField = It->second; 3161 assert(BaseField->getAccess() != AS_private); 3162 if (AS_none != 3163 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3164 Diag(Loc, diag::warn_shadow_field) 3165 << FieldName << RD << Base << DeclIsField; 3166 Diag(BaseField->getLocation(), diag::note_shadow_field); 3167 Bases.erase(It); 3168 } 3169 } 3170 } 3171 3172 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3173 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3174 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3175 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3176 /// present (but parsing it has been deferred). 3177 NamedDecl * 3178 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3179 MultiTemplateParamsArg TemplateParameterLists, 3180 Expr *BW, const VirtSpecifiers &VS, 3181 InClassInitStyle InitStyle) { 3182 const DeclSpec &DS = D.getDeclSpec(); 3183 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3184 DeclarationName Name = NameInfo.getName(); 3185 SourceLocation Loc = NameInfo.getLoc(); 3186 3187 // For anonymous bitfields, the location should point to the type. 3188 if (Loc.isInvalid()) 3189 Loc = D.getBeginLoc(); 3190 3191 Expr *BitWidth = static_cast<Expr*>(BW); 3192 3193 assert(isa<CXXRecordDecl>(CurContext)); 3194 assert(!DS.isFriendSpecified()); 3195 3196 bool isFunc = D.isDeclarationOfFunction(); 3197 const ParsedAttr *MSPropertyAttr = 3198 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3199 3200 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3201 // The Microsoft extension __interface only permits public member functions 3202 // and prohibits constructors, destructors, operators, non-public member 3203 // functions, static methods and data members. 3204 unsigned InvalidDecl; 3205 bool ShowDeclName = true; 3206 if (!isFunc && 3207 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3208 InvalidDecl = 0; 3209 else if (!isFunc) 3210 InvalidDecl = 1; 3211 else if (AS != AS_public) 3212 InvalidDecl = 2; 3213 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3214 InvalidDecl = 3; 3215 else switch (Name.getNameKind()) { 3216 case DeclarationName::CXXConstructorName: 3217 InvalidDecl = 4; 3218 ShowDeclName = false; 3219 break; 3220 3221 case DeclarationName::CXXDestructorName: 3222 InvalidDecl = 5; 3223 ShowDeclName = false; 3224 break; 3225 3226 case DeclarationName::CXXOperatorName: 3227 case DeclarationName::CXXConversionFunctionName: 3228 InvalidDecl = 6; 3229 break; 3230 3231 default: 3232 InvalidDecl = 0; 3233 break; 3234 } 3235 3236 if (InvalidDecl) { 3237 if (ShowDeclName) 3238 Diag(Loc, diag::err_invalid_member_in_interface) 3239 << (InvalidDecl-1) << Name; 3240 else 3241 Diag(Loc, diag::err_invalid_member_in_interface) 3242 << (InvalidDecl-1) << ""; 3243 return nullptr; 3244 } 3245 } 3246 3247 // C++ 9.2p6: A member shall not be declared to have automatic storage 3248 // duration (auto, register) or with the extern storage-class-specifier. 3249 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3250 // data members and cannot be applied to names declared const or static, 3251 // and cannot be applied to reference members. 3252 switch (DS.getStorageClassSpec()) { 3253 case DeclSpec::SCS_unspecified: 3254 case DeclSpec::SCS_typedef: 3255 case DeclSpec::SCS_static: 3256 break; 3257 case DeclSpec::SCS_mutable: 3258 if (isFunc) { 3259 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3260 3261 // FIXME: It would be nicer if the keyword was ignored only for this 3262 // declarator. Otherwise we could get follow-up errors. 3263 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3264 } 3265 break; 3266 default: 3267 Diag(DS.getStorageClassSpecLoc(), 3268 diag::err_storageclass_invalid_for_member); 3269 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3270 break; 3271 } 3272 3273 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3274 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3275 !isFunc); 3276 3277 if (DS.hasConstexprSpecifier() && isInstField) { 3278 SemaDiagnosticBuilder B = 3279 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3280 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3281 if (InitStyle == ICIS_NoInit) { 3282 B << 0 << 0; 3283 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3284 B << FixItHint::CreateRemoval(ConstexprLoc); 3285 else { 3286 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3287 D.getMutableDeclSpec().ClearConstexprSpec(); 3288 const char *PrevSpec; 3289 unsigned DiagID; 3290 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3291 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3292 (void)Failed; 3293 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3294 } 3295 } else { 3296 B << 1; 3297 const char *PrevSpec; 3298 unsigned DiagID; 3299 if (D.getMutableDeclSpec().SetStorageClassSpec( 3300 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3301 Context.getPrintingPolicy())) { 3302 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3303 "This is the only DeclSpec that should fail to be applied"); 3304 B << 1; 3305 } else { 3306 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3307 isInstField = false; 3308 } 3309 } 3310 } 3311 3312 NamedDecl *Member; 3313 if (isInstField) { 3314 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3315 3316 // Data members must have identifiers for names. 3317 if (!Name.isIdentifier()) { 3318 Diag(Loc, diag::err_bad_variable_name) 3319 << Name; 3320 return nullptr; 3321 } 3322 3323 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3324 3325 // Member field could not be with "template" keyword. 3326 // So TemplateParameterLists should be empty in this case. 3327 if (TemplateParameterLists.size()) { 3328 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3329 if (TemplateParams->size()) { 3330 // There is no such thing as a member field template. 3331 Diag(D.getIdentifierLoc(), diag::err_template_member) 3332 << II 3333 << SourceRange(TemplateParams->getTemplateLoc(), 3334 TemplateParams->getRAngleLoc()); 3335 } else { 3336 // There is an extraneous 'template<>' for this member. 3337 Diag(TemplateParams->getTemplateLoc(), 3338 diag::err_template_member_noparams) 3339 << II 3340 << SourceRange(TemplateParams->getTemplateLoc(), 3341 TemplateParams->getRAngleLoc()); 3342 } 3343 return nullptr; 3344 } 3345 3346 if (SS.isSet() && !SS.isInvalid()) { 3347 // The user provided a superfluous scope specifier inside a class 3348 // definition: 3349 // 3350 // class X { 3351 // int X::member; 3352 // }; 3353 if (DeclContext *DC = computeDeclContext(SS, false)) 3354 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3355 D.getName().getKind() == 3356 UnqualifiedIdKind::IK_TemplateId); 3357 else 3358 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3359 << Name << SS.getRange(); 3360 3361 SS.clear(); 3362 } 3363 3364 if (MSPropertyAttr) { 3365 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3366 BitWidth, InitStyle, AS, *MSPropertyAttr); 3367 if (!Member) 3368 return nullptr; 3369 isInstField = false; 3370 } else { 3371 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3372 BitWidth, InitStyle, AS); 3373 if (!Member) 3374 return nullptr; 3375 } 3376 3377 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3378 } else { 3379 Member = HandleDeclarator(S, D, TemplateParameterLists); 3380 if (!Member) 3381 return nullptr; 3382 3383 // Non-instance-fields can't have a bitfield. 3384 if (BitWidth) { 3385 if (Member->isInvalidDecl()) { 3386 // don't emit another diagnostic. 3387 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3388 // C++ 9.6p3: A bit-field shall not be a static member. 3389 // "static member 'A' cannot be a bit-field" 3390 Diag(Loc, diag::err_static_not_bitfield) 3391 << Name << BitWidth->getSourceRange(); 3392 } else if (isa<TypedefDecl>(Member)) { 3393 // "typedef member 'x' cannot be a bit-field" 3394 Diag(Loc, diag::err_typedef_not_bitfield) 3395 << Name << BitWidth->getSourceRange(); 3396 } else { 3397 // A function typedef ("typedef int f(); f a;"). 3398 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3399 Diag(Loc, diag::err_not_integral_type_bitfield) 3400 << Name << cast<ValueDecl>(Member)->getType() 3401 << BitWidth->getSourceRange(); 3402 } 3403 3404 BitWidth = nullptr; 3405 Member->setInvalidDecl(); 3406 } 3407 3408 NamedDecl *NonTemplateMember = Member; 3409 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3410 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3411 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3412 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3413 3414 Member->setAccess(AS); 3415 3416 // If we have declared a member function template or static data member 3417 // template, set the access of the templated declaration as well. 3418 if (NonTemplateMember != Member) 3419 NonTemplateMember->setAccess(AS); 3420 3421 // C++ [temp.deduct.guide]p3: 3422 // A deduction guide [...] for a member class template [shall be 3423 // declared] with the same access [as the template]. 3424 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3425 auto *TD = DG->getDeducedTemplate(); 3426 // Access specifiers are only meaningful if both the template and the 3427 // deduction guide are from the same scope. 3428 if (AS != TD->getAccess() && 3429 TD->getDeclContext()->getRedeclContext()->Equals( 3430 DG->getDeclContext()->getRedeclContext())) { 3431 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3432 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3433 << TD->getAccess(); 3434 const AccessSpecDecl *LastAccessSpec = nullptr; 3435 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3436 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3437 LastAccessSpec = AccessSpec; 3438 } 3439 assert(LastAccessSpec && "differing access with no access specifier"); 3440 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3441 << AS; 3442 } 3443 } 3444 } 3445 3446 if (VS.isOverrideSpecified()) 3447 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3448 AttributeCommonInfo::AS_Keyword)); 3449 if (VS.isFinalSpecified()) 3450 Member->addAttr(FinalAttr::Create( 3451 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3452 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3453 3454 if (VS.getLastLocation().isValid()) { 3455 // Update the end location of a method that has a virt-specifiers. 3456 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3457 MD->setRangeEnd(VS.getLastLocation()); 3458 } 3459 3460 CheckOverrideControl(Member); 3461 3462 assert((Name || isInstField) && "No identifier for non-field ?"); 3463 3464 if (isInstField) { 3465 FieldDecl *FD = cast<FieldDecl>(Member); 3466 FieldCollector->Add(FD); 3467 3468 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3469 // Remember all explicit private FieldDecls that have a name, no side 3470 // effects and are not part of a dependent type declaration. 3471 if (!FD->isImplicit() && FD->getDeclName() && 3472 FD->getAccess() == AS_private && 3473 !FD->hasAttr<UnusedAttr>() && 3474 !FD->getParent()->isDependentContext() && 3475 !InitializationHasSideEffects(*FD)) 3476 UnusedPrivateFields.insert(FD); 3477 } 3478 } 3479 3480 return Member; 3481 } 3482 3483 namespace { 3484 class UninitializedFieldVisitor 3485 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3486 Sema &S; 3487 // List of Decls to generate a warning on. Also remove Decls that become 3488 // initialized. 3489 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3490 // List of base classes of the record. Classes are removed after their 3491 // initializers. 3492 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3493 // Vector of decls to be removed from the Decl set prior to visiting the 3494 // nodes. These Decls may have been initialized in the prior initializer. 3495 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3496 // If non-null, add a note to the warning pointing back to the constructor. 3497 const CXXConstructorDecl *Constructor; 3498 // Variables to hold state when processing an initializer list. When 3499 // InitList is true, special case initialization of FieldDecls matching 3500 // InitListFieldDecl. 3501 bool InitList; 3502 FieldDecl *InitListFieldDecl; 3503 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3504 3505 public: 3506 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3507 UninitializedFieldVisitor(Sema &S, 3508 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3509 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3510 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3511 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3512 3513 // Returns true if the use of ME is not an uninitialized use. 3514 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3515 bool CheckReferenceOnly) { 3516 llvm::SmallVector<FieldDecl*, 4> Fields; 3517 bool ReferenceField = false; 3518 while (ME) { 3519 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3520 if (!FD) 3521 return false; 3522 Fields.push_back(FD); 3523 if (FD->getType()->isReferenceType()) 3524 ReferenceField = true; 3525 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3526 } 3527 3528 // Binding a reference to an uninitialized field is not an 3529 // uninitialized use. 3530 if (CheckReferenceOnly && !ReferenceField) 3531 return true; 3532 3533 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3534 // Discard the first field since it is the field decl that is being 3535 // initialized. 3536 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3537 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3538 } 3539 3540 for (auto UsedIter = UsedFieldIndex.begin(), 3541 UsedEnd = UsedFieldIndex.end(), 3542 OrigIter = InitFieldIndex.begin(), 3543 OrigEnd = InitFieldIndex.end(); 3544 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3545 if (*UsedIter < *OrigIter) 3546 return true; 3547 if (*UsedIter > *OrigIter) 3548 break; 3549 } 3550 3551 return false; 3552 } 3553 3554 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3555 bool AddressOf) { 3556 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3557 return; 3558 3559 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3560 // or union. 3561 MemberExpr *FieldME = ME; 3562 3563 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3564 3565 Expr *Base = ME; 3566 while (MemberExpr *SubME = 3567 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3568 3569 if (isa<VarDecl>(SubME->getMemberDecl())) 3570 return; 3571 3572 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3573 if (!FD->isAnonymousStructOrUnion()) 3574 FieldME = SubME; 3575 3576 if (!FieldME->getType().isPODType(S.Context)) 3577 AllPODFields = false; 3578 3579 Base = SubME->getBase(); 3580 } 3581 3582 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3583 Visit(Base); 3584 return; 3585 } 3586 3587 if (AddressOf && AllPODFields) 3588 return; 3589 3590 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3591 3592 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3593 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3594 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3595 } 3596 3597 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3598 QualType T = BaseCast->getType(); 3599 if (T->isPointerType() && 3600 BaseClasses.count(T->getPointeeType())) { 3601 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3602 << T->getPointeeType() << FoundVD; 3603 } 3604 } 3605 } 3606 3607 if (!Decls.count(FoundVD)) 3608 return; 3609 3610 const bool IsReference = FoundVD->getType()->isReferenceType(); 3611 3612 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3613 // Special checking for initializer lists. 3614 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3615 return; 3616 } 3617 } else { 3618 // Prevent double warnings on use of unbounded references. 3619 if (CheckReferenceOnly && !IsReference) 3620 return; 3621 } 3622 3623 unsigned diag = IsReference 3624 ? diag::warn_reference_field_is_uninit 3625 : diag::warn_field_is_uninit; 3626 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3627 if (Constructor) 3628 S.Diag(Constructor->getLocation(), 3629 diag::note_uninit_in_this_constructor) 3630 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3631 3632 } 3633 3634 void HandleValue(Expr *E, bool AddressOf) { 3635 E = E->IgnoreParens(); 3636 3637 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3638 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3639 AddressOf /*AddressOf*/); 3640 return; 3641 } 3642 3643 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3644 Visit(CO->getCond()); 3645 HandleValue(CO->getTrueExpr(), AddressOf); 3646 HandleValue(CO->getFalseExpr(), AddressOf); 3647 return; 3648 } 3649 3650 if (BinaryConditionalOperator *BCO = 3651 dyn_cast<BinaryConditionalOperator>(E)) { 3652 Visit(BCO->getCond()); 3653 HandleValue(BCO->getFalseExpr(), AddressOf); 3654 return; 3655 } 3656 3657 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3658 HandleValue(OVE->getSourceExpr(), AddressOf); 3659 return; 3660 } 3661 3662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3663 switch (BO->getOpcode()) { 3664 default: 3665 break; 3666 case(BO_PtrMemD): 3667 case(BO_PtrMemI): 3668 HandleValue(BO->getLHS(), AddressOf); 3669 Visit(BO->getRHS()); 3670 return; 3671 case(BO_Comma): 3672 Visit(BO->getLHS()); 3673 HandleValue(BO->getRHS(), AddressOf); 3674 return; 3675 } 3676 } 3677 3678 Visit(E); 3679 } 3680 3681 void CheckInitListExpr(InitListExpr *ILE) { 3682 InitFieldIndex.push_back(0); 3683 for (auto Child : ILE->children()) { 3684 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3685 CheckInitListExpr(SubList); 3686 } else { 3687 Visit(Child); 3688 } 3689 ++InitFieldIndex.back(); 3690 } 3691 InitFieldIndex.pop_back(); 3692 } 3693 3694 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3695 FieldDecl *Field, const Type *BaseClass) { 3696 // Remove Decls that may have been initialized in the previous 3697 // initializer. 3698 for (ValueDecl* VD : DeclsToRemove) 3699 Decls.erase(VD); 3700 DeclsToRemove.clear(); 3701 3702 Constructor = FieldConstructor; 3703 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3704 3705 if (ILE && Field) { 3706 InitList = true; 3707 InitListFieldDecl = Field; 3708 InitFieldIndex.clear(); 3709 CheckInitListExpr(ILE); 3710 } else { 3711 InitList = false; 3712 Visit(E); 3713 } 3714 3715 if (Field) 3716 Decls.erase(Field); 3717 if (BaseClass) 3718 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3719 } 3720 3721 void VisitMemberExpr(MemberExpr *ME) { 3722 // All uses of unbounded reference fields will warn. 3723 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3724 } 3725 3726 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3727 if (E->getCastKind() == CK_LValueToRValue) { 3728 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3729 return; 3730 } 3731 3732 Inherited::VisitImplicitCastExpr(E); 3733 } 3734 3735 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3736 if (E->getConstructor()->isCopyConstructor()) { 3737 Expr *ArgExpr = E->getArg(0); 3738 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3739 if (ILE->getNumInits() == 1) 3740 ArgExpr = ILE->getInit(0); 3741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3742 if (ICE->getCastKind() == CK_NoOp) 3743 ArgExpr = ICE->getSubExpr(); 3744 HandleValue(ArgExpr, false /*AddressOf*/); 3745 return; 3746 } 3747 Inherited::VisitCXXConstructExpr(E); 3748 } 3749 3750 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3751 Expr *Callee = E->getCallee(); 3752 if (isa<MemberExpr>(Callee)) { 3753 HandleValue(Callee, false /*AddressOf*/); 3754 for (auto Arg : E->arguments()) 3755 Visit(Arg); 3756 return; 3757 } 3758 3759 Inherited::VisitCXXMemberCallExpr(E); 3760 } 3761 3762 void VisitCallExpr(CallExpr *E) { 3763 // Treat std::move as a use. 3764 if (E->isCallToStdMove()) { 3765 HandleValue(E->getArg(0), /*AddressOf=*/false); 3766 return; 3767 } 3768 3769 Inherited::VisitCallExpr(E); 3770 } 3771 3772 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3773 Expr *Callee = E->getCallee(); 3774 3775 if (isa<UnresolvedLookupExpr>(Callee)) 3776 return Inherited::VisitCXXOperatorCallExpr(E); 3777 3778 Visit(Callee); 3779 for (auto Arg : E->arguments()) 3780 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3781 } 3782 3783 void VisitBinaryOperator(BinaryOperator *E) { 3784 // If a field assignment is detected, remove the field from the 3785 // uninitiailized field set. 3786 if (E->getOpcode() == BO_Assign) 3787 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3788 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3789 if (!FD->getType()->isReferenceType()) 3790 DeclsToRemove.push_back(FD); 3791 3792 if (E->isCompoundAssignmentOp()) { 3793 HandleValue(E->getLHS(), false /*AddressOf*/); 3794 Visit(E->getRHS()); 3795 return; 3796 } 3797 3798 Inherited::VisitBinaryOperator(E); 3799 } 3800 3801 void VisitUnaryOperator(UnaryOperator *E) { 3802 if (E->isIncrementDecrementOp()) { 3803 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3804 return; 3805 } 3806 if (E->getOpcode() == UO_AddrOf) { 3807 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3808 HandleValue(ME->getBase(), true /*AddressOf*/); 3809 return; 3810 } 3811 } 3812 3813 Inherited::VisitUnaryOperator(E); 3814 } 3815 }; 3816 3817 // Diagnose value-uses of fields to initialize themselves, e.g. 3818 // foo(foo) 3819 // where foo is not also a parameter to the constructor. 3820 // Also diagnose across field uninitialized use such as 3821 // x(y), y(x) 3822 // TODO: implement -Wuninitialized and fold this into that framework. 3823 static void DiagnoseUninitializedFields( 3824 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3825 3826 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3827 Constructor->getLocation())) { 3828 return; 3829 } 3830 3831 if (Constructor->isInvalidDecl()) 3832 return; 3833 3834 const CXXRecordDecl *RD = Constructor->getParent(); 3835 3836 if (RD->isDependentContext()) 3837 return; 3838 3839 // Holds fields that are uninitialized. 3840 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3841 3842 // At the beginning, all fields are uninitialized. 3843 for (auto *I : RD->decls()) { 3844 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3845 UninitializedFields.insert(FD); 3846 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3847 UninitializedFields.insert(IFD->getAnonField()); 3848 } 3849 } 3850 3851 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3852 for (auto I : RD->bases()) 3853 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3854 3855 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3856 return; 3857 3858 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3859 UninitializedFields, 3860 UninitializedBaseClasses); 3861 3862 for (const auto *FieldInit : Constructor->inits()) { 3863 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3864 break; 3865 3866 Expr *InitExpr = FieldInit->getInit(); 3867 if (!InitExpr) 3868 continue; 3869 3870 if (CXXDefaultInitExpr *Default = 3871 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3872 InitExpr = Default->getExpr(); 3873 if (!InitExpr) 3874 continue; 3875 // In class initializers will point to the constructor. 3876 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3877 FieldInit->getAnyMember(), 3878 FieldInit->getBaseClass()); 3879 } else { 3880 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3881 FieldInit->getAnyMember(), 3882 FieldInit->getBaseClass()); 3883 } 3884 } 3885 } 3886 } // namespace 3887 3888 /// Enter a new C++ default initializer scope. After calling this, the 3889 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3890 /// parsing or instantiating the initializer failed. 3891 void Sema::ActOnStartCXXInClassMemberInitializer() { 3892 // Create a synthetic function scope to represent the call to the constructor 3893 // that notionally surrounds a use of this initializer. 3894 PushFunctionScope(); 3895 } 3896 3897 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3898 if (!D.isFunctionDeclarator()) 3899 return; 3900 auto &FTI = D.getFunctionTypeInfo(); 3901 if (!FTI.Params) 3902 return; 3903 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3904 FTI.NumParams)) { 3905 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3906 if (ParamDecl->getDeclName()) 3907 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3908 } 3909 } 3910 3911 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3912 if (ConstraintExpr.isInvalid()) 3913 return ExprError(); 3914 return CorrectDelayedTyposInExpr(ConstraintExpr); 3915 } 3916 3917 /// This is invoked after parsing an in-class initializer for a 3918 /// non-static C++ class member, and after instantiating an in-class initializer 3919 /// in a class template. Such actions are deferred until the class is complete. 3920 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3921 SourceLocation InitLoc, 3922 Expr *InitExpr) { 3923 // Pop the notional constructor scope we created earlier. 3924 PopFunctionScopeInfo(nullptr, D); 3925 3926 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3927 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3928 "must set init style when field is created"); 3929 3930 if (!InitExpr) { 3931 D->setInvalidDecl(); 3932 if (FD) 3933 FD->removeInClassInitializer(); 3934 return; 3935 } 3936 3937 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3938 FD->setInvalidDecl(); 3939 FD->removeInClassInitializer(); 3940 return; 3941 } 3942 3943 ExprResult Init = InitExpr; 3944 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3945 InitializedEntity Entity = 3946 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3947 InitializationKind Kind = 3948 FD->getInClassInitStyle() == ICIS_ListInit 3949 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3950 InitExpr->getBeginLoc(), 3951 InitExpr->getEndLoc()) 3952 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3953 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3954 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3955 if (Init.isInvalid()) { 3956 FD->setInvalidDecl(); 3957 return; 3958 } 3959 } 3960 3961 // C++11 [class.base.init]p7: 3962 // The initialization of each base and member constitutes a 3963 // full-expression. 3964 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3965 if (Init.isInvalid()) { 3966 FD->setInvalidDecl(); 3967 return; 3968 } 3969 3970 InitExpr = Init.get(); 3971 3972 FD->setInClassInitializer(InitExpr); 3973 } 3974 3975 /// Find the direct and/or virtual base specifiers that 3976 /// correspond to the given base type, for use in base initialization 3977 /// within a constructor. 3978 static bool FindBaseInitializer(Sema &SemaRef, 3979 CXXRecordDecl *ClassDecl, 3980 QualType BaseType, 3981 const CXXBaseSpecifier *&DirectBaseSpec, 3982 const CXXBaseSpecifier *&VirtualBaseSpec) { 3983 // First, check for a direct base class. 3984 DirectBaseSpec = nullptr; 3985 for (const auto &Base : ClassDecl->bases()) { 3986 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3987 // We found a direct base of this type. That's what we're 3988 // initializing. 3989 DirectBaseSpec = &Base; 3990 break; 3991 } 3992 } 3993 3994 // Check for a virtual base class. 3995 // FIXME: We might be able to short-circuit this if we know in advance that 3996 // there are no virtual bases. 3997 VirtualBaseSpec = nullptr; 3998 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3999 // We haven't found a base yet; search the class hierarchy for a 4000 // virtual base class. 4001 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4002 /*DetectVirtual=*/false); 4003 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4004 SemaRef.Context.getTypeDeclType(ClassDecl), 4005 BaseType, Paths)) { 4006 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4007 Path != Paths.end(); ++Path) { 4008 if (Path->back().Base->isVirtual()) { 4009 VirtualBaseSpec = Path->back().Base; 4010 break; 4011 } 4012 } 4013 } 4014 } 4015 4016 return DirectBaseSpec || VirtualBaseSpec; 4017 } 4018 4019 /// Handle a C++ member initializer using braced-init-list syntax. 4020 MemInitResult 4021 Sema::ActOnMemInitializer(Decl *ConstructorD, 4022 Scope *S, 4023 CXXScopeSpec &SS, 4024 IdentifierInfo *MemberOrBase, 4025 ParsedType TemplateTypeTy, 4026 const DeclSpec &DS, 4027 SourceLocation IdLoc, 4028 Expr *InitList, 4029 SourceLocation EllipsisLoc) { 4030 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4031 DS, IdLoc, InitList, 4032 EllipsisLoc); 4033 } 4034 4035 /// Handle a C++ member initializer using parentheses syntax. 4036 MemInitResult 4037 Sema::ActOnMemInitializer(Decl *ConstructorD, 4038 Scope *S, 4039 CXXScopeSpec &SS, 4040 IdentifierInfo *MemberOrBase, 4041 ParsedType TemplateTypeTy, 4042 const DeclSpec &DS, 4043 SourceLocation IdLoc, 4044 SourceLocation LParenLoc, 4045 ArrayRef<Expr *> Args, 4046 SourceLocation RParenLoc, 4047 SourceLocation EllipsisLoc) { 4048 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4049 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4050 DS, IdLoc, List, EllipsisLoc); 4051 } 4052 4053 namespace { 4054 4055 // Callback to only accept typo corrections that can be a valid C++ member 4056 // intializer: either a non-static field member or a base class. 4057 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4058 public: 4059 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4060 : ClassDecl(ClassDecl) {} 4061 4062 bool ValidateCandidate(const TypoCorrection &candidate) override { 4063 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4064 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4065 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4066 return isa<TypeDecl>(ND); 4067 } 4068 return false; 4069 } 4070 4071 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4072 return std::make_unique<MemInitializerValidatorCCC>(*this); 4073 } 4074 4075 private: 4076 CXXRecordDecl *ClassDecl; 4077 }; 4078 4079 } 4080 4081 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4082 CXXScopeSpec &SS, 4083 ParsedType TemplateTypeTy, 4084 IdentifierInfo *MemberOrBase) { 4085 if (SS.getScopeRep() || TemplateTypeTy) 4086 return nullptr; 4087 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4088 if (Result.empty()) 4089 return nullptr; 4090 ValueDecl *Member; 4091 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4092 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4093 return Member; 4094 return nullptr; 4095 } 4096 4097 /// Handle a C++ member initializer. 4098 MemInitResult 4099 Sema::BuildMemInitializer(Decl *ConstructorD, 4100 Scope *S, 4101 CXXScopeSpec &SS, 4102 IdentifierInfo *MemberOrBase, 4103 ParsedType TemplateTypeTy, 4104 const DeclSpec &DS, 4105 SourceLocation IdLoc, 4106 Expr *Init, 4107 SourceLocation EllipsisLoc) { 4108 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4109 if (!Res.isUsable()) 4110 return true; 4111 Init = Res.get(); 4112 4113 if (!ConstructorD) 4114 return true; 4115 4116 AdjustDeclIfTemplate(ConstructorD); 4117 4118 CXXConstructorDecl *Constructor 4119 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4120 if (!Constructor) { 4121 // The user wrote a constructor initializer on a function that is 4122 // not a C++ constructor. Ignore the error for now, because we may 4123 // have more member initializers coming; we'll diagnose it just 4124 // once in ActOnMemInitializers. 4125 return true; 4126 } 4127 4128 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4129 4130 // C++ [class.base.init]p2: 4131 // Names in a mem-initializer-id are looked up in the scope of the 4132 // constructor's class and, if not found in that scope, are looked 4133 // up in the scope containing the constructor's definition. 4134 // [Note: if the constructor's class contains a member with the 4135 // same name as a direct or virtual base class of the class, a 4136 // mem-initializer-id naming the member or base class and composed 4137 // of a single identifier refers to the class member. A 4138 // mem-initializer-id for the hidden base class may be specified 4139 // using a qualified name. ] 4140 4141 // Look for a member, first. 4142 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4143 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4144 if (EllipsisLoc.isValid()) 4145 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4146 << MemberOrBase 4147 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4148 4149 return BuildMemberInitializer(Member, Init, IdLoc); 4150 } 4151 // It didn't name a member, so see if it names a class. 4152 QualType BaseType; 4153 TypeSourceInfo *TInfo = nullptr; 4154 4155 if (TemplateTypeTy) { 4156 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4157 if (BaseType.isNull()) 4158 return true; 4159 } else if (DS.getTypeSpecType() == TST_decltype) { 4160 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4161 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4162 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4163 return true; 4164 } else { 4165 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4166 LookupParsedName(R, S, &SS); 4167 4168 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4169 if (!TyD) { 4170 if (R.isAmbiguous()) return true; 4171 4172 // We don't want access-control diagnostics here. 4173 R.suppressDiagnostics(); 4174 4175 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4176 bool NotUnknownSpecialization = false; 4177 DeclContext *DC = computeDeclContext(SS, false); 4178 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4179 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4180 4181 if (!NotUnknownSpecialization) { 4182 // When the scope specifier can refer to a member of an unknown 4183 // specialization, we take it as a type name. 4184 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4185 SS.getWithLocInContext(Context), 4186 *MemberOrBase, IdLoc); 4187 if (BaseType.isNull()) 4188 return true; 4189 4190 TInfo = Context.CreateTypeSourceInfo(BaseType); 4191 DependentNameTypeLoc TL = 4192 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4193 if (!TL.isNull()) { 4194 TL.setNameLoc(IdLoc); 4195 TL.setElaboratedKeywordLoc(SourceLocation()); 4196 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4197 } 4198 4199 R.clear(); 4200 R.setLookupName(MemberOrBase); 4201 } 4202 } 4203 4204 // If no results were found, try to correct typos. 4205 TypoCorrection Corr; 4206 MemInitializerValidatorCCC CCC(ClassDecl); 4207 if (R.empty() && BaseType.isNull() && 4208 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4209 CCC, CTK_ErrorRecovery, ClassDecl))) { 4210 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4211 // We have found a non-static data member with a similar 4212 // name to what was typed; complain and initialize that 4213 // member. 4214 diagnoseTypo(Corr, 4215 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4216 << MemberOrBase << true); 4217 return BuildMemberInitializer(Member, Init, IdLoc); 4218 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4219 const CXXBaseSpecifier *DirectBaseSpec; 4220 const CXXBaseSpecifier *VirtualBaseSpec; 4221 if (FindBaseInitializer(*this, ClassDecl, 4222 Context.getTypeDeclType(Type), 4223 DirectBaseSpec, VirtualBaseSpec)) { 4224 // We have found a direct or virtual base class with a 4225 // similar name to what was typed; complain and initialize 4226 // that base class. 4227 diagnoseTypo(Corr, 4228 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4229 << MemberOrBase << false, 4230 PDiag() /*Suppress note, we provide our own.*/); 4231 4232 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4233 : VirtualBaseSpec; 4234 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4235 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4236 4237 TyD = Type; 4238 } 4239 } 4240 } 4241 4242 if (!TyD && BaseType.isNull()) { 4243 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4244 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4245 return true; 4246 } 4247 } 4248 4249 if (BaseType.isNull()) { 4250 BaseType = Context.getTypeDeclType(TyD); 4251 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4252 if (SS.isSet()) { 4253 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4254 BaseType); 4255 TInfo = Context.CreateTypeSourceInfo(BaseType); 4256 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4257 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4258 TL.setElaboratedKeywordLoc(SourceLocation()); 4259 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4260 } 4261 } 4262 } 4263 4264 if (!TInfo) 4265 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4266 4267 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4268 } 4269 4270 MemInitResult 4271 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4272 SourceLocation IdLoc) { 4273 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4274 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4275 assert((DirectMember || IndirectMember) && 4276 "Member must be a FieldDecl or IndirectFieldDecl"); 4277 4278 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4279 return true; 4280 4281 if (Member->isInvalidDecl()) 4282 return true; 4283 4284 MultiExprArg Args; 4285 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4286 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4287 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4288 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4289 } else { 4290 // Template instantiation doesn't reconstruct ParenListExprs for us. 4291 Args = Init; 4292 } 4293 4294 SourceRange InitRange = Init->getSourceRange(); 4295 4296 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4297 // Can't check initialization for a member of dependent type or when 4298 // any of the arguments are type-dependent expressions. 4299 DiscardCleanupsInEvaluationContext(); 4300 } else { 4301 bool InitList = false; 4302 if (isa<InitListExpr>(Init)) { 4303 InitList = true; 4304 Args = Init; 4305 } 4306 4307 // Initialize the member. 4308 InitializedEntity MemberEntity = 4309 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4310 : InitializedEntity::InitializeMember(IndirectMember, 4311 nullptr); 4312 InitializationKind Kind = 4313 InitList ? InitializationKind::CreateDirectList( 4314 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4315 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4316 InitRange.getEnd()); 4317 4318 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4319 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4320 nullptr); 4321 if (MemberInit.isInvalid()) 4322 return true; 4323 4324 // C++11 [class.base.init]p7: 4325 // The initialization of each base and member constitutes a 4326 // full-expression. 4327 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4328 /*DiscardedValue*/ false); 4329 if (MemberInit.isInvalid()) 4330 return true; 4331 4332 Init = MemberInit.get(); 4333 } 4334 4335 if (DirectMember) { 4336 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4337 InitRange.getBegin(), Init, 4338 InitRange.getEnd()); 4339 } else { 4340 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4341 InitRange.getBegin(), Init, 4342 InitRange.getEnd()); 4343 } 4344 } 4345 4346 MemInitResult 4347 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4348 CXXRecordDecl *ClassDecl) { 4349 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4350 if (!LangOpts.CPlusPlus11) 4351 return Diag(NameLoc, diag::err_delegating_ctor) 4352 << TInfo->getTypeLoc().getLocalSourceRange(); 4353 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4354 4355 bool InitList = true; 4356 MultiExprArg Args = Init; 4357 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4358 InitList = false; 4359 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4360 } 4361 4362 SourceRange InitRange = Init->getSourceRange(); 4363 // Initialize the object. 4364 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4365 QualType(ClassDecl->getTypeForDecl(), 0)); 4366 InitializationKind Kind = 4367 InitList ? InitializationKind::CreateDirectList( 4368 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4369 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4370 InitRange.getEnd()); 4371 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4372 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4373 Args, nullptr); 4374 if (DelegationInit.isInvalid()) 4375 return true; 4376 4377 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4378 "Delegating constructor with no target?"); 4379 4380 // C++11 [class.base.init]p7: 4381 // The initialization of each base and member constitutes a 4382 // full-expression. 4383 DelegationInit = ActOnFinishFullExpr( 4384 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4385 if (DelegationInit.isInvalid()) 4386 return true; 4387 4388 // If we are in a dependent context, template instantiation will 4389 // perform this type-checking again. Just save the arguments that we 4390 // received in a ParenListExpr. 4391 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4392 // of the information that we have about the base 4393 // initializer. However, deconstructing the ASTs is a dicey process, 4394 // and this approach is far more likely to get the corner cases right. 4395 if (CurContext->isDependentContext()) 4396 DelegationInit = Init; 4397 4398 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4399 DelegationInit.getAs<Expr>(), 4400 InitRange.getEnd()); 4401 } 4402 4403 MemInitResult 4404 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4405 Expr *Init, CXXRecordDecl *ClassDecl, 4406 SourceLocation EllipsisLoc) { 4407 SourceLocation BaseLoc 4408 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4409 4410 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4411 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4412 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4413 4414 // C++ [class.base.init]p2: 4415 // [...] Unless the mem-initializer-id names a nonstatic data 4416 // member of the constructor's class or a direct or virtual base 4417 // of that class, the mem-initializer is ill-formed. A 4418 // mem-initializer-list can initialize a base class using any 4419 // name that denotes that base class type. 4420 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4421 4422 SourceRange InitRange = Init->getSourceRange(); 4423 if (EllipsisLoc.isValid()) { 4424 // This is a pack expansion. 4425 if (!BaseType->containsUnexpandedParameterPack()) { 4426 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4427 << SourceRange(BaseLoc, InitRange.getEnd()); 4428 4429 EllipsisLoc = SourceLocation(); 4430 } 4431 } else { 4432 // Check for any unexpanded parameter packs. 4433 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4434 return true; 4435 4436 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4437 return true; 4438 } 4439 4440 // Check for direct and virtual base classes. 4441 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4442 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4443 if (!Dependent) { 4444 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4445 BaseType)) 4446 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4447 4448 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4449 VirtualBaseSpec); 4450 4451 // C++ [base.class.init]p2: 4452 // Unless the mem-initializer-id names a nonstatic data member of the 4453 // constructor's class or a direct or virtual base of that class, the 4454 // mem-initializer is ill-formed. 4455 if (!DirectBaseSpec && !VirtualBaseSpec) { 4456 // If the class has any dependent bases, then it's possible that 4457 // one of those types will resolve to the same type as 4458 // BaseType. Therefore, just treat this as a dependent base 4459 // class initialization. FIXME: Should we try to check the 4460 // initialization anyway? It seems odd. 4461 if (ClassDecl->hasAnyDependentBases()) 4462 Dependent = true; 4463 else 4464 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4465 << BaseType << Context.getTypeDeclType(ClassDecl) 4466 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4467 } 4468 } 4469 4470 if (Dependent) { 4471 DiscardCleanupsInEvaluationContext(); 4472 4473 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4474 /*IsVirtual=*/false, 4475 InitRange.getBegin(), Init, 4476 InitRange.getEnd(), EllipsisLoc); 4477 } 4478 4479 // C++ [base.class.init]p2: 4480 // If a mem-initializer-id is ambiguous because it designates both 4481 // a direct non-virtual base class and an inherited virtual base 4482 // class, the mem-initializer is ill-formed. 4483 if (DirectBaseSpec && VirtualBaseSpec) 4484 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4485 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4486 4487 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4488 if (!BaseSpec) 4489 BaseSpec = VirtualBaseSpec; 4490 4491 // Initialize the base. 4492 bool InitList = true; 4493 MultiExprArg Args = Init; 4494 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4495 InitList = false; 4496 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4497 } 4498 4499 InitializedEntity BaseEntity = 4500 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4501 InitializationKind Kind = 4502 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4503 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4504 InitRange.getEnd()); 4505 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4506 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4507 if (BaseInit.isInvalid()) 4508 return true; 4509 4510 // C++11 [class.base.init]p7: 4511 // The initialization of each base and member constitutes a 4512 // full-expression. 4513 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4514 /*DiscardedValue*/ false); 4515 if (BaseInit.isInvalid()) 4516 return true; 4517 4518 // If we are in a dependent context, template instantiation will 4519 // perform this type-checking again. Just save the arguments that we 4520 // received in a ParenListExpr. 4521 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4522 // of the information that we have about the base 4523 // initializer. However, deconstructing the ASTs is a dicey process, 4524 // and this approach is far more likely to get the corner cases right. 4525 if (CurContext->isDependentContext()) 4526 BaseInit = Init; 4527 4528 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4529 BaseSpec->isVirtual(), 4530 InitRange.getBegin(), 4531 BaseInit.getAs<Expr>(), 4532 InitRange.getEnd(), EllipsisLoc); 4533 } 4534 4535 // Create a static_cast\<T&&>(expr). 4536 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4537 if (T.isNull()) T = E->getType(); 4538 QualType TargetType = SemaRef.BuildReferenceType( 4539 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4540 SourceLocation ExprLoc = E->getBeginLoc(); 4541 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4542 TargetType, ExprLoc); 4543 4544 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4545 SourceRange(ExprLoc, ExprLoc), 4546 E->getSourceRange()).get(); 4547 } 4548 4549 /// ImplicitInitializerKind - How an implicit base or member initializer should 4550 /// initialize its base or member. 4551 enum ImplicitInitializerKind { 4552 IIK_Default, 4553 IIK_Copy, 4554 IIK_Move, 4555 IIK_Inherit 4556 }; 4557 4558 static bool 4559 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4560 ImplicitInitializerKind ImplicitInitKind, 4561 CXXBaseSpecifier *BaseSpec, 4562 bool IsInheritedVirtualBase, 4563 CXXCtorInitializer *&CXXBaseInit) { 4564 InitializedEntity InitEntity 4565 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4566 IsInheritedVirtualBase); 4567 4568 ExprResult BaseInit; 4569 4570 switch (ImplicitInitKind) { 4571 case IIK_Inherit: 4572 case IIK_Default: { 4573 InitializationKind InitKind 4574 = InitializationKind::CreateDefault(Constructor->getLocation()); 4575 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4576 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4577 break; 4578 } 4579 4580 case IIK_Move: 4581 case IIK_Copy: { 4582 bool Moving = ImplicitInitKind == IIK_Move; 4583 ParmVarDecl *Param = Constructor->getParamDecl(0); 4584 QualType ParamType = Param->getType().getNonReferenceType(); 4585 4586 Expr *CopyCtorArg = 4587 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4588 SourceLocation(), Param, false, 4589 Constructor->getLocation(), ParamType, 4590 VK_LValue, nullptr); 4591 4592 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4593 4594 // Cast to the base class to avoid ambiguities. 4595 QualType ArgTy = 4596 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4597 ParamType.getQualifiers()); 4598 4599 if (Moving) { 4600 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4601 } 4602 4603 CXXCastPath BasePath; 4604 BasePath.push_back(BaseSpec); 4605 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4606 CK_UncheckedDerivedToBase, 4607 Moving ? VK_XValue : VK_LValue, 4608 &BasePath).get(); 4609 4610 InitializationKind InitKind 4611 = InitializationKind::CreateDirect(Constructor->getLocation(), 4612 SourceLocation(), SourceLocation()); 4613 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4614 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4615 break; 4616 } 4617 } 4618 4619 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4620 if (BaseInit.isInvalid()) 4621 return true; 4622 4623 CXXBaseInit = 4624 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4625 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4626 SourceLocation()), 4627 BaseSpec->isVirtual(), 4628 SourceLocation(), 4629 BaseInit.getAs<Expr>(), 4630 SourceLocation(), 4631 SourceLocation()); 4632 4633 return false; 4634 } 4635 4636 static bool RefersToRValueRef(Expr *MemRef) { 4637 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4638 return Referenced->getType()->isRValueReferenceType(); 4639 } 4640 4641 static bool 4642 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4643 ImplicitInitializerKind ImplicitInitKind, 4644 FieldDecl *Field, IndirectFieldDecl *Indirect, 4645 CXXCtorInitializer *&CXXMemberInit) { 4646 if (Field->isInvalidDecl()) 4647 return true; 4648 4649 SourceLocation Loc = Constructor->getLocation(); 4650 4651 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4652 bool Moving = ImplicitInitKind == IIK_Move; 4653 ParmVarDecl *Param = Constructor->getParamDecl(0); 4654 QualType ParamType = Param->getType().getNonReferenceType(); 4655 4656 // Suppress copying zero-width bitfields. 4657 if (Field->isZeroLengthBitField(SemaRef.Context)) 4658 return false; 4659 4660 Expr *MemberExprBase = 4661 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4662 SourceLocation(), Param, false, 4663 Loc, ParamType, VK_LValue, nullptr); 4664 4665 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4666 4667 if (Moving) { 4668 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4669 } 4670 4671 // Build a reference to this field within the parameter. 4672 CXXScopeSpec SS; 4673 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4674 Sema::LookupMemberName); 4675 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4676 : cast<ValueDecl>(Field), AS_public); 4677 MemberLookup.resolveKind(); 4678 ExprResult CtorArg 4679 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4680 ParamType, Loc, 4681 /*IsArrow=*/false, 4682 SS, 4683 /*TemplateKWLoc=*/SourceLocation(), 4684 /*FirstQualifierInScope=*/nullptr, 4685 MemberLookup, 4686 /*TemplateArgs=*/nullptr, 4687 /*S*/nullptr); 4688 if (CtorArg.isInvalid()) 4689 return true; 4690 4691 // C++11 [class.copy]p15: 4692 // - if a member m has rvalue reference type T&&, it is direct-initialized 4693 // with static_cast<T&&>(x.m); 4694 if (RefersToRValueRef(CtorArg.get())) { 4695 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4696 } 4697 4698 InitializedEntity Entity = 4699 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4700 /*Implicit*/ true) 4701 : InitializedEntity::InitializeMember(Field, nullptr, 4702 /*Implicit*/ true); 4703 4704 // Direct-initialize to use the copy constructor. 4705 InitializationKind InitKind = 4706 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4707 4708 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4709 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4710 ExprResult MemberInit = 4711 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4712 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4713 if (MemberInit.isInvalid()) 4714 return true; 4715 4716 if (Indirect) 4717 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4718 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4719 else 4720 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4721 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4722 return false; 4723 } 4724 4725 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4726 "Unhandled implicit init kind!"); 4727 4728 QualType FieldBaseElementType = 4729 SemaRef.Context.getBaseElementType(Field->getType()); 4730 4731 if (FieldBaseElementType->isRecordType()) { 4732 InitializedEntity InitEntity = 4733 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4734 /*Implicit*/ true) 4735 : InitializedEntity::InitializeMember(Field, nullptr, 4736 /*Implicit*/ true); 4737 InitializationKind InitKind = 4738 InitializationKind::CreateDefault(Loc); 4739 4740 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4741 ExprResult MemberInit = 4742 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4743 4744 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4745 if (MemberInit.isInvalid()) 4746 return true; 4747 4748 if (Indirect) 4749 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4750 Indirect, Loc, 4751 Loc, 4752 MemberInit.get(), 4753 Loc); 4754 else 4755 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4756 Field, Loc, Loc, 4757 MemberInit.get(), 4758 Loc); 4759 return false; 4760 } 4761 4762 if (!Field->getParent()->isUnion()) { 4763 if (FieldBaseElementType->isReferenceType()) { 4764 SemaRef.Diag(Constructor->getLocation(), 4765 diag::err_uninitialized_member_in_ctor) 4766 << (int)Constructor->isImplicit() 4767 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4768 << 0 << Field->getDeclName(); 4769 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4770 return true; 4771 } 4772 4773 if (FieldBaseElementType.isConstQualified()) { 4774 SemaRef.Diag(Constructor->getLocation(), 4775 diag::err_uninitialized_member_in_ctor) 4776 << (int)Constructor->isImplicit() 4777 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4778 << 1 << Field->getDeclName(); 4779 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4780 return true; 4781 } 4782 } 4783 4784 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4785 // ARC and Weak: 4786 // Default-initialize Objective-C pointers to NULL. 4787 CXXMemberInit 4788 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4789 Loc, Loc, 4790 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4791 Loc); 4792 return false; 4793 } 4794 4795 // Nothing to initialize. 4796 CXXMemberInit = nullptr; 4797 return false; 4798 } 4799 4800 namespace { 4801 struct BaseAndFieldInfo { 4802 Sema &S; 4803 CXXConstructorDecl *Ctor; 4804 bool AnyErrorsInInits; 4805 ImplicitInitializerKind IIK; 4806 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4807 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4808 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4809 4810 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4811 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4812 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4813 if (Ctor->getInheritedConstructor()) 4814 IIK = IIK_Inherit; 4815 else if (Generated && Ctor->isCopyConstructor()) 4816 IIK = IIK_Copy; 4817 else if (Generated && Ctor->isMoveConstructor()) 4818 IIK = IIK_Move; 4819 else 4820 IIK = IIK_Default; 4821 } 4822 4823 bool isImplicitCopyOrMove() const { 4824 switch (IIK) { 4825 case IIK_Copy: 4826 case IIK_Move: 4827 return true; 4828 4829 case IIK_Default: 4830 case IIK_Inherit: 4831 return false; 4832 } 4833 4834 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4835 } 4836 4837 bool addFieldInitializer(CXXCtorInitializer *Init) { 4838 AllToInit.push_back(Init); 4839 4840 // Check whether this initializer makes the field "used". 4841 if (Init->getInit()->HasSideEffects(S.Context)) 4842 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4843 4844 return false; 4845 } 4846 4847 bool isInactiveUnionMember(FieldDecl *Field) { 4848 RecordDecl *Record = Field->getParent(); 4849 if (!Record->isUnion()) 4850 return false; 4851 4852 if (FieldDecl *Active = 4853 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4854 return Active != Field->getCanonicalDecl(); 4855 4856 // In an implicit copy or move constructor, ignore any in-class initializer. 4857 if (isImplicitCopyOrMove()) 4858 return true; 4859 4860 // If there's no explicit initialization, the field is active only if it 4861 // has an in-class initializer... 4862 if (Field->hasInClassInitializer()) 4863 return false; 4864 // ... or it's an anonymous struct or union whose class has an in-class 4865 // initializer. 4866 if (!Field->isAnonymousStructOrUnion()) 4867 return true; 4868 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4869 return !FieldRD->hasInClassInitializer(); 4870 } 4871 4872 /// Determine whether the given field is, or is within, a union member 4873 /// that is inactive (because there was an initializer given for a different 4874 /// member of the union, or because the union was not initialized at all). 4875 bool isWithinInactiveUnionMember(FieldDecl *Field, 4876 IndirectFieldDecl *Indirect) { 4877 if (!Indirect) 4878 return isInactiveUnionMember(Field); 4879 4880 for (auto *C : Indirect->chain()) { 4881 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4882 if (Field && isInactiveUnionMember(Field)) 4883 return true; 4884 } 4885 return false; 4886 } 4887 }; 4888 } 4889 4890 /// Determine whether the given type is an incomplete or zero-lenfgth 4891 /// array type. 4892 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4893 if (T->isIncompleteArrayType()) 4894 return true; 4895 4896 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4897 if (!ArrayT->getSize()) 4898 return true; 4899 4900 T = ArrayT->getElementType(); 4901 } 4902 4903 return false; 4904 } 4905 4906 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4907 FieldDecl *Field, 4908 IndirectFieldDecl *Indirect = nullptr) { 4909 if (Field->isInvalidDecl()) 4910 return false; 4911 4912 // Overwhelmingly common case: we have a direct initializer for this field. 4913 if (CXXCtorInitializer *Init = 4914 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4915 return Info.addFieldInitializer(Init); 4916 4917 // C++11 [class.base.init]p8: 4918 // if the entity is a non-static data member that has a 4919 // brace-or-equal-initializer and either 4920 // -- the constructor's class is a union and no other variant member of that 4921 // union is designated by a mem-initializer-id or 4922 // -- the constructor's class is not a union, and, if the entity is a member 4923 // of an anonymous union, no other member of that union is designated by 4924 // a mem-initializer-id, 4925 // the entity is initialized as specified in [dcl.init]. 4926 // 4927 // We also apply the same rules to handle anonymous structs within anonymous 4928 // unions. 4929 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4930 return false; 4931 4932 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4933 ExprResult DIE = 4934 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4935 if (DIE.isInvalid()) 4936 return true; 4937 4938 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4939 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4940 4941 CXXCtorInitializer *Init; 4942 if (Indirect) 4943 Init = new (SemaRef.Context) 4944 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4945 SourceLocation(), DIE.get(), SourceLocation()); 4946 else 4947 Init = new (SemaRef.Context) 4948 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4949 SourceLocation(), DIE.get(), SourceLocation()); 4950 return Info.addFieldInitializer(Init); 4951 } 4952 4953 // Don't initialize incomplete or zero-length arrays. 4954 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4955 return false; 4956 4957 // Don't try to build an implicit initializer if there were semantic 4958 // errors in any of the initializers (and therefore we might be 4959 // missing some that the user actually wrote). 4960 if (Info.AnyErrorsInInits) 4961 return false; 4962 4963 CXXCtorInitializer *Init = nullptr; 4964 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4965 Indirect, Init)) 4966 return true; 4967 4968 if (!Init) 4969 return false; 4970 4971 return Info.addFieldInitializer(Init); 4972 } 4973 4974 bool 4975 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4976 CXXCtorInitializer *Initializer) { 4977 assert(Initializer->isDelegatingInitializer()); 4978 Constructor->setNumCtorInitializers(1); 4979 CXXCtorInitializer **initializer = 4980 new (Context) CXXCtorInitializer*[1]; 4981 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4982 Constructor->setCtorInitializers(initializer); 4983 4984 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4985 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4986 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4987 } 4988 4989 DelegatingCtorDecls.push_back(Constructor); 4990 4991 DiagnoseUninitializedFields(*this, Constructor); 4992 4993 return false; 4994 } 4995 4996 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4997 ArrayRef<CXXCtorInitializer *> Initializers) { 4998 if (Constructor->isDependentContext()) { 4999 // Just store the initializers as written, they will be checked during 5000 // instantiation. 5001 if (!Initializers.empty()) { 5002 Constructor->setNumCtorInitializers(Initializers.size()); 5003 CXXCtorInitializer **baseOrMemberInitializers = 5004 new (Context) CXXCtorInitializer*[Initializers.size()]; 5005 memcpy(baseOrMemberInitializers, Initializers.data(), 5006 Initializers.size() * sizeof(CXXCtorInitializer*)); 5007 Constructor->setCtorInitializers(baseOrMemberInitializers); 5008 } 5009 5010 // Let template instantiation know whether we had errors. 5011 if (AnyErrors) 5012 Constructor->setInvalidDecl(); 5013 5014 return false; 5015 } 5016 5017 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5018 5019 // We need to build the initializer AST according to order of construction 5020 // and not what user specified in the Initializers list. 5021 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5022 if (!ClassDecl) 5023 return true; 5024 5025 bool HadError = false; 5026 5027 for (unsigned i = 0; i < Initializers.size(); i++) { 5028 CXXCtorInitializer *Member = Initializers[i]; 5029 5030 if (Member->isBaseInitializer()) 5031 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5032 else { 5033 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5034 5035 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5036 for (auto *C : F->chain()) { 5037 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5038 if (FD && FD->getParent()->isUnion()) 5039 Info.ActiveUnionMember.insert(std::make_pair( 5040 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5041 } 5042 } else if (FieldDecl *FD = Member->getMember()) { 5043 if (FD->getParent()->isUnion()) 5044 Info.ActiveUnionMember.insert(std::make_pair( 5045 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5046 } 5047 } 5048 } 5049 5050 // Keep track of the direct virtual bases. 5051 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5052 for (auto &I : ClassDecl->bases()) { 5053 if (I.isVirtual()) 5054 DirectVBases.insert(&I); 5055 } 5056 5057 // Push virtual bases before others. 5058 for (auto &VBase : ClassDecl->vbases()) { 5059 if (CXXCtorInitializer *Value 5060 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5061 // [class.base.init]p7, per DR257: 5062 // A mem-initializer where the mem-initializer-id names a virtual base 5063 // class is ignored during execution of a constructor of any class that 5064 // is not the most derived class. 5065 if (ClassDecl->isAbstract()) { 5066 // FIXME: Provide a fixit to remove the base specifier. This requires 5067 // tracking the location of the associated comma for a base specifier. 5068 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5069 << VBase.getType() << ClassDecl; 5070 DiagnoseAbstractType(ClassDecl); 5071 } 5072 5073 Info.AllToInit.push_back(Value); 5074 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5075 // [class.base.init]p8, per DR257: 5076 // If a given [...] base class is not named by a mem-initializer-id 5077 // [...] and the entity is not a virtual base class of an abstract 5078 // class, then [...] the entity is default-initialized. 5079 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5080 CXXCtorInitializer *CXXBaseInit; 5081 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5082 &VBase, IsInheritedVirtualBase, 5083 CXXBaseInit)) { 5084 HadError = true; 5085 continue; 5086 } 5087 5088 Info.AllToInit.push_back(CXXBaseInit); 5089 } 5090 } 5091 5092 // Non-virtual bases. 5093 for (auto &Base : ClassDecl->bases()) { 5094 // Virtuals are in the virtual base list and already constructed. 5095 if (Base.isVirtual()) 5096 continue; 5097 5098 if (CXXCtorInitializer *Value 5099 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5100 Info.AllToInit.push_back(Value); 5101 } else if (!AnyErrors) { 5102 CXXCtorInitializer *CXXBaseInit; 5103 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5104 &Base, /*IsInheritedVirtualBase=*/false, 5105 CXXBaseInit)) { 5106 HadError = true; 5107 continue; 5108 } 5109 5110 Info.AllToInit.push_back(CXXBaseInit); 5111 } 5112 } 5113 5114 // Fields. 5115 for (auto *Mem : ClassDecl->decls()) { 5116 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5117 // C++ [class.bit]p2: 5118 // A declaration for a bit-field that omits the identifier declares an 5119 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5120 // initialized. 5121 if (F->isUnnamedBitfield()) 5122 continue; 5123 5124 // If we're not generating the implicit copy/move constructor, then we'll 5125 // handle anonymous struct/union fields based on their individual 5126 // indirect fields. 5127 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5128 continue; 5129 5130 if (CollectFieldInitializer(*this, Info, F)) 5131 HadError = true; 5132 continue; 5133 } 5134 5135 // Beyond this point, we only consider default initialization. 5136 if (Info.isImplicitCopyOrMove()) 5137 continue; 5138 5139 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5140 if (F->getType()->isIncompleteArrayType()) { 5141 assert(ClassDecl->hasFlexibleArrayMember() && 5142 "Incomplete array type is not valid"); 5143 continue; 5144 } 5145 5146 // Initialize each field of an anonymous struct individually. 5147 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5148 HadError = true; 5149 5150 continue; 5151 } 5152 } 5153 5154 unsigned NumInitializers = Info.AllToInit.size(); 5155 if (NumInitializers > 0) { 5156 Constructor->setNumCtorInitializers(NumInitializers); 5157 CXXCtorInitializer **baseOrMemberInitializers = 5158 new (Context) CXXCtorInitializer*[NumInitializers]; 5159 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5160 NumInitializers * sizeof(CXXCtorInitializer*)); 5161 Constructor->setCtorInitializers(baseOrMemberInitializers); 5162 5163 // Constructors implicitly reference the base and member 5164 // destructors. 5165 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5166 Constructor->getParent()); 5167 } 5168 5169 return HadError; 5170 } 5171 5172 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5173 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5174 const RecordDecl *RD = RT->getDecl(); 5175 if (RD->isAnonymousStructOrUnion()) { 5176 for (auto *Field : RD->fields()) 5177 PopulateKeysForFields(Field, IdealInits); 5178 return; 5179 } 5180 } 5181 IdealInits.push_back(Field->getCanonicalDecl()); 5182 } 5183 5184 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5185 return Context.getCanonicalType(BaseType).getTypePtr(); 5186 } 5187 5188 static const void *GetKeyForMember(ASTContext &Context, 5189 CXXCtorInitializer *Member) { 5190 if (!Member->isAnyMemberInitializer()) 5191 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5192 5193 return Member->getAnyMember()->getCanonicalDecl(); 5194 } 5195 5196 static void DiagnoseBaseOrMemInitializerOrder( 5197 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5198 ArrayRef<CXXCtorInitializer *> Inits) { 5199 if (Constructor->getDeclContext()->isDependentContext()) 5200 return; 5201 5202 // Don't check initializers order unless the warning is enabled at the 5203 // location of at least one initializer. 5204 bool ShouldCheckOrder = false; 5205 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5206 CXXCtorInitializer *Init = Inits[InitIndex]; 5207 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5208 Init->getSourceLocation())) { 5209 ShouldCheckOrder = true; 5210 break; 5211 } 5212 } 5213 if (!ShouldCheckOrder) 5214 return; 5215 5216 // Build the list of bases and members in the order that they'll 5217 // actually be initialized. The explicit initializers should be in 5218 // this same order but may be missing things. 5219 SmallVector<const void*, 32> IdealInitKeys; 5220 5221 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5222 5223 // 1. Virtual bases. 5224 for (const auto &VBase : ClassDecl->vbases()) 5225 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5226 5227 // 2. Non-virtual bases. 5228 for (const auto &Base : ClassDecl->bases()) { 5229 if (Base.isVirtual()) 5230 continue; 5231 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5232 } 5233 5234 // 3. Direct fields. 5235 for (auto *Field : ClassDecl->fields()) { 5236 if (Field->isUnnamedBitfield()) 5237 continue; 5238 5239 PopulateKeysForFields(Field, IdealInitKeys); 5240 } 5241 5242 unsigned NumIdealInits = IdealInitKeys.size(); 5243 unsigned IdealIndex = 0; 5244 5245 CXXCtorInitializer *PrevInit = nullptr; 5246 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5247 CXXCtorInitializer *Init = Inits[InitIndex]; 5248 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5249 5250 // Scan forward to try to find this initializer in the idealized 5251 // initializers list. 5252 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5253 if (InitKey == IdealInitKeys[IdealIndex]) 5254 break; 5255 5256 // If we didn't find this initializer, it must be because we 5257 // scanned past it on a previous iteration. That can only 5258 // happen if we're out of order; emit a warning. 5259 if (IdealIndex == NumIdealInits && PrevInit) { 5260 Sema::SemaDiagnosticBuilder D = 5261 SemaRef.Diag(PrevInit->getSourceLocation(), 5262 diag::warn_initializer_out_of_order); 5263 5264 if (PrevInit->isAnyMemberInitializer()) 5265 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5266 else 5267 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5268 5269 if (Init->isAnyMemberInitializer()) 5270 D << 0 << Init->getAnyMember()->getDeclName(); 5271 else 5272 D << 1 << Init->getTypeSourceInfo()->getType(); 5273 5274 // Move back to the initializer's location in the ideal list. 5275 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5276 if (InitKey == IdealInitKeys[IdealIndex]) 5277 break; 5278 5279 assert(IdealIndex < NumIdealInits && 5280 "initializer not found in initializer list"); 5281 } 5282 5283 PrevInit = Init; 5284 } 5285 } 5286 5287 namespace { 5288 bool CheckRedundantInit(Sema &S, 5289 CXXCtorInitializer *Init, 5290 CXXCtorInitializer *&PrevInit) { 5291 if (!PrevInit) { 5292 PrevInit = Init; 5293 return false; 5294 } 5295 5296 if (FieldDecl *Field = Init->getAnyMember()) 5297 S.Diag(Init->getSourceLocation(), 5298 diag::err_multiple_mem_initialization) 5299 << Field->getDeclName() 5300 << Init->getSourceRange(); 5301 else { 5302 const Type *BaseClass = Init->getBaseClass(); 5303 assert(BaseClass && "neither field nor base"); 5304 S.Diag(Init->getSourceLocation(), 5305 diag::err_multiple_base_initialization) 5306 << QualType(BaseClass, 0) 5307 << Init->getSourceRange(); 5308 } 5309 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5310 << 0 << PrevInit->getSourceRange(); 5311 5312 return true; 5313 } 5314 5315 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5316 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5317 5318 bool CheckRedundantUnionInit(Sema &S, 5319 CXXCtorInitializer *Init, 5320 RedundantUnionMap &Unions) { 5321 FieldDecl *Field = Init->getAnyMember(); 5322 RecordDecl *Parent = Field->getParent(); 5323 NamedDecl *Child = Field; 5324 5325 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5326 if (Parent->isUnion()) { 5327 UnionEntry &En = Unions[Parent]; 5328 if (En.first && En.first != Child) { 5329 S.Diag(Init->getSourceLocation(), 5330 diag::err_multiple_mem_union_initialization) 5331 << Field->getDeclName() 5332 << Init->getSourceRange(); 5333 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5334 << 0 << En.second->getSourceRange(); 5335 return true; 5336 } 5337 if (!En.first) { 5338 En.first = Child; 5339 En.second = Init; 5340 } 5341 if (!Parent->isAnonymousStructOrUnion()) 5342 return false; 5343 } 5344 5345 Child = Parent; 5346 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5347 } 5348 5349 return false; 5350 } 5351 } 5352 5353 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5354 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5355 SourceLocation ColonLoc, 5356 ArrayRef<CXXCtorInitializer*> MemInits, 5357 bool AnyErrors) { 5358 if (!ConstructorDecl) 5359 return; 5360 5361 AdjustDeclIfTemplate(ConstructorDecl); 5362 5363 CXXConstructorDecl *Constructor 5364 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5365 5366 if (!Constructor) { 5367 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5368 return; 5369 } 5370 5371 // Mapping for the duplicate initializers check. 5372 // For member initializers, this is keyed with a FieldDecl*. 5373 // For base initializers, this is keyed with a Type*. 5374 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5375 5376 // Mapping for the inconsistent anonymous-union initializers check. 5377 RedundantUnionMap MemberUnions; 5378 5379 bool HadError = false; 5380 for (unsigned i = 0; i < MemInits.size(); i++) { 5381 CXXCtorInitializer *Init = MemInits[i]; 5382 5383 // Set the source order index. 5384 Init->setSourceOrder(i); 5385 5386 if (Init->isAnyMemberInitializer()) { 5387 const void *Key = GetKeyForMember(Context, Init); 5388 if (CheckRedundantInit(*this, Init, Members[Key]) || 5389 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5390 HadError = true; 5391 } else if (Init->isBaseInitializer()) { 5392 const void *Key = GetKeyForMember(Context, Init); 5393 if (CheckRedundantInit(*this, Init, Members[Key])) 5394 HadError = true; 5395 } else { 5396 assert(Init->isDelegatingInitializer()); 5397 // This must be the only initializer 5398 if (MemInits.size() != 1) { 5399 Diag(Init->getSourceLocation(), 5400 diag::err_delegating_initializer_alone) 5401 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5402 // We will treat this as being the only initializer. 5403 } 5404 SetDelegatingInitializer(Constructor, MemInits[i]); 5405 // Return immediately as the initializer is set. 5406 return; 5407 } 5408 } 5409 5410 if (HadError) 5411 return; 5412 5413 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5414 5415 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5416 5417 DiagnoseUninitializedFields(*this, Constructor); 5418 } 5419 5420 void 5421 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5422 CXXRecordDecl *ClassDecl) { 5423 // Ignore dependent contexts. Also ignore unions, since their members never 5424 // have destructors implicitly called. 5425 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5426 return; 5427 5428 // FIXME: all the access-control diagnostics are positioned on the 5429 // field/base declaration. That's probably good; that said, the 5430 // user might reasonably want to know why the destructor is being 5431 // emitted, and we currently don't say. 5432 5433 // Non-static data members. 5434 for (auto *Field : ClassDecl->fields()) { 5435 if (Field->isInvalidDecl()) 5436 continue; 5437 5438 // Don't destroy incomplete or zero-length arrays. 5439 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5440 continue; 5441 5442 QualType FieldType = Context.getBaseElementType(Field->getType()); 5443 5444 const RecordType* RT = FieldType->getAs<RecordType>(); 5445 if (!RT) 5446 continue; 5447 5448 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5449 if (FieldClassDecl->isInvalidDecl()) 5450 continue; 5451 if (FieldClassDecl->hasIrrelevantDestructor()) 5452 continue; 5453 // The destructor for an implicit anonymous union member is never invoked. 5454 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5455 continue; 5456 5457 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5458 assert(Dtor && "No dtor found for FieldClassDecl!"); 5459 CheckDestructorAccess(Field->getLocation(), Dtor, 5460 PDiag(diag::err_access_dtor_field) 5461 << Field->getDeclName() 5462 << FieldType); 5463 5464 MarkFunctionReferenced(Location, Dtor); 5465 DiagnoseUseOfDecl(Dtor, Location); 5466 } 5467 5468 // We only potentially invoke the destructors of potentially constructed 5469 // subobjects. 5470 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5471 5472 // If the destructor exists and has already been marked used in the MS ABI, 5473 // then virtual base destructors have already been checked and marked used. 5474 // Skip checking them again to avoid duplicate diagnostics. 5475 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5476 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5477 if (Dtor && Dtor->isUsed()) 5478 VisitVirtualBases = false; 5479 } 5480 5481 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5482 5483 // Bases. 5484 for (const auto &Base : ClassDecl->bases()) { 5485 // Bases are always records in a well-formed non-dependent class. 5486 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5487 5488 // Remember direct virtual bases. 5489 if (Base.isVirtual()) { 5490 if (!VisitVirtualBases) 5491 continue; 5492 DirectVirtualBases.insert(RT); 5493 } 5494 5495 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5496 // If our base class is invalid, we probably can't get its dtor anyway. 5497 if (BaseClassDecl->isInvalidDecl()) 5498 continue; 5499 if (BaseClassDecl->hasIrrelevantDestructor()) 5500 continue; 5501 5502 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5503 assert(Dtor && "No dtor found for BaseClassDecl!"); 5504 5505 // FIXME: caret should be on the start of the class name 5506 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5507 PDiag(diag::err_access_dtor_base) 5508 << Base.getType() << Base.getSourceRange(), 5509 Context.getTypeDeclType(ClassDecl)); 5510 5511 MarkFunctionReferenced(Location, Dtor); 5512 DiagnoseUseOfDecl(Dtor, Location); 5513 } 5514 5515 if (VisitVirtualBases) 5516 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5517 &DirectVirtualBases); 5518 } 5519 5520 void Sema::MarkVirtualBaseDestructorsReferenced( 5521 SourceLocation Location, CXXRecordDecl *ClassDecl, 5522 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5523 // Virtual bases. 5524 for (const auto &VBase : ClassDecl->vbases()) { 5525 // Bases are always records in a well-formed non-dependent class. 5526 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5527 5528 // Ignore already visited direct virtual bases. 5529 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5530 continue; 5531 5532 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5533 // If our base class is invalid, we probably can't get its dtor anyway. 5534 if (BaseClassDecl->isInvalidDecl()) 5535 continue; 5536 if (BaseClassDecl->hasIrrelevantDestructor()) 5537 continue; 5538 5539 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5540 assert(Dtor && "No dtor found for BaseClassDecl!"); 5541 if (CheckDestructorAccess( 5542 ClassDecl->getLocation(), Dtor, 5543 PDiag(diag::err_access_dtor_vbase) 5544 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5545 Context.getTypeDeclType(ClassDecl)) == 5546 AR_accessible) { 5547 CheckDerivedToBaseConversion( 5548 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5549 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5550 SourceRange(), DeclarationName(), nullptr); 5551 } 5552 5553 MarkFunctionReferenced(Location, Dtor); 5554 DiagnoseUseOfDecl(Dtor, Location); 5555 } 5556 } 5557 5558 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5559 if (!CDtorDecl) 5560 return; 5561 5562 if (CXXConstructorDecl *Constructor 5563 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5564 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5565 DiagnoseUninitializedFields(*this, Constructor); 5566 } 5567 } 5568 5569 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5570 if (!getLangOpts().CPlusPlus) 5571 return false; 5572 5573 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5574 if (!RD) 5575 return false; 5576 5577 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5578 // class template specialization here, but doing so breaks a lot of code. 5579 5580 // We can't answer whether something is abstract until it has a 5581 // definition. If it's currently being defined, we'll walk back 5582 // over all the declarations when we have a full definition. 5583 const CXXRecordDecl *Def = RD->getDefinition(); 5584 if (!Def || Def->isBeingDefined()) 5585 return false; 5586 5587 return RD->isAbstract(); 5588 } 5589 5590 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5591 TypeDiagnoser &Diagnoser) { 5592 if (!isAbstractType(Loc, T)) 5593 return false; 5594 5595 T = Context.getBaseElementType(T); 5596 Diagnoser.diagnose(*this, Loc, T); 5597 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5598 return true; 5599 } 5600 5601 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5602 // Check if we've already emitted the list of pure virtual functions 5603 // for this class. 5604 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5605 return; 5606 5607 // If the diagnostic is suppressed, don't emit the notes. We're only 5608 // going to emit them once, so try to attach them to a diagnostic we're 5609 // actually going to show. 5610 if (Diags.isLastDiagnosticIgnored()) 5611 return; 5612 5613 CXXFinalOverriderMap FinalOverriders; 5614 RD->getFinalOverriders(FinalOverriders); 5615 5616 // Keep a set of seen pure methods so we won't diagnose the same method 5617 // more than once. 5618 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5619 5620 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5621 MEnd = FinalOverriders.end(); 5622 M != MEnd; 5623 ++M) { 5624 for (OverridingMethods::iterator SO = M->second.begin(), 5625 SOEnd = M->second.end(); 5626 SO != SOEnd; ++SO) { 5627 // C++ [class.abstract]p4: 5628 // A class is abstract if it contains or inherits at least one 5629 // pure virtual function for which the final overrider is pure 5630 // virtual. 5631 5632 // 5633 if (SO->second.size() != 1) 5634 continue; 5635 5636 if (!SO->second.front().Method->isPure()) 5637 continue; 5638 5639 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5640 continue; 5641 5642 Diag(SO->second.front().Method->getLocation(), 5643 diag::note_pure_virtual_function) 5644 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5645 } 5646 } 5647 5648 if (!PureVirtualClassDiagSet) 5649 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5650 PureVirtualClassDiagSet->insert(RD); 5651 } 5652 5653 namespace { 5654 struct AbstractUsageInfo { 5655 Sema &S; 5656 CXXRecordDecl *Record; 5657 CanQualType AbstractType; 5658 bool Invalid; 5659 5660 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5661 : S(S), Record(Record), 5662 AbstractType(S.Context.getCanonicalType( 5663 S.Context.getTypeDeclType(Record))), 5664 Invalid(false) {} 5665 5666 void DiagnoseAbstractType() { 5667 if (Invalid) return; 5668 S.DiagnoseAbstractType(Record); 5669 Invalid = true; 5670 } 5671 5672 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5673 }; 5674 5675 struct CheckAbstractUsage { 5676 AbstractUsageInfo &Info; 5677 const NamedDecl *Ctx; 5678 5679 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5680 : Info(Info), Ctx(Ctx) {} 5681 5682 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5683 switch (TL.getTypeLocClass()) { 5684 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5685 #define TYPELOC(CLASS, PARENT) \ 5686 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5687 #include "clang/AST/TypeLocNodes.def" 5688 } 5689 } 5690 5691 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5692 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5693 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5694 if (!TL.getParam(I)) 5695 continue; 5696 5697 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5698 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5699 } 5700 } 5701 5702 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5703 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5704 } 5705 5706 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5707 // Visit the type parameters from a permissive context. 5708 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5709 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5710 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5711 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5712 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5713 // TODO: other template argument types? 5714 } 5715 } 5716 5717 // Visit pointee types from a permissive context. 5718 #define CheckPolymorphic(Type) \ 5719 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5720 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5721 } 5722 CheckPolymorphic(PointerTypeLoc) 5723 CheckPolymorphic(ReferenceTypeLoc) 5724 CheckPolymorphic(MemberPointerTypeLoc) 5725 CheckPolymorphic(BlockPointerTypeLoc) 5726 CheckPolymorphic(AtomicTypeLoc) 5727 5728 /// Handle all the types we haven't given a more specific 5729 /// implementation for above. 5730 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5731 // Every other kind of type that we haven't called out already 5732 // that has an inner type is either (1) sugar or (2) contains that 5733 // inner type in some way as a subobject. 5734 if (TypeLoc Next = TL.getNextTypeLoc()) 5735 return Visit(Next, Sel); 5736 5737 // If there's no inner type and we're in a permissive context, 5738 // don't diagnose. 5739 if (Sel == Sema::AbstractNone) return; 5740 5741 // Check whether the type matches the abstract type. 5742 QualType T = TL.getType(); 5743 if (T->isArrayType()) { 5744 Sel = Sema::AbstractArrayType; 5745 T = Info.S.Context.getBaseElementType(T); 5746 } 5747 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5748 if (CT != Info.AbstractType) return; 5749 5750 // It matched; do some magic. 5751 if (Sel == Sema::AbstractArrayType) { 5752 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5753 << T << TL.getSourceRange(); 5754 } else { 5755 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5756 << Sel << T << TL.getSourceRange(); 5757 } 5758 Info.DiagnoseAbstractType(); 5759 } 5760 }; 5761 5762 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5763 Sema::AbstractDiagSelID Sel) { 5764 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5765 } 5766 5767 } 5768 5769 /// Check for invalid uses of an abstract type in a method declaration. 5770 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5771 CXXMethodDecl *MD) { 5772 // No need to do the check on definitions, which require that 5773 // the return/param types be complete. 5774 if (MD->doesThisDeclarationHaveABody()) 5775 return; 5776 5777 // For safety's sake, just ignore it if we don't have type source 5778 // information. This should never happen for non-implicit methods, 5779 // but... 5780 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5781 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5782 } 5783 5784 /// Check for invalid uses of an abstract type within a class definition. 5785 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5786 CXXRecordDecl *RD) { 5787 for (auto *D : RD->decls()) { 5788 if (D->isImplicit()) continue; 5789 5790 // Methods and method templates. 5791 if (isa<CXXMethodDecl>(D)) { 5792 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5793 } else if (isa<FunctionTemplateDecl>(D)) { 5794 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5795 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5796 5797 // Fields and static variables. 5798 } else if (isa<FieldDecl>(D)) { 5799 FieldDecl *FD = cast<FieldDecl>(D); 5800 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5801 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5802 } else if (isa<VarDecl>(D)) { 5803 VarDecl *VD = cast<VarDecl>(D); 5804 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5805 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5806 5807 // Nested classes and class templates. 5808 } else if (isa<CXXRecordDecl>(D)) { 5809 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5810 } else if (isa<ClassTemplateDecl>(D)) { 5811 CheckAbstractClassUsage(Info, 5812 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5813 } 5814 } 5815 } 5816 5817 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5818 Attr *ClassAttr = getDLLAttr(Class); 5819 if (!ClassAttr) 5820 return; 5821 5822 assert(ClassAttr->getKind() == attr::DLLExport); 5823 5824 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5825 5826 if (TSK == TSK_ExplicitInstantiationDeclaration) 5827 // Don't go any further if this is just an explicit instantiation 5828 // declaration. 5829 return; 5830 5831 // Add a context note to explain how we got to any diagnostics produced below. 5832 struct MarkingClassDllexported { 5833 Sema &S; 5834 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5835 SourceLocation AttrLoc) 5836 : S(S) { 5837 Sema::CodeSynthesisContext Ctx; 5838 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5839 Ctx.PointOfInstantiation = AttrLoc; 5840 Ctx.Entity = Class; 5841 S.pushCodeSynthesisContext(Ctx); 5842 } 5843 ~MarkingClassDllexported() { 5844 S.popCodeSynthesisContext(); 5845 } 5846 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5847 5848 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5849 S.MarkVTableUsed(Class->getLocation(), Class, true); 5850 5851 for (Decl *Member : Class->decls()) { 5852 // Defined static variables that are members of an exported base 5853 // class must be marked export too. 5854 auto *VD = dyn_cast<VarDecl>(Member); 5855 if (VD && Member->getAttr<DLLExportAttr>() && 5856 VD->getStorageClass() == SC_Static && 5857 TSK == TSK_ImplicitInstantiation) 5858 S.MarkVariableReferenced(VD->getLocation(), VD); 5859 5860 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5861 if (!MD) 5862 continue; 5863 5864 if (Member->getAttr<DLLExportAttr>()) { 5865 if (MD->isUserProvided()) { 5866 // Instantiate non-default class member functions ... 5867 5868 // .. except for certain kinds of template specializations. 5869 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5870 continue; 5871 5872 S.MarkFunctionReferenced(Class->getLocation(), MD); 5873 5874 // The function will be passed to the consumer when its definition is 5875 // encountered. 5876 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5877 MD->isCopyAssignmentOperator() || 5878 MD->isMoveAssignmentOperator()) { 5879 // Synthesize and instantiate non-trivial implicit methods, explicitly 5880 // defaulted methods, and the copy and move assignment operators. The 5881 // latter are exported even if they are trivial, because the address of 5882 // an operator can be taken and should compare equal across libraries. 5883 S.MarkFunctionReferenced(Class->getLocation(), MD); 5884 5885 // There is no later point when we will see the definition of this 5886 // function, so pass it to the consumer now. 5887 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5888 } 5889 } 5890 } 5891 } 5892 5893 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5894 CXXRecordDecl *Class) { 5895 // Only the MS ABI has default constructor closures, so we don't need to do 5896 // this semantic checking anywhere else. 5897 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5898 return; 5899 5900 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5901 for (Decl *Member : Class->decls()) { 5902 // Look for exported default constructors. 5903 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5904 if (!CD || !CD->isDefaultConstructor()) 5905 continue; 5906 auto *Attr = CD->getAttr<DLLExportAttr>(); 5907 if (!Attr) 5908 continue; 5909 5910 // If the class is non-dependent, mark the default arguments as ODR-used so 5911 // that we can properly codegen the constructor closure. 5912 if (!Class->isDependentContext()) { 5913 for (ParmVarDecl *PD : CD->parameters()) { 5914 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5915 S.DiscardCleanupsInEvaluationContext(); 5916 } 5917 } 5918 5919 if (LastExportedDefaultCtor) { 5920 S.Diag(LastExportedDefaultCtor->getLocation(), 5921 diag::err_attribute_dll_ambiguous_default_ctor) 5922 << Class; 5923 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5924 << CD->getDeclName(); 5925 return; 5926 } 5927 LastExportedDefaultCtor = CD; 5928 } 5929 } 5930 5931 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5932 CXXRecordDecl *Class) { 5933 bool ErrorReported = false; 5934 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5935 ClassTemplateDecl *TD) { 5936 if (ErrorReported) 5937 return; 5938 S.Diag(TD->getLocation(), 5939 diag::err_cuda_device_builtin_surftex_cls_template) 5940 << /*surface*/ 0 << TD; 5941 ErrorReported = true; 5942 }; 5943 5944 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5945 if (!TD) { 5946 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5947 if (!SD) { 5948 S.Diag(Class->getLocation(), 5949 diag::err_cuda_device_builtin_surftex_ref_decl) 5950 << /*surface*/ 0 << Class; 5951 S.Diag(Class->getLocation(), 5952 diag::note_cuda_device_builtin_surftex_should_be_template_class) 5953 << Class; 5954 return; 5955 } 5956 TD = SD->getSpecializedTemplate(); 5957 } 5958 5959 TemplateParameterList *Params = TD->getTemplateParameters(); 5960 unsigned N = Params->size(); 5961 5962 if (N != 2) { 5963 reportIllegalClassTemplate(S, TD); 5964 S.Diag(TD->getLocation(), 5965 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 5966 << TD << 2; 5967 } 5968 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5969 reportIllegalClassTemplate(S, TD); 5970 S.Diag(TD->getLocation(), 5971 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5972 << TD << /*1st*/ 0 << /*type*/ 0; 5973 } 5974 if (N > 1) { 5975 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 5976 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 5977 reportIllegalClassTemplate(S, TD); 5978 S.Diag(TD->getLocation(), 5979 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5980 << TD << /*2nd*/ 1 << /*integer*/ 1; 5981 } 5982 } 5983 } 5984 5985 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 5986 CXXRecordDecl *Class) { 5987 bool ErrorReported = false; 5988 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5989 ClassTemplateDecl *TD) { 5990 if (ErrorReported) 5991 return; 5992 S.Diag(TD->getLocation(), 5993 diag::err_cuda_device_builtin_surftex_cls_template) 5994 << /*texture*/ 1 << TD; 5995 ErrorReported = true; 5996 }; 5997 5998 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5999 if (!TD) { 6000 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6001 if (!SD) { 6002 S.Diag(Class->getLocation(), 6003 diag::err_cuda_device_builtin_surftex_ref_decl) 6004 << /*texture*/ 1 << Class; 6005 S.Diag(Class->getLocation(), 6006 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6007 << Class; 6008 return; 6009 } 6010 TD = SD->getSpecializedTemplate(); 6011 } 6012 6013 TemplateParameterList *Params = TD->getTemplateParameters(); 6014 unsigned N = Params->size(); 6015 6016 if (N != 3) { 6017 reportIllegalClassTemplate(S, TD); 6018 S.Diag(TD->getLocation(), 6019 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6020 << TD << 3; 6021 } 6022 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6023 reportIllegalClassTemplate(S, TD); 6024 S.Diag(TD->getLocation(), 6025 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6026 << TD << /*1st*/ 0 << /*type*/ 0; 6027 } 6028 if (N > 1) { 6029 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6030 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6031 reportIllegalClassTemplate(S, TD); 6032 S.Diag(TD->getLocation(), 6033 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6034 << TD << /*2nd*/ 1 << /*integer*/ 1; 6035 } 6036 } 6037 if (N > 2) { 6038 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6039 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6040 reportIllegalClassTemplate(S, TD); 6041 S.Diag(TD->getLocation(), 6042 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6043 << TD << /*3rd*/ 2 << /*integer*/ 1; 6044 } 6045 } 6046 } 6047 6048 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6049 // Mark any compiler-generated routines with the implicit code_seg attribute. 6050 for (auto *Method : Class->methods()) { 6051 if (Method->isUserProvided()) 6052 continue; 6053 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6054 Method->addAttr(A); 6055 } 6056 } 6057 6058 /// Check class-level dllimport/dllexport attribute. 6059 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6060 Attr *ClassAttr = getDLLAttr(Class); 6061 6062 // MSVC inherits DLL attributes to partial class template specializations. 6063 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 6064 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6065 if (Attr *TemplateAttr = 6066 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6067 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6068 A->setInherited(true); 6069 ClassAttr = A; 6070 } 6071 } 6072 } 6073 6074 if (!ClassAttr) 6075 return; 6076 6077 if (!Class->isExternallyVisible()) { 6078 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6079 << Class << ClassAttr; 6080 return; 6081 } 6082 6083 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 6084 !ClassAttr->isInherited()) { 6085 // Diagnose dll attributes on members of class with dll attribute. 6086 for (Decl *Member : Class->decls()) { 6087 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6088 continue; 6089 InheritableAttr *MemberAttr = getDLLAttr(Member); 6090 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6091 continue; 6092 6093 Diag(MemberAttr->getLocation(), 6094 diag::err_attribute_dll_member_of_dll_class) 6095 << MemberAttr << ClassAttr; 6096 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6097 Member->setInvalidDecl(); 6098 } 6099 } 6100 6101 if (Class->getDescribedClassTemplate()) 6102 // Don't inherit dll attribute until the template is instantiated. 6103 return; 6104 6105 // The class is either imported or exported. 6106 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6107 6108 // Check if this was a dllimport attribute propagated from a derived class to 6109 // a base class template specialization. We don't apply these attributes to 6110 // static data members. 6111 const bool PropagatedImport = 6112 !ClassExported && 6113 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6114 6115 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6116 6117 // Ignore explicit dllexport on explicit class template instantiation 6118 // declarations, except in MinGW mode. 6119 if (ClassExported && !ClassAttr->isInherited() && 6120 TSK == TSK_ExplicitInstantiationDeclaration && 6121 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6122 Class->dropAttr<DLLExportAttr>(); 6123 return; 6124 } 6125 6126 // Force declaration of implicit members so they can inherit the attribute. 6127 ForceDeclarationOfImplicitMembers(Class); 6128 6129 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6130 // seem to be true in practice? 6131 6132 for (Decl *Member : Class->decls()) { 6133 VarDecl *VD = dyn_cast<VarDecl>(Member); 6134 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6135 6136 // Only methods and static fields inherit the attributes. 6137 if (!VD && !MD) 6138 continue; 6139 6140 if (MD) { 6141 // Don't process deleted methods. 6142 if (MD->isDeleted()) 6143 continue; 6144 6145 if (MD->isInlined()) { 6146 // MinGW does not import or export inline methods. But do it for 6147 // template instantiations. 6148 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 6149 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 6150 TSK != TSK_ExplicitInstantiationDeclaration && 6151 TSK != TSK_ExplicitInstantiationDefinition) 6152 continue; 6153 6154 // MSVC versions before 2015 don't export the move assignment operators 6155 // and move constructor, so don't attempt to import/export them if 6156 // we have a definition. 6157 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6158 if ((MD->isMoveAssignmentOperator() || 6159 (Ctor && Ctor->isMoveConstructor())) && 6160 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6161 continue; 6162 6163 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6164 // operator is exported anyway. 6165 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6166 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6167 continue; 6168 } 6169 } 6170 6171 // Don't apply dllimport attributes to static data members of class template 6172 // instantiations when the attribute is propagated from a derived class. 6173 if (VD && PropagatedImport) 6174 continue; 6175 6176 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6177 continue; 6178 6179 if (!getDLLAttr(Member)) { 6180 InheritableAttr *NewAttr = nullptr; 6181 6182 // Do not export/import inline function when -fno-dllexport-inlines is 6183 // passed. But add attribute for later local static var check. 6184 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6185 TSK != TSK_ExplicitInstantiationDeclaration && 6186 TSK != TSK_ExplicitInstantiationDefinition) { 6187 if (ClassExported) { 6188 NewAttr = ::new (getASTContext()) 6189 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6190 } else { 6191 NewAttr = ::new (getASTContext()) 6192 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6193 } 6194 } else { 6195 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6196 } 6197 6198 NewAttr->setInherited(true); 6199 Member->addAttr(NewAttr); 6200 6201 if (MD) { 6202 // Propagate DLLAttr to friend re-declarations of MD that have already 6203 // been constructed. 6204 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6205 FD = FD->getPreviousDecl()) { 6206 if (FD->getFriendObjectKind() == Decl::FOK_None) 6207 continue; 6208 assert(!getDLLAttr(FD) && 6209 "friend re-decl should not already have a DLLAttr"); 6210 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6211 NewAttr->setInherited(true); 6212 FD->addAttr(NewAttr); 6213 } 6214 } 6215 } 6216 } 6217 6218 if (ClassExported) 6219 DelayedDllExportClasses.push_back(Class); 6220 } 6221 6222 /// Perform propagation of DLL attributes from a derived class to a 6223 /// templated base class for MS compatibility. 6224 void Sema::propagateDLLAttrToBaseClassTemplate( 6225 CXXRecordDecl *Class, Attr *ClassAttr, 6226 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6227 if (getDLLAttr( 6228 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6229 // If the base class template has a DLL attribute, don't try to change it. 6230 return; 6231 } 6232 6233 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6234 if (!getDLLAttr(BaseTemplateSpec) && 6235 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6236 TSK == TSK_ImplicitInstantiation)) { 6237 // The template hasn't been instantiated yet (or it has, but only as an 6238 // explicit instantiation declaration or implicit instantiation, which means 6239 // we haven't codegenned any members yet), so propagate the attribute. 6240 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6241 NewAttr->setInherited(true); 6242 BaseTemplateSpec->addAttr(NewAttr); 6243 6244 // If this was an import, mark that we propagated it from a derived class to 6245 // a base class template specialization. 6246 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6247 ImportAttr->setPropagatedToBaseTemplate(); 6248 6249 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6250 // needs to be run again to work see the new attribute. Otherwise this will 6251 // get run whenever the template is instantiated. 6252 if (TSK != TSK_Undeclared) 6253 checkClassLevelDLLAttribute(BaseTemplateSpec); 6254 6255 return; 6256 } 6257 6258 if (getDLLAttr(BaseTemplateSpec)) { 6259 // The template has already been specialized or instantiated with an 6260 // attribute, explicitly or through propagation. We should not try to change 6261 // it. 6262 return; 6263 } 6264 6265 // The template was previously instantiated or explicitly specialized without 6266 // a dll attribute, It's too late for us to add an attribute, so warn that 6267 // this is unsupported. 6268 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6269 << BaseTemplateSpec->isExplicitSpecialization(); 6270 Diag(ClassAttr->getLocation(), diag::note_attribute); 6271 if (BaseTemplateSpec->isExplicitSpecialization()) { 6272 Diag(BaseTemplateSpec->getLocation(), 6273 diag::note_template_class_explicit_specialization_was_here) 6274 << BaseTemplateSpec; 6275 } else { 6276 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6277 diag::note_template_class_instantiation_was_here) 6278 << BaseTemplateSpec; 6279 } 6280 } 6281 6282 /// Determine the kind of defaulting that would be done for a given function. 6283 /// 6284 /// If the function is both a default constructor and a copy / move constructor 6285 /// (due to having a default argument for the first parameter), this picks 6286 /// CXXDefaultConstructor. 6287 /// 6288 /// FIXME: Check that case is properly handled by all callers. 6289 Sema::DefaultedFunctionKind 6290 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6291 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6292 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6293 if (Ctor->isDefaultConstructor()) 6294 return Sema::CXXDefaultConstructor; 6295 6296 if (Ctor->isCopyConstructor()) 6297 return Sema::CXXCopyConstructor; 6298 6299 if (Ctor->isMoveConstructor()) 6300 return Sema::CXXMoveConstructor; 6301 } 6302 6303 if (MD->isCopyAssignmentOperator()) 6304 return Sema::CXXCopyAssignment; 6305 6306 if (MD->isMoveAssignmentOperator()) 6307 return Sema::CXXMoveAssignment; 6308 6309 if (isa<CXXDestructorDecl>(FD)) 6310 return Sema::CXXDestructor; 6311 } 6312 6313 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6314 case OO_EqualEqual: 6315 return DefaultedComparisonKind::Equal; 6316 6317 case OO_ExclaimEqual: 6318 return DefaultedComparisonKind::NotEqual; 6319 6320 case OO_Spaceship: 6321 // No point allowing this if <=> doesn't exist in the current language mode. 6322 if (!getLangOpts().CPlusPlus20) 6323 break; 6324 return DefaultedComparisonKind::ThreeWay; 6325 6326 case OO_Less: 6327 case OO_LessEqual: 6328 case OO_Greater: 6329 case OO_GreaterEqual: 6330 // No point allowing this if <=> doesn't exist in the current language mode. 6331 if (!getLangOpts().CPlusPlus20) 6332 break; 6333 return DefaultedComparisonKind::Relational; 6334 6335 default: 6336 break; 6337 } 6338 6339 // Not defaultable. 6340 return DefaultedFunctionKind(); 6341 } 6342 6343 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6344 SourceLocation DefaultLoc) { 6345 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6346 if (DFK.isComparison()) 6347 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6348 6349 switch (DFK.asSpecialMember()) { 6350 case Sema::CXXDefaultConstructor: 6351 S.DefineImplicitDefaultConstructor(DefaultLoc, 6352 cast<CXXConstructorDecl>(FD)); 6353 break; 6354 case Sema::CXXCopyConstructor: 6355 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6356 break; 6357 case Sema::CXXCopyAssignment: 6358 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6359 break; 6360 case Sema::CXXDestructor: 6361 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6362 break; 6363 case Sema::CXXMoveConstructor: 6364 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6365 break; 6366 case Sema::CXXMoveAssignment: 6367 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6368 break; 6369 case Sema::CXXInvalid: 6370 llvm_unreachable("Invalid special member."); 6371 } 6372 } 6373 6374 /// Determine whether a type is permitted to be passed or returned in 6375 /// registers, per C++ [class.temporary]p3. 6376 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6377 TargetInfo::CallingConvKind CCK) { 6378 if (D->isDependentType() || D->isInvalidDecl()) 6379 return false; 6380 6381 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6382 // The PS4 platform ABI follows the behavior of Clang 3.2. 6383 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6384 return !D->hasNonTrivialDestructorForCall() && 6385 !D->hasNonTrivialCopyConstructorForCall(); 6386 6387 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6388 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6389 bool DtorIsTrivialForCall = false; 6390 6391 // If a class has at least one non-deleted, trivial copy constructor, it 6392 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6393 // 6394 // Note: This permits classes with non-trivial copy or move ctors to be 6395 // passed in registers, so long as they *also* have a trivial copy ctor, 6396 // which is non-conforming. 6397 if (D->needsImplicitCopyConstructor()) { 6398 if (!D->defaultedCopyConstructorIsDeleted()) { 6399 if (D->hasTrivialCopyConstructor()) 6400 CopyCtorIsTrivial = true; 6401 if (D->hasTrivialCopyConstructorForCall()) 6402 CopyCtorIsTrivialForCall = true; 6403 } 6404 } else { 6405 for (const CXXConstructorDecl *CD : D->ctors()) { 6406 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6407 if (CD->isTrivial()) 6408 CopyCtorIsTrivial = true; 6409 if (CD->isTrivialForCall()) 6410 CopyCtorIsTrivialForCall = true; 6411 } 6412 } 6413 } 6414 6415 if (D->needsImplicitDestructor()) { 6416 if (!D->defaultedDestructorIsDeleted() && 6417 D->hasTrivialDestructorForCall()) 6418 DtorIsTrivialForCall = true; 6419 } else if (const auto *DD = D->getDestructor()) { 6420 if (!DD->isDeleted() && DD->isTrivialForCall()) 6421 DtorIsTrivialForCall = true; 6422 } 6423 6424 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6425 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6426 return true; 6427 6428 // If a class has a destructor, we'd really like to pass it indirectly 6429 // because it allows us to elide copies. Unfortunately, MSVC makes that 6430 // impossible for small types, which it will pass in a single register or 6431 // stack slot. Most objects with dtors are large-ish, so handle that early. 6432 // We can't call out all large objects as being indirect because there are 6433 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6434 // how we pass large POD types. 6435 6436 // Note: This permits small classes with nontrivial destructors to be 6437 // passed in registers, which is non-conforming. 6438 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6439 uint64_t TypeSize = isAArch64 ? 128 : 64; 6440 6441 if (CopyCtorIsTrivial && 6442 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6443 return true; 6444 return false; 6445 } 6446 6447 // Per C++ [class.temporary]p3, the relevant condition is: 6448 // each copy constructor, move constructor, and destructor of X is 6449 // either trivial or deleted, and X has at least one non-deleted copy 6450 // or move constructor 6451 bool HasNonDeletedCopyOrMove = false; 6452 6453 if (D->needsImplicitCopyConstructor() && 6454 !D->defaultedCopyConstructorIsDeleted()) { 6455 if (!D->hasTrivialCopyConstructorForCall()) 6456 return false; 6457 HasNonDeletedCopyOrMove = true; 6458 } 6459 6460 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6461 !D->defaultedMoveConstructorIsDeleted()) { 6462 if (!D->hasTrivialMoveConstructorForCall()) 6463 return false; 6464 HasNonDeletedCopyOrMove = true; 6465 } 6466 6467 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6468 !D->hasTrivialDestructorForCall()) 6469 return false; 6470 6471 for (const CXXMethodDecl *MD : D->methods()) { 6472 if (MD->isDeleted()) 6473 continue; 6474 6475 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6476 if (CD && CD->isCopyOrMoveConstructor()) 6477 HasNonDeletedCopyOrMove = true; 6478 else if (!isa<CXXDestructorDecl>(MD)) 6479 continue; 6480 6481 if (!MD->isTrivialForCall()) 6482 return false; 6483 } 6484 6485 return HasNonDeletedCopyOrMove; 6486 } 6487 6488 /// Report an error regarding overriding, along with any relevant 6489 /// overridden methods. 6490 /// 6491 /// \param DiagID the primary error to report. 6492 /// \param MD the overriding method. 6493 static bool 6494 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6495 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6496 bool IssuedDiagnostic = false; 6497 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6498 if (Report(O)) { 6499 if (!IssuedDiagnostic) { 6500 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6501 IssuedDiagnostic = true; 6502 } 6503 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6504 } 6505 } 6506 return IssuedDiagnostic; 6507 } 6508 6509 /// Perform semantic checks on a class definition that has been 6510 /// completing, introducing implicitly-declared members, checking for 6511 /// abstract types, etc. 6512 /// 6513 /// \param S The scope in which the class was parsed. Null if we didn't just 6514 /// parse a class definition. 6515 /// \param Record The completed class. 6516 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6517 if (!Record) 6518 return; 6519 6520 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6521 AbstractUsageInfo Info(*this, Record); 6522 CheckAbstractClassUsage(Info, Record); 6523 } 6524 6525 // If this is not an aggregate type and has no user-declared constructor, 6526 // complain about any non-static data members of reference or const scalar 6527 // type, since they will never get initializers. 6528 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6529 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6530 !Record->isLambda()) { 6531 bool Complained = false; 6532 for (const auto *F : Record->fields()) { 6533 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6534 continue; 6535 6536 if (F->getType()->isReferenceType() || 6537 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6538 if (!Complained) { 6539 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6540 << Record->getTagKind() << Record; 6541 Complained = true; 6542 } 6543 6544 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6545 << F->getType()->isReferenceType() 6546 << F->getDeclName(); 6547 } 6548 } 6549 } 6550 6551 if (Record->getIdentifier()) { 6552 // C++ [class.mem]p13: 6553 // If T is the name of a class, then each of the following shall have a 6554 // name different from T: 6555 // - every member of every anonymous union that is a member of class T. 6556 // 6557 // C++ [class.mem]p14: 6558 // In addition, if class T has a user-declared constructor (12.1), every 6559 // non-static data member of class T shall have a name different from T. 6560 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6561 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6562 ++I) { 6563 NamedDecl *D = (*I)->getUnderlyingDecl(); 6564 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6565 Record->hasUserDeclaredConstructor()) || 6566 isa<IndirectFieldDecl>(D)) { 6567 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6568 << D->getDeclName(); 6569 break; 6570 } 6571 } 6572 } 6573 6574 // Warn if the class has virtual methods but non-virtual public destructor. 6575 if (Record->isPolymorphic() && !Record->isDependentType()) { 6576 CXXDestructorDecl *dtor = Record->getDestructor(); 6577 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6578 !Record->hasAttr<FinalAttr>()) 6579 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6580 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6581 } 6582 6583 if (Record->isAbstract()) { 6584 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6585 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6586 << FA->isSpelledAsSealed(); 6587 DiagnoseAbstractType(Record); 6588 } 6589 } 6590 6591 // Warn if the class has a final destructor but is not itself marked final. 6592 if (!Record->hasAttr<FinalAttr>()) { 6593 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6594 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6595 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6596 << FA->isSpelledAsSealed() 6597 << FixItHint::CreateInsertion( 6598 getLocForEndOfToken(Record->getLocation()), 6599 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6600 Diag(Record->getLocation(), 6601 diag::note_final_dtor_non_final_class_silence) 6602 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6603 } 6604 } 6605 } 6606 6607 // See if trivial_abi has to be dropped. 6608 if (Record->hasAttr<TrivialABIAttr>()) 6609 checkIllFormedTrivialABIStruct(*Record); 6610 6611 // Set HasTrivialSpecialMemberForCall if the record has attribute 6612 // "trivial_abi". 6613 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6614 6615 if (HasTrivialABI) 6616 Record->setHasTrivialSpecialMemberForCall(); 6617 6618 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6619 // We check these last because they can depend on the properties of the 6620 // primary comparison functions (==, <=>). 6621 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6622 6623 // Perform checks that can't be done until we know all the properties of a 6624 // member function (whether it's defaulted, deleted, virtual, overriding, 6625 // ...). 6626 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6627 // A static function cannot override anything. 6628 if (MD->getStorageClass() == SC_Static) { 6629 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6630 [](const CXXMethodDecl *) { return true; })) 6631 return; 6632 } 6633 6634 // A deleted function cannot override a non-deleted function and vice 6635 // versa. 6636 if (ReportOverrides(*this, 6637 MD->isDeleted() ? diag::err_deleted_override 6638 : diag::err_non_deleted_override, 6639 MD, [&](const CXXMethodDecl *V) { 6640 return MD->isDeleted() != V->isDeleted(); 6641 })) { 6642 if (MD->isDefaulted() && MD->isDeleted()) 6643 // Explain why this defaulted function was deleted. 6644 DiagnoseDeletedDefaultedFunction(MD); 6645 return; 6646 } 6647 6648 // A consteval function cannot override a non-consteval function and vice 6649 // versa. 6650 if (ReportOverrides(*this, 6651 MD->isConsteval() ? diag::err_consteval_override 6652 : diag::err_non_consteval_override, 6653 MD, [&](const CXXMethodDecl *V) { 6654 return MD->isConsteval() != V->isConsteval(); 6655 })) { 6656 if (MD->isDefaulted() && MD->isDeleted()) 6657 // Explain why this defaulted function was deleted. 6658 DiagnoseDeletedDefaultedFunction(MD); 6659 return; 6660 } 6661 }; 6662 6663 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6664 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6665 return false; 6666 6667 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6668 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6669 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6670 DefaultedSecondaryComparisons.push_back(FD); 6671 return true; 6672 } 6673 6674 CheckExplicitlyDefaultedFunction(S, FD); 6675 return false; 6676 }; 6677 6678 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6679 // Check whether the explicitly-defaulted members are valid. 6680 bool Incomplete = CheckForDefaultedFunction(M); 6681 6682 // Skip the rest of the checks for a member of a dependent class. 6683 if (Record->isDependentType()) 6684 return; 6685 6686 // For an explicitly defaulted or deleted special member, we defer 6687 // determining triviality until the class is complete. That time is now! 6688 CXXSpecialMember CSM = getSpecialMember(M); 6689 if (!M->isImplicit() && !M->isUserProvided()) { 6690 if (CSM != CXXInvalid) { 6691 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6692 // Inform the class that we've finished declaring this member. 6693 Record->finishedDefaultedOrDeletedMember(M); 6694 M->setTrivialForCall( 6695 HasTrivialABI || 6696 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6697 Record->setTrivialForCallFlags(M); 6698 } 6699 } 6700 6701 // Set triviality for the purpose of calls if this is a user-provided 6702 // copy/move constructor or destructor. 6703 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6704 CSM == CXXDestructor) && M->isUserProvided()) { 6705 M->setTrivialForCall(HasTrivialABI); 6706 Record->setTrivialForCallFlags(M); 6707 } 6708 6709 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6710 M->hasAttr<DLLExportAttr>()) { 6711 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6712 M->isTrivial() && 6713 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6714 CSM == CXXDestructor)) 6715 M->dropAttr<DLLExportAttr>(); 6716 6717 if (M->hasAttr<DLLExportAttr>()) { 6718 // Define after any fields with in-class initializers have been parsed. 6719 DelayedDllExportMemberFunctions.push_back(M); 6720 } 6721 } 6722 6723 // Define defaulted constexpr virtual functions that override a base class 6724 // function right away. 6725 // FIXME: We can defer doing this until the vtable is marked as used. 6726 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6727 DefineDefaultedFunction(*this, M, M->getLocation()); 6728 6729 if (!Incomplete) 6730 CheckCompletedMemberFunction(M); 6731 }; 6732 6733 // Check the destructor before any other member function. We need to 6734 // determine whether it's trivial in order to determine whether the claas 6735 // type is a literal type, which is a prerequisite for determining whether 6736 // other special member functions are valid and whether they're implicitly 6737 // 'constexpr'. 6738 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6739 CompleteMemberFunction(Dtor); 6740 6741 bool HasMethodWithOverrideControl = false, 6742 HasOverridingMethodWithoutOverrideControl = false; 6743 for (auto *D : Record->decls()) { 6744 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6745 // FIXME: We could do this check for dependent types with non-dependent 6746 // bases. 6747 if (!Record->isDependentType()) { 6748 // See if a method overloads virtual methods in a base 6749 // class without overriding any. 6750 if (!M->isStatic()) 6751 DiagnoseHiddenVirtualMethods(M); 6752 if (M->hasAttr<OverrideAttr>()) 6753 HasMethodWithOverrideControl = true; 6754 else if (M->size_overridden_methods() > 0) 6755 HasOverridingMethodWithoutOverrideControl = true; 6756 } 6757 6758 if (!isa<CXXDestructorDecl>(M)) 6759 CompleteMemberFunction(M); 6760 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6761 CheckForDefaultedFunction( 6762 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6763 } 6764 } 6765 6766 if (HasOverridingMethodWithoutOverrideControl) { 6767 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6768 for (auto *M : Record->methods()) 6769 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6770 } 6771 6772 // Check the defaulted secondary comparisons after any other member functions. 6773 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6774 CheckExplicitlyDefaultedFunction(S, FD); 6775 6776 // If this is a member function, we deferred checking it until now. 6777 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6778 CheckCompletedMemberFunction(MD); 6779 } 6780 6781 // ms_struct is a request to use the same ABI rules as MSVC. Check 6782 // whether this class uses any C++ features that are implemented 6783 // completely differently in MSVC, and if so, emit a diagnostic. 6784 // That diagnostic defaults to an error, but we allow projects to 6785 // map it down to a warning (or ignore it). It's a fairly common 6786 // practice among users of the ms_struct pragma to mass-annotate 6787 // headers, sweeping up a bunch of types that the project doesn't 6788 // really rely on MSVC-compatible layout for. We must therefore 6789 // support "ms_struct except for C++ stuff" as a secondary ABI. 6790 // Don't emit this diagnostic if the feature was enabled as a 6791 // language option (as opposed to via a pragma or attribute), as 6792 // the option -mms-bitfields otherwise essentially makes it impossible 6793 // to build C++ code, unless this diagnostic is turned off. 6794 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6795 (Record->isPolymorphic() || Record->getNumBases())) { 6796 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6797 } 6798 6799 checkClassLevelDLLAttribute(Record); 6800 checkClassLevelCodeSegAttribute(Record); 6801 6802 bool ClangABICompat4 = 6803 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6804 TargetInfo::CallingConvKind CCK = 6805 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6806 bool CanPass = canPassInRegisters(*this, Record, CCK); 6807 6808 // Do not change ArgPassingRestrictions if it has already been set to 6809 // APK_CanNeverPassInRegs. 6810 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6811 Record->setArgPassingRestrictions(CanPass 6812 ? RecordDecl::APK_CanPassInRegs 6813 : RecordDecl::APK_CannotPassInRegs); 6814 6815 // If canPassInRegisters returns true despite the record having a non-trivial 6816 // destructor, the record is destructed in the callee. This happens only when 6817 // the record or one of its subobjects has a field annotated with trivial_abi 6818 // or a field qualified with ObjC __strong/__weak. 6819 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6820 Record->setParamDestroyedInCallee(true); 6821 else if (Record->hasNonTrivialDestructor()) 6822 Record->setParamDestroyedInCallee(CanPass); 6823 6824 if (getLangOpts().ForceEmitVTables) { 6825 // If we want to emit all the vtables, we need to mark it as used. This 6826 // is especially required for cases like vtable assumption loads. 6827 MarkVTableUsed(Record->getInnerLocStart(), Record); 6828 } 6829 6830 if (getLangOpts().CUDA) { 6831 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6832 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6833 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6834 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6835 } 6836 } 6837 6838 /// Look up the special member function that would be called by a special 6839 /// member function for a subobject of class type. 6840 /// 6841 /// \param Class The class type of the subobject. 6842 /// \param CSM The kind of special member function. 6843 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6844 /// \param ConstRHS True if this is a copy operation with a const object 6845 /// on its RHS, that is, if the argument to the outer special member 6846 /// function is 'const' and this is not a field marked 'mutable'. 6847 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6848 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6849 unsigned FieldQuals, bool ConstRHS) { 6850 unsigned LHSQuals = 0; 6851 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6852 LHSQuals = FieldQuals; 6853 6854 unsigned RHSQuals = FieldQuals; 6855 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6856 RHSQuals = 0; 6857 else if (ConstRHS) 6858 RHSQuals |= Qualifiers::Const; 6859 6860 return S.LookupSpecialMember(Class, CSM, 6861 RHSQuals & Qualifiers::Const, 6862 RHSQuals & Qualifiers::Volatile, 6863 false, 6864 LHSQuals & Qualifiers::Const, 6865 LHSQuals & Qualifiers::Volatile); 6866 } 6867 6868 class Sema::InheritedConstructorInfo { 6869 Sema &S; 6870 SourceLocation UseLoc; 6871 6872 /// A mapping from the base classes through which the constructor was 6873 /// inherited to the using shadow declaration in that base class (or a null 6874 /// pointer if the constructor was declared in that base class). 6875 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6876 InheritedFromBases; 6877 6878 public: 6879 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6880 ConstructorUsingShadowDecl *Shadow) 6881 : S(S), UseLoc(UseLoc) { 6882 bool DiagnosedMultipleConstructedBases = false; 6883 CXXRecordDecl *ConstructedBase = nullptr; 6884 UsingDecl *ConstructedBaseUsing = nullptr; 6885 6886 // Find the set of such base class subobjects and check that there's a 6887 // unique constructed subobject. 6888 for (auto *D : Shadow->redecls()) { 6889 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6890 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6891 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6892 6893 InheritedFromBases.insert( 6894 std::make_pair(DNominatedBase->getCanonicalDecl(), 6895 DShadow->getNominatedBaseClassShadowDecl())); 6896 if (DShadow->constructsVirtualBase()) 6897 InheritedFromBases.insert( 6898 std::make_pair(DConstructedBase->getCanonicalDecl(), 6899 DShadow->getConstructedBaseClassShadowDecl())); 6900 else 6901 assert(DNominatedBase == DConstructedBase); 6902 6903 // [class.inhctor.init]p2: 6904 // If the constructor was inherited from multiple base class subobjects 6905 // of type B, the program is ill-formed. 6906 if (!ConstructedBase) { 6907 ConstructedBase = DConstructedBase; 6908 ConstructedBaseUsing = D->getUsingDecl(); 6909 } else if (ConstructedBase != DConstructedBase && 6910 !Shadow->isInvalidDecl()) { 6911 if (!DiagnosedMultipleConstructedBases) { 6912 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6913 << Shadow->getTargetDecl(); 6914 S.Diag(ConstructedBaseUsing->getLocation(), 6915 diag::note_ambiguous_inherited_constructor_using) 6916 << ConstructedBase; 6917 DiagnosedMultipleConstructedBases = true; 6918 } 6919 S.Diag(D->getUsingDecl()->getLocation(), 6920 diag::note_ambiguous_inherited_constructor_using) 6921 << DConstructedBase; 6922 } 6923 } 6924 6925 if (DiagnosedMultipleConstructedBases) 6926 Shadow->setInvalidDecl(); 6927 } 6928 6929 /// Find the constructor to use for inherited construction of a base class, 6930 /// and whether that base class constructor inherits the constructor from a 6931 /// virtual base class (in which case it won't actually invoke it). 6932 std::pair<CXXConstructorDecl *, bool> 6933 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6934 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6935 if (It == InheritedFromBases.end()) 6936 return std::make_pair(nullptr, false); 6937 6938 // This is an intermediary class. 6939 if (It->second) 6940 return std::make_pair( 6941 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6942 It->second->constructsVirtualBase()); 6943 6944 // This is the base class from which the constructor was inherited. 6945 return std::make_pair(Ctor, false); 6946 } 6947 }; 6948 6949 /// Is the special member function which would be selected to perform the 6950 /// specified operation on the specified class type a constexpr constructor? 6951 static bool 6952 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6953 Sema::CXXSpecialMember CSM, unsigned Quals, 6954 bool ConstRHS, 6955 CXXConstructorDecl *InheritedCtor = nullptr, 6956 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6957 // If we're inheriting a constructor, see if we need to call it for this base 6958 // class. 6959 if (InheritedCtor) { 6960 assert(CSM == Sema::CXXDefaultConstructor); 6961 auto BaseCtor = 6962 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6963 if (BaseCtor) 6964 return BaseCtor->isConstexpr(); 6965 } 6966 6967 if (CSM == Sema::CXXDefaultConstructor) 6968 return ClassDecl->hasConstexprDefaultConstructor(); 6969 if (CSM == Sema::CXXDestructor) 6970 return ClassDecl->hasConstexprDestructor(); 6971 6972 Sema::SpecialMemberOverloadResult SMOR = 6973 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6974 if (!SMOR.getMethod()) 6975 // A constructor we wouldn't select can't be "involved in initializing" 6976 // anything. 6977 return true; 6978 return SMOR.getMethod()->isConstexpr(); 6979 } 6980 6981 /// Determine whether the specified special member function would be constexpr 6982 /// if it were implicitly defined. 6983 static bool defaultedSpecialMemberIsConstexpr( 6984 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6985 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6986 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6987 if (!S.getLangOpts().CPlusPlus11) 6988 return false; 6989 6990 // C++11 [dcl.constexpr]p4: 6991 // In the definition of a constexpr constructor [...] 6992 bool Ctor = true; 6993 switch (CSM) { 6994 case Sema::CXXDefaultConstructor: 6995 if (Inherited) 6996 break; 6997 // Since default constructor lookup is essentially trivial (and cannot 6998 // involve, for instance, template instantiation), we compute whether a 6999 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7000 // 7001 // This is important for performance; we need to know whether the default 7002 // constructor is constexpr to determine whether the type is a literal type. 7003 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7004 7005 case Sema::CXXCopyConstructor: 7006 case Sema::CXXMoveConstructor: 7007 // For copy or move constructors, we need to perform overload resolution. 7008 break; 7009 7010 case Sema::CXXCopyAssignment: 7011 case Sema::CXXMoveAssignment: 7012 if (!S.getLangOpts().CPlusPlus14) 7013 return false; 7014 // In C++1y, we need to perform overload resolution. 7015 Ctor = false; 7016 break; 7017 7018 case Sema::CXXDestructor: 7019 return ClassDecl->defaultedDestructorIsConstexpr(); 7020 7021 case Sema::CXXInvalid: 7022 return false; 7023 } 7024 7025 // -- if the class is a non-empty union, or for each non-empty anonymous 7026 // union member of a non-union class, exactly one non-static data member 7027 // shall be initialized; [DR1359] 7028 // 7029 // If we squint, this is guaranteed, since exactly one non-static data member 7030 // will be initialized (if the constructor isn't deleted), we just don't know 7031 // which one. 7032 if (Ctor && ClassDecl->isUnion()) 7033 return CSM == Sema::CXXDefaultConstructor 7034 ? ClassDecl->hasInClassInitializer() || 7035 !ClassDecl->hasVariantMembers() 7036 : true; 7037 7038 // -- the class shall not have any virtual base classes; 7039 if (Ctor && ClassDecl->getNumVBases()) 7040 return false; 7041 7042 // C++1y [class.copy]p26: 7043 // -- [the class] is a literal type, and 7044 if (!Ctor && !ClassDecl->isLiteral()) 7045 return false; 7046 7047 // -- every constructor involved in initializing [...] base class 7048 // sub-objects shall be a constexpr constructor; 7049 // -- the assignment operator selected to copy/move each direct base 7050 // class is a constexpr function, and 7051 for (const auto &B : ClassDecl->bases()) { 7052 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7053 if (!BaseType) continue; 7054 7055 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7056 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7057 InheritedCtor, Inherited)) 7058 return false; 7059 } 7060 7061 // -- every constructor involved in initializing non-static data members 7062 // [...] shall be a constexpr constructor; 7063 // -- every non-static data member and base class sub-object shall be 7064 // initialized 7065 // -- for each non-static data member of X that is of class type (or array 7066 // thereof), the assignment operator selected to copy/move that member is 7067 // a constexpr function 7068 for (const auto *F : ClassDecl->fields()) { 7069 if (F->isInvalidDecl()) 7070 continue; 7071 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7072 continue; 7073 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7074 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7075 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7076 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7077 BaseType.getCVRQualifiers(), 7078 ConstArg && !F->isMutable())) 7079 return false; 7080 } else if (CSM == Sema::CXXDefaultConstructor) { 7081 return false; 7082 } 7083 } 7084 7085 // All OK, it's constexpr! 7086 return true; 7087 } 7088 7089 namespace { 7090 /// RAII object to register a defaulted function as having its exception 7091 /// specification computed. 7092 struct ComputingExceptionSpec { 7093 Sema &S; 7094 7095 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7096 : S(S) { 7097 Sema::CodeSynthesisContext Ctx; 7098 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7099 Ctx.PointOfInstantiation = Loc; 7100 Ctx.Entity = FD; 7101 S.pushCodeSynthesisContext(Ctx); 7102 } 7103 ~ComputingExceptionSpec() { 7104 S.popCodeSynthesisContext(); 7105 } 7106 }; 7107 } 7108 7109 static Sema::ImplicitExceptionSpecification 7110 ComputeDefaultedSpecialMemberExceptionSpec( 7111 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7112 Sema::InheritedConstructorInfo *ICI); 7113 7114 static Sema::ImplicitExceptionSpecification 7115 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7116 FunctionDecl *FD, 7117 Sema::DefaultedComparisonKind DCK); 7118 7119 static Sema::ImplicitExceptionSpecification 7120 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7121 auto DFK = S.getDefaultedFunctionKind(FD); 7122 if (DFK.isSpecialMember()) 7123 return ComputeDefaultedSpecialMemberExceptionSpec( 7124 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7125 if (DFK.isComparison()) 7126 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7127 DFK.asComparison()); 7128 7129 auto *CD = cast<CXXConstructorDecl>(FD); 7130 assert(CD->getInheritedConstructor() && 7131 "only defaulted functions and inherited constructors have implicit " 7132 "exception specs"); 7133 Sema::InheritedConstructorInfo ICI( 7134 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7135 return ComputeDefaultedSpecialMemberExceptionSpec( 7136 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7137 } 7138 7139 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7140 CXXMethodDecl *MD) { 7141 FunctionProtoType::ExtProtoInfo EPI; 7142 7143 // Build an exception specification pointing back at this member. 7144 EPI.ExceptionSpec.Type = EST_Unevaluated; 7145 EPI.ExceptionSpec.SourceDecl = MD; 7146 7147 // Set the calling convention to the default for C++ instance methods. 7148 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7149 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7150 /*IsCXXMethod=*/true)); 7151 return EPI; 7152 } 7153 7154 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7155 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7156 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7157 return; 7158 7159 // Evaluate the exception specification. 7160 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7161 auto ESI = IES.getExceptionSpec(); 7162 7163 // Update the type of the special member to use it. 7164 UpdateExceptionSpec(FD, ESI); 7165 } 7166 7167 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7168 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7169 7170 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7171 if (!DefKind) { 7172 assert(FD->getDeclContext()->isDependentContext()); 7173 return; 7174 } 7175 7176 if (DefKind.isSpecialMember() 7177 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7178 DefKind.asSpecialMember()) 7179 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7180 FD->setInvalidDecl(); 7181 } 7182 7183 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7184 CXXSpecialMember CSM) { 7185 CXXRecordDecl *RD = MD->getParent(); 7186 7187 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7188 "not an explicitly-defaulted special member"); 7189 7190 // Defer all checking for special members of a dependent type. 7191 if (RD->isDependentType()) 7192 return false; 7193 7194 // Whether this was the first-declared instance of the constructor. 7195 // This affects whether we implicitly add an exception spec and constexpr. 7196 bool First = MD == MD->getCanonicalDecl(); 7197 7198 bool HadError = false; 7199 7200 // C++11 [dcl.fct.def.default]p1: 7201 // A function that is explicitly defaulted shall 7202 // -- be a special member function [...] (checked elsewhere), 7203 // -- have the same type (except for ref-qualifiers, and except that a 7204 // copy operation can take a non-const reference) as an implicit 7205 // declaration, and 7206 // -- not have default arguments. 7207 // C++2a changes the second bullet to instead delete the function if it's 7208 // defaulted on its first declaration, unless it's "an assignment operator, 7209 // and its return type differs or its parameter type is not a reference". 7210 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7211 bool ShouldDeleteForTypeMismatch = false; 7212 unsigned ExpectedParams = 1; 7213 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7214 ExpectedParams = 0; 7215 if (MD->getNumParams() != ExpectedParams) { 7216 // This checks for default arguments: a copy or move constructor with a 7217 // default argument is classified as a default constructor, and assignment 7218 // operations and destructors can't have default arguments. 7219 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7220 << CSM << MD->getSourceRange(); 7221 HadError = true; 7222 } else if (MD->isVariadic()) { 7223 if (DeleteOnTypeMismatch) 7224 ShouldDeleteForTypeMismatch = true; 7225 else { 7226 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7227 << CSM << MD->getSourceRange(); 7228 HadError = true; 7229 } 7230 } 7231 7232 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7233 7234 bool CanHaveConstParam = false; 7235 if (CSM == CXXCopyConstructor) 7236 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7237 else if (CSM == CXXCopyAssignment) 7238 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7239 7240 QualType ReturnType = Context.VoidTy; 7241 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7242 // Check for return type matching. 7243 ReturnType = Type->getReturnType(); 7244 7245 QualType DeclType = Context.getTypeDeclType(RD); 7246 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7247 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7248 7249 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7250 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7251 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7252 HadError = true; 7253 } 7254 7255 // A defaulted special member cannot have cv-qualifiers. 7256 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7257 if (DeleteOnTypeMismatch) 7258 ShouldDeleteForTypeMismatch = true; 7259 else { 7260 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7261 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7262 HadError = true; 7263 } 7264 } 7265 } 7266 7267 // Check for parameter type matching. 7268 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7269 bool HasConstParam = false; 7270 if (ExpectedParams && ArgType->isReferenceType()) { 7271 // Argument must be reference to possibly-const T. 7272 QualType ReferentType = ArgType->getPointeeType(); 7273 HasConstParam = ReferentType.isConstQualified(); 7274 7275 if (ReferentType.isVolatileQualified()) { 7276 if (DeleteOnTypeMismatch) 7277 ShouldDeleteForTypeMismatch = true; 7278 else { 7279 Diag(MD->getLocation(), 7280 diag::err_defaulted_special_member_volatile_param) << CSM; 7281 HadError = true; 7282 } 7283 } 7284 7285 if (HasConstParam && !CanHaveConstParam) { 7286 if (DeleteOnTypeMismatch) 7287 ShouldDeleteForTypeMismatch = true; 7288 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7289 Diag(MD->getLocation(), 7290 diag::err_defaulted_special_member_copy_const_param) 7291 << (CSM == CXXCopyAssignment); 7292 // FIXME: Explain why this special member can't be const. 7293 HadError = true; 7294 } else { 7295 Diag(MD->getLocation(), 7296 diag::err_defaulted_special_member_move_const_param) 7297 << (CSM == CXXMoveAssignment); 7298 HadError = true; 7299 } 7300 } 7301 } else if (ExpectedParams) { 7302 // A copy assignment operator can take its argument by value, but a 7303 // defaulted one cannot. 7304 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7305 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7306 HadError = true; 7307 } 7308 7309 // C++11 [dcl.fct.def.default]p2: 7310 // An explicitly-defaulted function may be declared constexpr only if it 7311 // would have been implicitly declared as constexpr, 7312 // Do not apply this rule to members of class templates, since core issue 1358 7313 // makes such functions always instantiate to constexpr functions. For 7314 // functions which cannot be constexpr (for non-constructors in C++11 and for 7315 // destructors in C++14 and C++17), this is checked elsewhere. 7316 // 7317 // FIXME: This should not apply if the member is deleted. 7318 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7319 HasConstParam); 7320 if ((getLangOpts().CPlusPlus20 || 7321 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7322 : isa<CXXConstructorDecl>(MD))) && 7323 MD->isConstexpr() && !Constexpr && 7324 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7325 Diag(MD->getBeginLoc(), MD->isConsteval() 7326 ? diag::err_incorrect_defaulted_consteval 7327 : diag::err_incorrect_defaulted_constexpr) 7328 << CSM; 7329 // FIXME: Explain why the special member can't be constexpr. 7330 HadError = true; 7331 } 7332 7333 if (First) { 7334 // C++2a [dcl.fct.def.default]p3: 7335 // If a function is explicitly defaulted on its first declaration, it is 7336 // implicitly considered to be constexpr if the implicit declaration 7337 // would be. 7338 MD->setConstexprKind( 7339 Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr) 7340 : CSK_unspecified); 7341 7342 if (!Type->hasExceptionSpec()) { 7343 // C++2a [except.spec]p3: 7344 // If a declaration of a function does not have a noexcept-specifier 7345 // [and] is defaulted on its first declaration, [...] the exception 7346 // specification is as specified below 7347 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7348 EPI.ExceptionSpec.Type = EST_Unevaluated; 7349 EPI.ExceptionSpec.SourceDecl = MD; 7350 MD->setType(Context.getFunctionType(ReturnType, 7351 llvm::makeArrayRef(&ArgType, 7352 ExpectedParams), 7353 EPI)); 7354 } 7355 } 7356 7357 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7358 if (First) { 7359 SetDeclDeleted(MD, MD->getLocation()); 7360 if (!inTemplateInstantiation() && !HadError) { 7361 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7362 if (ShouldDeleteForTypeMismatch) { 7363 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7364 } else { 7365 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7366 } 7367 } 7368 if (ShouldDeleteForTypeMismatch && !HadError) { 7369 Diag(MD->getLocation(), 7370 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7371 } 7372 } else { 7373 // C++11 [dcl.fct.def.default]p4: 7374 // [For a] user-provided explicitly-defaulted function [...] if such a 7375 // function is implicitly defined as deleted, the program is ill-formed. 7376 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7377 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7378 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7379 HadError = true; 7380 } 7381 } 7382 7383 return HadError; 7384 } 7385 7386 namespace { 7387 /// Helper class for building and checking a defaulted comparison. 7388 /// 7389 /// Defaulted functions are built in two phases: 7390 /// 7391 /// * First, the set of operations that the function will perform are 7392 /// identified, and some of them are checked. If any of the checked 7393 /// operations is invalid in certain ways, the comparison function is 7394 /// defined as deleted and no body is built. 7395 /// * Then, if the function is not defined as deleted, the body is built. 7396 /// 7397 /// This is accomplished by performing two visitation steps over the eventual 7398 /// body of the function. 7399 template<typename Derived, typename ResultList, typename Result, 7400 typename Subobject> 7401 class DefaultedComparisonVisitor { 7402 public: 7403 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7404 7405 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7406 DefaultedComparisonKind DCK) 7407 : S(S), RD(RD), FD(FD), DCK(DCK) { 7408 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7409 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7410 // UnresolvedSet to avoid this copy. 7411 Fns.assign(Info->getUnqualifiedLookups().begin(), 7412 Info->getUnqualifiedLookups().end()); 7413 } 7414 } 7415 7416 ResultList visit() { 7417 // The type of an lvalue naming a parameter of this function. 7418 QualType ParamLvalType = 7419 FD->getParamDecl(0)->getType().getNonReferenceType(); 7420 7421 ResultList Results; 7422 7423 switch (DCK) { 7424 case DefaultedComparisonKind::None: 7425 llvm_unreachable("not a defaulted comparison"); 7426 7427 case DefaultedComparisonKind::Equal: 7428 case DefaultedComparisonKind::ThreeWay: 7429 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7430 return Results; 7431 7432 case DefaultedComparisonKind::NotEqual: 7433 case DefaultedComparisonKind::Relational: 7434 Results.add(getDerived().visitExpandedSubobject( 7435 ParamLvalType, getDerived().getCompleteObject())); 7436 return Results; 7437 } 7438 llvm_unreachable(""); 7439 } 7440 7441 protected: 7442 Derived &getDerived() { return static_cast<Derived&>(*this); } 7443 7444 /// Visit the expanded list of subobjects of the given type, as specified in 7445 /// C++2a [class.compare.default]. 7446 /// 7447 /// \return \c true if the ResultList object said we're done, \c false if not. 7448 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7449 Qualifiers Quals) { 7450 // C++2a [class.compare.default]p4: 7451 // The direct base class subobjects of C 7452 for (CXXBaseSpecifier &Base : Record->bases()) 7453 if (Results.add(getDerived().visitSubobject( 7454 S.Context.getQualifiedType(Base.getType(), Quals), 7455 getDerived().getBase(&Base)))) 7456 return true; 7457 7458 // followed by the non-static data members of C 7459 for (FieldDecl *Field : Record->fields()) { 7460 // Recursively expand anonymous structs. 7461 if (Field->isAnonymousStructOrUnion()) { 7462 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7463 Quals)) 7464 return true; 7465 continue; 7466 } 7467 7468 // Figure out the type of an lvalue denoting this field. 7469 Qualifiers FieldQuals = Quals; 7470 if (Field->isMutable()) 7471 FieldQuals.removeConst(); 7472 QualType FieldType = 7473 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7474 7475 if (Results.add(getDerived().visitSubobject( 7476 FieldType, getDerived().getField(Field)))) 7477 return true; 7478 } 7479 7480 // form a list of subobjects. 7481 return false; 7482 } 7483 7484 Result visitSubobject(QualType Type, Subobject Subobj) { 7485 // In that list, any subobject of array type is recursively expanded 7486 const ArrayType *AT = S.Context.getAsArrayType(Type); 7487 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7488 return getDerived().visitSubobjectArray(CAT->getElementType(), 7489 CAT->getSize(), Subobj); 7490 return getDerived().visitExpandedSubobject(Type, Subobj); 7491 } 7492 7493 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7494 Subobject Subobj) { 7495 return getDerived().visitSubobject(Type, Subobj); 7496 } 7497 7498 protected: 7499 Sema &S; 7500 CXXRecordDecl *RD; 7501 FunctionDecl *FD; 7502 DefaultedComparisonKind DCK; 7503 UnresolvedSet<16> Fns; 7504 }; 7505 7506 /// Information about a defaulted comparison, as determined by 7507 /// DefaultedComparisonAnalyzer. 7508 struct DefaultedComparisonInfo { 7509 bool Deleted = false; 7510 bool Constexpr = true; 7511 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7512 7513 static DefaultedComparisonInfo deleted() { 7514 DefaultedComparisonInfo Deleted; 7515 Deleted.Deleted = true; 7516 return Deleted; 7517 } 7518 7519 bool add(const DefaultedComparisonInfo &R) { 7520 Deleted |= R.Deleted; 7521 Constexpr &= R.Constexpr; 7522 Category = commonComparisonType(Category, R.Category); 7523 return Deleted; 7524 } 7525 }; 7526 7527 /// An element in the expanded list of subobjects of a defaulted comparison, as 7528 /// specified in C++2a [class.compare.default]p4. 7529 struct DefaultedComparisonSubobject { 7530 enum { CompleteObject, Member, Base } Kind; 7531 NamedDecl *Decl; 7532 SourceLocation Loc; 7533 }; 7534 7535 /// A visitor over the notional body of a defaulted comparison that determines 7536 /// whether that body would be deleted or constexpr. 7537 class DefaultedComparisonAnalyzer 7538 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7539 DefaultedComparisonInfo, 7540 DefaultedComparisonInfo, 7541 DefaultedComparisonSubobject> { 7542 public: 7543 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7544 7545 private: 7546 DiagnosticKind Diagnose; 7547 7548 public: 7549 using Base = DefaultedComparisonVisitor; 7550 using Result = DefaultedComparisonInfo; 7551 using Subobject = DefaultedComparisonSubobject; 7552 7553 friend Base; 7554 7555 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7556 DefaultedComparisonKind DCK, 7557 DiagnosticKind Diagnose = NoDiagnostics) 7558 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7559 7560 Result visit() { 7561 if ((DCK == DefaultedComparisonKind::Equal || 7562 DCK == DefaultedComparisonKind::ThreeWay) && 7563 RD->hasVariantMembers()) { 7564 // C++2a [class.compare.default]p2 [P2002R0]: 7565 // A defaulted comparison operator function for class C is defined as 7566 // deleted if [...] C has variant members. 7567 if (Diagnose == ExplainDeleted) { 7568 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7569 << FD << RD->isUnion() << RD; 7570 } 7571 return Result::deleted(); 7572 } 7573 7574 return Base::visit(); 7575 } 7576 7577 private: 7578 Subobject getCompleteObject() { 7579 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7580 } 7581 7582 Subobject getBase(CXXBaseSpecifier *Base) { 7583 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7584 Base->getBaseTypeLoc()}; 7585 } 7586 7587 Subobject getField(FieldDecl *Field) { 7588 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7589 } 7590 7591 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7592 // C++2a [class.compare.default]p2 [P2002R0]: 7593 // A defaulted <=> or == operator function for class C is defined as 7594 // deleted if any non-static data member of C is of reference type 7595 if (Type->isReferenceType()) { 7596 if (Diagnose == ExplainDeleted) { 7597 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7598 << FD << RD; 7599 } 7600 return Result::deleted(); 7601 } 7602 7603 // [...] Let xi be an lvalue denoting the ith element [...] 7604 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7605 Expr *Args[] = {&Xi, &Xi}; 7606 7607 // All operators start by trying to apply that same operator recursively. 7608 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7609 assert(OO != OO_None && "not an overloaded operator!"); 7610 return visitBinaryOperator(OO, Args, Subobj); 7611 } 7612 7613 Result 7614 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7615 Subobject Subobj, 7616 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7617 // Note that there is no need to consider rewritten candidates here if 7618 // we've already found there is no viable 'operator<=>' candidate (and are 7619 // considering synthesizing a '<=>' from '==' and '<'). 7620 OverloadCandidateSet CandidateSet( 7621 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7622 OverloadCandidateSet::OperatorRewriteInfo( 7623 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7624 7625 /// C++2a [class.compare.default]p1 [P2002R0]: 7626 /// [...] the defaulted function itself is never a candidate for overload 7627 /// resolution [...] 7628 CandidateSet.exclude(FD); 7629 7630 if (Args[0]->getType()->isOverloadableType()) 7631 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7632 else { 7633 // FIXME: We determine whether this is a valid expression by checking to 7634 // see if there's a viable builtin operator candidate for it. That isn't 7635 // really what the rules ask us to do, but should give the right results. 7636 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7637 } 7638 7639 Result R; 7640 7641 OverloadCandidateSet::iterator Best; 7642 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7643 case OR_Success: { 7644 // C++2a [class.compare.secondary]p2 [P2002R0]: 7645 // The operator function [...] is defined as deleted if [...] the 7646 // candidate selected by overload resolution is not a rewritten 7647 // candidate. 7648 if ((DCK == DefaultedComparisonKind::NotEqual || 7649 DCK == DefaultedComparisonKind::Relational) && 7650 !Best->RewriteKind) { 7651 if (Diagnose == ExplainDeleted) { 7652 S.Diag(Best->Function->getLocation(), 7653 diag::note_defaulted_comparison_not_rewritten_callee) 7654 << FD; 7655 } 7656 return Result::deleted(); 7657 } 7658 7659 // Throughout C++2a [class.compare]: if overload resolution does not 7660 // result in a usable function, the candidate function is defined as 7661 // deleted. This requires that we selected an accessible function. 7662 // 7663 // Note that this only considers the access of the function when named 7664 // within the type of the subobject, and not the access path for any 7665 // derived-to-base conversion. 7666 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7667 if (ArgClass && Best->FoundDecl.getDecl() && 7668 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7669 QualType ObjectType = Subobj.Kind == Subobject::Member 7670 ? Args[0]->getType() 7671 : S.Context.getRecordType(RD); 7672 if (!S.isMemberAccessibleForDeletion( 7673 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7674 Diagnose == ExplainDeleted 7675 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7676 << FD << Subobj.Kind << Subobj.Decl 7677 : S.PDiag())) 7678 return Result::deleted(); 7679 } 7680 7681 // C++2a [class.compare.default]p3 [P2002R0]: 7682 // A defaulted comparison function is constexpr-compatible if [...] 7683 // no overlod resolution performed [...] results in a non-constexpr 7684 // function. 7685 if (FunctionDecl *BestFD = Best->Function) { 7686 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7687 // If it's not constexpr, explain why not. 7688 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7689 if (Subobj.Kind != Subobject::CompleteObject) 7690 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7691 << Subobj.Kind << Subobj.Decl; 7692 S.Diag(BestFD->getLocation(), 7693 diag::note_defaulted_comparison_not_constexpr_here); 7694 // Bail out after explaining; we don't want any more notes. 7695 return Result::deleted(); 7696 } 7697 R.Constexpr &= BestFD->isConstexpr(); 7698 } 7699 7700 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7701 if (auto *BestFD = Best->Function) { 7702 // If any callee has an undeduced return type, deduce it now. 7703 // FIXME: It's not clear how a failure here should be handled. For 7704 // now, we produce an eager diagnostic, because that is forward 7705 // compatible with most (all?) other reasonable options. 7706 if (BestFD->getReturnType()->isUndeducedType() && 7707 S.DeduceReturnType(BestFD, FD->getLocation(), 7708 /*Diagnose=*/false)) { 7709 // Don't produce a duplicate error when asked to explain why the 7710 // comparison is deleted: we diagnosed that when initially checking 7711 // the defaulted operator. 7712 if (Diagnose == NoDiagnostics) { 7713 S.Diag( 7714 FD->getLocation(), 7715 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7716 << Subobj.Kind << Subobj.Decl; 7717 S.Diag( 7718 Subobj.Loc, 7719 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7720 << Subobj.Kind << Subobj.Decl; 7721 S.Diag(BestFD->getLocation(), 7722 diag::note_defaulted_comparison_cannot_deduce_callee) 7723 << Subobj.Kind << Subobj.Decl; 7724 } 7725 return Result::deleted(); 7726 } 7727 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7728 BestFD->getCallResultType())) { 7729 R.Category = Info->Kind; 7730 } else { 7731 if (Diagnose == ExplainDeleted) { 7732 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7733 << Subobj.Kind << Subobj.Decl 7734 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7735 S.Diag(BestFD->getLocation(), 7736 diag::note_defaulted_comparison_cannot_deduce_callee) 7737 << Subobj.Kind << Subobj.Decl; 7738 } 7739 return Result::deleted(); 7740 } 7741 } else { 7742 Optional<ComparisonCategoryType> Cat = 7743 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7744 assert(Cat && "no category for builtin comparison?"); 7745 R.Category = *Cat; 7746 } 7747 } 7748 7749 // Note that we might be rewriting to a different operator. That call is 7750 // not considered until we come to actually build the comparison function. 7751 break; 7752 } 7753 7754 case OR_Ambiguous: 7755 if (Diagnose == ExplainDeleted) { 7756 unsigned Kind = 0; 7757 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7758 Kind = OO == OO_EqualEqual ? 1 : 2; 7759 CandidateSet.NoteCandidates( 7760 PartialDiagnosticAt( 7761 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7762 << FD << Kind << Subobj.Kind << Subobj.Decl), 7763 S, OCD_AmbiguousCandidates, Args); 7764 } 7765 R = Result::deleted(); 7766 break; 7767 7768 case OR_Deleted: 7769 if (Diagnose == ExplainDeleted) { 7770 if ((DCK == DefaultedComparisonKind::NotEqual || 7771 DCK == DefaultedComparisonKind::Relational) && 7772 !Best->RewriteKind) { 7773 S.Diag(Best->Function->getLocation(), 7774 diag::note_defaulted_comparison_not_rewritten_callee) 7775 << FD; 7776 } else { 7777 S.Diag(Subobj.Loc, 7778 diag::note_defaulted_comparison_calls_deleted) 7779 << FD << Subobj.Kind << Subobj.Decl; 7780 S.NoteDeletedFunction(Best->Function); 7781 } 7782 } 7783 R = Result::deleted(); 7784 break; 7785 7786 case OR_No_Viable_Function: 7787 // If there's no usable candidate, we're done unless we can rewrite a 7788 // '<=>' in terms of '==' and '<'. 7789 if (OO == OO_Spaceship && 7790 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7791 // For any kind of comparison category return type, we need a usable 7792 // '==' and a usable '<'. 7793 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7794 &CandidateSet))) 7795 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7796 break; 7797 } 7798 7799 if (Diagnose == ExplainDeleted) { 7800 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7801 << FD << Subobj.Kind << Subobj.Decl; 7802 7803 // For a three-way comparison, list both the candidates for the 7804 // original operator and the candidates for the synthesized operator. 7805 if (SpaceshipCandidates) { 7806 SpaceshipCandidates->NoteCandidates( 7807 S, Args, 7808 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7809 Args, FD->getLocation())); 7810 S.Diag(Subobj.Loc, 7811 diag::note_defaulted_comparison_no_viable_function_synthesized) 7812 << (OO == OO_EqualEqual ? 0 : 1); 7813 } 7814 7815 CandidateSet.NoteCandidates( 7816 S, Args, 7817 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7818 FD->getLocation())); 7819 } 7820 R = Result::deleted(); 7821 break; 7822 } 7823 7824 return R; 7825 } 7826 }; 7827 7828 /// A list of statements. 7829 struct StmtListResult { 7830 bool IsInvalid = false; 7831 llvm::SmallVector<Stmt*, 16> Stmts; 7832 7833 bool add(const StmtResult &S) { 7834 IsInvalid |= S.isInvalid(); 7835 if (IsInvalid) 7836 return true; 7837 Stmts.push_back(S.get()); 7838 return false; 7839 } 7840 }; 7841 7842 /// A visitor over the notional body of a defaulted comparison that synthesizes 7843 /// the actual body. 7844 class DefaultedComparisonSynthesizer 7845 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7846 StmtListResult, StmtResult, 7847 std::pair<ExprResult, ExprResult>> { 7848 SourceLocation Loc; 7849 unsigned ArrayDepth = 0; 7850 7851 public: 7852 using Base = DefaultedComparisonVisitor; 7853 using ExprPair = std::pair<ExprResult, ExprResult>; 7854 7855 friend Base; 7856 7857 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7858 DefaultedComparisonKind DCK, 7859 SourceLocation BodyLoc) 7860 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7861 7862 /// Build a suitable function body for this defaulted comparison operator. 7863 StmtResult build() { 7864 Sema::CompoundScopeRAII CompoundScope(S); 7865 7866 StmtListResult Stmts = visit(); 7867 if (Stmts.IsInvalid) 7868 return StmtError(); 7869 7870 ExprResult RetVal; 7871 switch (DCK) { 7872 case DefaultedComparisonKind::None: 7873 llvm_unreachable("not a defaulted comparison"); 7874 7875 case DefaultedComparisonKind::Equal: { 7876 // C++2a [class.eq]p3: 7877 // [...] compar[e] the corresponding elements [...] until the first 7878 // index i where xi == yi yields [...] false. If no such index exists, 7879 // V is true. Otherwise, V is false. 7880 // 7881 // Join the comparisons with '&&'s and return the result. Use a right 7882 // fold (traversing the conditions right-to-left), because that 7883 // short-circuits more naturally. 7884 auto OldStmts = std::move(Stmts.Stmts); 7885 Stmts.Stmts.clear(); 7886 ExprResult CmpSoFar; 7887 // Finish a particular comparison chain. 7888 auto FinishCmp = [&] { 7889 if (Expr *Prior = CmpSoFar.get()) { 7890 // Convert the last expression to 'return ...;' 7891 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7892 RetVal = CmpSoFar; 7893 // Convert any prior comparison to 'if (!(...)) return false;' 7894 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7895 return true; 7896 CmpSoFar = ExprResult(); 7897 } 7898 return false; 7899 }; 7900 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7901 Expr *E = dyn_cast<Expr>(EAsStmt); 7902 if (!E) { 7903 // Found an array comparison. 7904 if (FinishCmp() || Stmts.add(EAsStmt)) 7905 return StmtError(); 7906 continue; 7907 } 7908 7909 if (CmpSoFar.isUnset()) { 7910 CmpSoFar = E; 7911 continue; 7912 } 7913 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7914 if (CmpSoFar.isInvalid()) 7915 return StmtError(); 7916 } 7917 if (FinishCmp()) 7918 return StmtError(); 7919 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7920 // If no such index exists, V is true. 7921 if (RetVal.isUnset()) 7922 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7923 break; 7924 } 7925 7926 case DefaultedComparisonKind::ThreeWay: { 7927 // Per C++2a [class.spaceship]p3, as a fallback add: 7928 // return static_cast<R>(std::strong_ordering::equal); 7929 QualType StrongOrdering = S.CheckComparisonCategoryType( 7930 ComparisonCategoryType::StrongOrdering, Loc, 7931 Sema::ComparisonCategoryUsage::DefaultedOperator); 7932 if (StrongOrdering.isNull()) 7933 return StmtError(); 7934 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7935 .getValueInfo(ComparisonCategoryResult::Equal) 7936 ->VD; 7937 RetVal = getDecl(EqualVD); 7938 if (RetVal.isInvalid()) 7939 return StmtError(); 7940 RetVal = buildStaticCastToR(RetVal.get()); 7941 break; 7942 } 7943 7944 case DefaultedComparisonKind::NotEqual: 7945 case DefaultedComparisonKind::Relational: 7946 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7947 break; 7948 } 7949 7950 // Build the final return statement. 7951 if (RetVal.isInvalid()) 7952 return StmtError(); 7953 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7954 if (ReturnStmt.isInvalid()) 7955 return StmtError(); 7956 Stmts.Stmts.push_back(ReturnStmt.get()); 7957 7958 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7959 } 7960 7961 private: 7962 ExprResult getDecl(ValueDecl *VD) { 7963 return S.BuildDeclarationNameExpr( 7964 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7965 } 7966 7967 ExprResult getParam(unsigned I) { 7968 ParmVarDecl *PD = FD->getParamDecl(I); 7969 return getDecl(PD); 7970 } 7971 7972 ExprPair getCompleteObject() { 7973 unsigned Param = 0; 7974 ExprResult LHS; 7975 if (isa<CXXMethodDecl>(FD)) { 7976 // LHS is '*this'. 7977 LHS = S.ActOnCXXThis(Loc); 7978 if (!LHS.isInvalid()) 7979 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7980 } else { 7981 LHS = getParam(Param++); 7982 } 7983 ExprResult RHS = getParam(Param++); 7984 assert(Param == FD->getNumParams()); 7985 return {LHS, RHS}; 7986 } 7987 7988 ExprPair getBase(CXXBaseSpecifier *Base) { 7989 ExprPair Obj = getCompleteObject(); 7990 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7991 return {ExprError(), ExprError()}; 7992 CXXCastPath Path = {Base}; 7993 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7994 CK_DerivedToBase, VK_LValue, &Path), 7995 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7996 CK_DerivedToBase, VK_LValue, &Path)}; 7997 } 7998 7999 ExprPair getField(FieldDecl *Field) { 8000 ExprPair Obj = getCompleteObject(); 8001 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8002 return {ExprError(), ExprError()}; 8003 8004 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8005 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8006 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8007 CXXScopeSpec(), Field, Found, NameInfo), 8008 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8009 CXXScopeSpec(), Field, Found, NameInfo)}; 8010 } 8011 8012 // FIXME: When expanding a subobject, register a note in the code synthesis 8013 // stack to say which subobject we're comparing. 8014 8015 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8016 if (Cond.isInvalid()) 8017 return StmtError(); 8018 8019 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8020 if (NotCond.isInvalid()) 8021 return StmtError(); 8022 8023 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8024 assert(!False.isInvalid() && "should never fail"); 8025 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8026 if (ReturnFalse.isInvalid()) 8027 return StmtError(); 8028 8029 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8030 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8031 Sema::ConditionKind::Boolean), 8032 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8033 } 8034 8035 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8036 ExprPair Subobj) { 8037 QualType SizeType = S.Context.getSizeType(); 8038 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8039 8040 // Build 'size_t i$n = 0'. 8041 IdentifierInfo *IterationVarName = nullptr; 8042 { 8043 SmallString<8> Str; 8044 llvm::raw_svector_ostream OS(Str); 8045 OS << "i" << ArrayDepth; 8046 IterationVarName = &S.Context.Idents.get(OS.str()); 8047 } 8048 VarDecl *IterationVar = VarDecl::Create( 8049 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8050 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8051 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8052 IterationVar->setInit( 8053 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8054 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8055 8056 auto IterRef = [&] { 8057 ExprResult Ref = S.BuildDeclarationNameExpr( 8058 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8059 IterationVar); 8060 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8061 return Ref.get(); 8062 }; 8063 8064 // Build 'i$n != Size'. 8065 ExprResult Cond = S.CreateBuiltinBinOp( 8066 Loc, BO_NE, IterRef(), 8067 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8068 assert(!Cond.isInvalid() && "should never fail"); 8069 8070 // Build '++i$n'. 8071 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8072 assert(!Inc.isInvalid() && "should never fail"); 8073 8074 // Build 'a[i$n]' and 'b[i$n]'. 8075 auto Index = [&](ExprResult E) { 8076 if (E.isInvalid()) 8077 return ExprError(); 8078 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8079 }; 8080 Subobj.first = Index(Subobj.first); 8081 Subobj.second = Index(Subobj.second); 8082 8083 // Compare the array elements. 8084 ++ArrayDepth; 8085 StmtResult Substmt = visitSubobject(Type, Subobj); 8086 --ArrayDepth; 8087 8088 if (Substmt.isInvalid()) 8089 return StmtError(); 8090 8091 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8092 // For outer levels or for an 'operator<=>' we already have a suitable 8093 // statement that returns as necessary. 8094 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8095 assert(DCK == DefaultedComparisonKind::Equal && 8096 "should have non-expression statement"); 8097 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8098 if (Substmt.isInvalid()) 8099 return StmtError(); 8100 } 8101 8102 // Build 'for (...) ...' 8103 return S.ActOnForStmt(Loc, Loc, Init, 8104 S.ActOnCondition(nullptr, Loc, Cond.get(), 8105 Sema::ConditionKind::Boolean), 8106 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8107 Substmt.get()); 8108 } 8109 8110 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8111 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8112 return StmtError(); 8113 8114 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8115 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8116 ExprResult Op; 8117 if (Type->isOverloadableType()) 8118 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8119 Obj.second.get(), /*PerformADL=*/true, 8120 /*AllowRewrittenCandidates=*/true, FD); 8121 else 8122 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8123 if (Op.isInvalid()) 8124 return StmtError(); 8125 8126 switch (DCK) { 8127 case DefaultedComparisonKind::None: 8128 llvm_unreachable("not a defaulted comparison"); 8129 8130 case DefaultedComparisonKind::Equal: 8131 // Per C++2a [class.eq]p2, each comparison is individually contextually 8132 // converted to bool. 8133 Op = S.PerformContextuallyConvertToBool(Op.get()); 8134 if (Op.isInvalid()) 8135 return StmtError(); 8136 return Op.get(); 8137 8138 case DefaultedComparisonKind::ThreeWay: { 8139 // Per C++2a [class.spaceship]p3, form: 8140 // if (R cmp = static_cast<R>(op); cmp != 0) 8141 // return cmp; 8142 QualType R = FD->getReturnType(); 8143 Op = buildStaticCastToR(Op.get()); 8144 if (Op.isInvalid()) 8145 return StmtError(); 8146 8147 // R cmp = ...; 8148 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8149 VarDecl *VD = 8150 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8151 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8152 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8153 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8154 8155 // cmp != 0 8156 ExprResult VDRef = getDecl(VD); 8157 if (VDRef.isInvalid()) 8158 return StmtError(); 8159 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8160 Expr *Zero = 8161 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8162 ExprResult Comp; 8163 if (VDRef.get()->getType()->isOverloadableType()) 8164 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8165 true, FD); 8166 else 8167 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8168 if (Comp.isInvalid()) 8169 return StmtError(); 8170 Sema::ConditionResult Cond = S.ActOnCondition( 8171 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8172 if (Cond.isInvalid()) 8173 return StmtError(); 8174 8175 // return cmp; 8176 VDRef = getDecl(VD); 8177 if (VDRef.isInvalid()) 8178 return StmtError(); 8179 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8180 if (ReturnStmt.isInvalid()) 8181 return StmtError(); 8182 8183 // if (...) 8184 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8185 ReturnStmt.get(), 8186 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8187 } 8188 8189 case DefaultedComparisonKind::NotEqual: 8190 case DefaultedComparisonKind::Relational: 8191 // C++2a [class.compare.secondary]p2: 8192 // Otherwise, the operator function yields x @ y. 8193 return Op.get(); 8194 } 8195 llvm_unreachable(""); 8196 } 8197 8198 /// Build "static_cast<R>(E)". 8199 ExprResult buildStaticCastToR(Expr *E) { 8200 QualType R = FD->getReturnType(); 8201 assert(!R->isUndeducedType() && "type should have been deduced already"); 8202 8203 // Don't bother forming a no-op cast in the common case. 8204 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8205 return E; 8206 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8207 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8208 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8209 } 8210 }; 8211 } 8212 8213 /// Perform the unqualified lookups that might be needed to form a defaulted 8214 /// comparison function for the given operator. 8215 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8216 UnresolvedSetImpl &Operators, 8217 OverloadedOperatorKind Op) { 8218 auto Lookup = [&](OverloadedOperatorKind OO) { 8219 Self.LookupOverloadedOperatorName(OO, S, Operators); 8220 }; 8221 8222 // Every defaulted operator looks up itself. 8223 Lookup(Op); 8224 // ... and the rewritten form of itself, if any. 8225 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8226 Lookup(ExtraOp); 8227 8228 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8229 // synthesize a three-way comparison from '<' and '=='. In a dependent 8230 // context, we also need to look up '==' in case we implicitly declare a 8231 // defaulted 'operator=='. 8232 if (Op == OO_Spaceship) { 8233 Lookup(OO_ExclaimEqual); 8234 Lookup(OO_Less); 8235 Lookup(OO_EqualEqual); 8236 } 8237 } 8238 8239 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8240 DefaultedComparisonKind DCK) { 8241 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8242 8243 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8244 assert(RD && "defaulted comparison is not defaulted in a class"); 8245 8246 // Perform any unqualified lookups we're going to need to default this 8247 // function. 8248 if (S) { 8249 UnresolvedSet<32> Operators; 8250 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8251 FD->getOverloadedOperator()); 8252 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8253 Context, Operators.pairs())); 8254 } 8255 8256 // C++2a [class.compare.default]p1: 8257 // A defaulted comparison operator function for some class C shall be a 8258 // non-template function declared in the member-specification of C that is 8259 // -- a non-static const member of C having one parameter of type 8260 // const C&, or 8261 // -- a friend of C having two parameters of type const C& or two 8262 // parameters of type C. 8263 QualType ExpectedParmType1 = Context.getRecordType(RD); 8264 QualType ExpectedParmType2 = 8265 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8266 if (isa<CXXMethodDecl>(FD)) 8267 ExpectedParmType1 = ExpectedParmType2; 8268 for (const ParmVarDecl *Param : FD->parameters()) { 8269 if (!Param->getType()->isDependentType() && 8270 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8271 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8272 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8273 // corresponding defaulted 'operator<=>' already. 8274 if (!FD->isImplicit()) { 8275 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8276 << (int)DCK << Param->getType() << ExpectedParmType1 8277 << !isa<CXXMethodDecl>(FD) 8278 << ExpectedParmType2 << Param->getSourceRange(); 8279 } 8280 return true; 8281 } 8282 } 8283 if (FD->getNumParams() == 2 && 8284 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8285 FD->getParamDecl(1)->getType())) { 8286 if (!FD->isImplicit()) { 8287 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8288 << (int)DCK 8289 << FD->getParamDecl(0)->getType() 8290 << FD->getParamDecl(0)->getSourceRange() 8291 << FD->getParamDecl(1)->getType() 8292 << FD->getParamDecl(1)->getSourceRange(); 8293 } 8294 return true; 8295 } 8296 8297 // ... non-static const member ... 8298 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8299 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8300 if (!MD->isConst()) { 8301 SourceLocation InsertLoc; 8302 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8303 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8304 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8305 // corresponding defaulted 'operator<=>' already. 8306 if (!MD->isImplicit()) { 8307 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8308 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8309 } 8310 8311 // Add the 'const' to the type to recover. 8312 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8313 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8314 EPI.TypeQuals.addConst(); 8315 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8316 FPT->getParamTypes(), EPI)); 8317 } 8318 } else { 8319 // A non-member function declared in a class must be a friend. 8320 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8321 } 8322 8323 // C++2a [class.eq]p1, [class.rel]p1: 8324 // A [defaulted comparison other than <=>] shall have a declared return 8325 // type bool. 8326 if (DCK != DefaultedComparisonKind::ThreeWay && 8327 !FD->getDeclaredReturnType()->isDependentType() && 8328 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8329 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8330 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8331 << FD->getReturnTypeSourceRange(); 8332 return true; 8333 } 8334 // C++2a [class.spaceship]p2 [P2002R0]: 8335 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8336 // R shall not contain a placeholder type. 8337 if (DCK == DefaultedComparisonKind::ThreeWay && 8338 FD->getDeclaredReturnType()->getContainedDeducedType() && 8339 !Context.hasSameType(FD->getDeclaredReturnType(), 8340 Context.getAutoDeductType())) { 8341 Diag(FD->getLocation(), 8342 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8343 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8344 << FD->getReturnTypeSourceRange(); 8345 return true; 8346 } 8347 8348 // For a defaulted function in a dependent class, defer all remaining checks 8349 // until instantiation. 8350 if (RD->isDependentType()) 8351 return false; 8352 8353 // Determine whether the function should be defined as deleted. 8354 DefaultedComparisonInfo Info = 8355 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8356 8357 bool First = FD == FD->getCanonicalDecl(); 8358 8359 // If we want to delete the function, then do so; there's nothing else to 8360 // check in that case. 8361 if (Info.Deleted) { 8362 if (!First) { 8363 // C++11 [dcl.fct.def.default]p4: 8364 // [For a] user-provided explicitly-defaulted function [...] if such a 8365 // function is implicitly defined as deleted, the program is ill-formed. 8366 // 8367 // This is really just a consequence of the general rule that you can 8368 // only delete a function on its first declaration. 8369 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8370 << FD->isImplicit() << (int)DCK; 8371 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8372 DefaultedComparisonAnalyzer::ExplainDeleted) 8373 .visit(); 8374 return true; 8375 } 8376 8377 SetDeclDeleted(FD, FD->getLocation()); 8378 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8379 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8380 << (int)DCK; 8381 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8382 DefaultedComparisonAnalyzer::ExplainDeleted) 8383 .visit(); 8384 } 8385 return false; 8386 } 8387 8388 // C++2a [class.spaceship]p2: 8389 // The return type is deduced as the common comparison type of R0, R1, ... 8390 if (DCK == DefaultedComparisonKind::ThreeWay && 8391 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8392 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8393 if (RetLoc.isInvalid()) 8394 RetLoc = FD->getBeginLoc(); 8395 // FIXME: Should we really care whether we have the complete type and the 8396 // 'enumerator' constants here? A forward declaration seems sufficient. 8397 QualType Cat = CheckComparisonCategoryType( 8398 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8399 if (Cat.isNull()) 8400 return true; 8401 Context.adjustDeducedFunctionResultType( 8402 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8403 } 8404 8405 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8406 // An explicitly-defaulted function that is not defined as deleted may be 8407 // declared constexpr or consteval only if it is constexpr-compatible. 8408 // C++2a [class.compare.default]p3 [P2002R0]: 8409 // A defaulted comparison function is constexpr-compatible if it satisfies 8410 // the requirements for a constexpr function [...] 8411 // The only relevant requirements are that the parameter and return types are 8412 // literal types. The remaining conditions are checked by the analyzer. 8413 if (FD->isConstexpr()) { 8414 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8415 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8416 !Info.Constexpr) { 8417 Diag(FD->getBeginLoc(), 8418 diag::err_incorrect_defaulted_comparison_constexpr) 8419 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8420 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8421 DefaultedComparisonAnalyzer::ExplainConstexpr) 8422 .visit(); 8423 } 8424 } 8425 8426 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8427 // If a constexpr-compatible function is explicitly defaulted on its first 8428 // declaration, it is implicitly considered to be constexpr. 8429 // FIXME: Only applying this to the first declaration seems problematic, as 8430 // simple reorderings can affect the meaning of the program. 8431 if (First && !FD->isConstexpr() && Info.Constexpr) 8432 FD->setConstexprKind(CSK_constexpr); 8433 8434 // C++2a [except.spec]p3: 8435 // If a declaration of a function does not have a noexcept-specifier 8436 // [and] is defaulted on its first declaration, [...] the exception 8437 // specification is as specified below 8438 if (FD->getExceptionSpecType() == EST_None) { 8439 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8440 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8441 EPI.ExceptionSpec.Type = EST_Unevaluated; 8442 EPI.ExceptionSpec.SourceDecl = FD; 8443 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8444 FPT->getParamTypes(), EPI)); 8445 } 8446 8447 return false; 8448 } 8449 8450 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8451 FunctionDecl *Spaceship) { 8452 Sema::CodeSynthesisContext Ctx; 8453 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8454 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8455 Ctx.Entity = Spaceship; 8456 pushCodeSynthesisContext(Ctx); 8457 8458 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8459 EqualEqual->setImplicit(); 8460 8461 popCodeSynthesisContext(); 8462 } 8463 8464 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8465 DefaultedComparisonKind DCK) { 8466 assert(FD->isDefaulted() && !FD->isDeleted() && 8467 !FD->doesThisDeclarationHaveABody()); 8468 if (FD->willHaveBody() || FD->isInvalidDecl()) 8469 return; 8470 8471 SynthesizedFunctionScope Scope(*this, FD); 8472 8473 // Add a context note for diagnostics produced after this point. 8474 Scope.addContextNote(UseLoc); 8475 8476 { 8477 // Build and set up the function body. 8478 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8479 SourceLocation BodyLoc = 8480 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8481 StmtResult Body = 8482 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8483 if (Body.isInvalid()) { 8484 FD->setInvalidDecl(); 8485 return; 8486 } 8487 FD->setBody(Body.get()); 8488 FD->markUsed(Context); 8489 } 8490 8491 // The exception specification is needed because we are defining the 8492 // function. Note that this will reuse the body we just built. 8493 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8494 8495 if (ASTMutationListener *L = getASTMutationListener()) 8496 L->CompletedImplicitDefinition(FD); 8497 } 8498 8499 static Sema::ImplicitExceptionSpecification 8500 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8501 FunctionDecl *FD, 8502 Sema::DefaultedComparisonKind DCK) { 8503 ComputingExceptionSpec CES(S, FD, Loc); 8504 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8505 8506 if (FD->isInvalidDecl()) 8507 return ExceptSpec; 8508 8509 // The common case is that we just defined the comparison function. In that 8510 // case, just look at whether the body can throw. 8511 if (FD->hasBody()) { 8512 ExceptSpec.CalledStmt(FD->getBody()); 8513 } else { 8514 // Otherwise, build a body so we can check it. This should ideally only 8515 // happen when we're not actually marking the function referenced. (This is 8516 // only really important for efficiency: we don't want to build and throw 8517 // away bodies for comparison functions more than we strictly need to.) 8518 8519 // Pretend to synthesize the function body in an unevaluated context. 8520 // Note that we can't actually just go ahead and define the function here: 8521 // we are not permitted to mark its callees as referenced. 8522 Sema::SynthesizedFunctionScope Scope(S, FD); 8523 EnterExpressionEvaluationContext Context( 8524 S, Sema::ExpressionEvaluationContext::Unevaluated); 8525 8526 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8527 SourceLocation BodyLoc = 8528 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8529 StmtResult Body = 8530 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8531 if (!Body.isInvalid()) 8532 ExceptSpec.CalledStmt(Body.get()); 8533 8534 // FIXME: Can we hold onto this body and just transform it to potentially 8535 // evaluated when we're asked to define the function rather than rebuilding 8536 // it? Either that, or we should only build the bits of the body that we 8537 // need (the expressions, not the statements). 8538 } 8539 8540 return ExceptSpec; 8541 } 8542 8543 void Sema::CheckDelayedMemberExceptionSpecs() { 8544 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8545 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8546 8547 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8548 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8549 8550 // Perform any deferred checking of exception specifications for virtual 8551 // destructors. 8552 for (auto &Check : Overriding) 8553 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8554 8555 // Perform any deferred checking of exception specifications for befriended 8556 // special members. 8557 for (auto &Check : Equivalent) 8558 CheckEquivalentExceptionSpec(Check.second, Check.first); 8559 } 8560 8561 namespace { 8562 /// CRTP base class for visiting operations performed by a special member 8563 /// function (or inherited constructor). 8564 template<typename Derived> 8565 struct SpecialMemberVisitor { 8566 Sema &S; 8567 CXXMethodDecl *MD; 8568 Sema::CXXSpecialMember CSM; 8569 Sema::InheritedConstructorInfo *ICI; 8570 8571 // Properties of the special member, computed for convenience. 8572 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8573 8574 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8575 Sema::InheritedConstructorInfo *ICI) 8576 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8577 switch (CSM) { 8578 case Sema::CXXDefaultConstructor: 8579 case Sema::CXXCopyConstructor: 8580 case Sema::CXXMoveConstructor: 8581 IsConstructor = true; 8582 break; 8583 case Sema::CXXCopyAssignment: 8584 case Sema::CXXMoveAssignment: 8585 IsAssignment = true; 8586 break; 8587 case Sema::CXXDestructor: 8588 break; 8589 case Sema::CXXInvalid: 8590 llvm_unreachable("invalid special member kind"); 8591 } 8592 8593 if (MD->getNumParams()) { 8594 if (const ReferenceType *RT = 8595 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8596 ConstArg = RT->getPointeeType().isConstQualified(); 8597 } 8598 } 8599 8600 Derived &getDerived() { return static_cast<Derived&>(*this); } 8601 8602 /// Is this a "move" special member? 8603 bool isMove() const { 8604 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8605 } 8606 8607 /// Look up the corresponding special member in the given class. 8608 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8609 unsigned Quals, bool IsMutable) { 8610 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8611 ConstArg && !IsMutable); 8612 } 8613 8614 /// Look up the constructor for the specified base class to see if it's 8615 /// overridden due to this being an inherited constructor. 8616 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8617 if (!ICI) 8618 return {}; 8619 assert(CSM == Sema::CXXDefaultConstructor); 8620 auto *BaseCtor = 8621 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8622 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8623 return MD; 8624 return {}; 8625 } 8626 8627 /// A base or member subobject. 8628 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8629 8630 /// Get the location to use for a subobject in diagnostics. 8631 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8632 // FIXME: For an indirect virtual base, the direct base leading to 8633 // the indirect virtual base would be a more useful choice. 8634 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8635 return B->getBaseTypeLoc(); 8636 else 8637 return Subobj.get<FieldDecl*>()->getLocation(); 8638 } 8639 8640 enum BasesToVisit { 8641 /// Visit all non-virtual (direct) bases. 8642 VisitNonVirtualBases, 8643 /// Visit all direct bases, virtual or not. 8644 VisitDirectBases, 8645 /// Visit all non-virtual bases, and all virtual bases if the class 8646 /// is not abstract. 8647 VisitPotentiallyConstructedBases, 8648 /// Visit all direct or virtual bases. 8649 VisitAllBases 8650 }; 8651 8652 // Visit the bases and members of the class. 8653 bool visit(BasesToVisit Bases) { 8654 CXXRecordDecl *RD = MD->getParent(); 8655 8656 if (Bases == VisitPotentiallyConstructedBases) 8657 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8658 8659 for (auto &B : RD->bases()) 8660 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8661 getDerived().visitBase(&B)) 8662 return true; 8663 8664 if (Bases == VisitAllBases) 8665 for (auto &B : RD->vbases()) 8666 if (getDerived().visitBase(&B)) 8667 return true; 8668 8669 for (auto *F : RD->fields()) 8670 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8671 getDerived().visitField(F)) 8672 return true; 8673 8674 return false; 8675 } 8676 }; 8677 } 8678 8679 namespace { 8680 struct SpecialMemberDeletionInfo 8681 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8682 bool Diagnose; 8683 8684 SourceLocation Loc; 8685 8686 bool AllFieldsAreConst; 8687 8688 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8689 Sema::CXXSpecialMember CSM, 8690 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8691 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8692 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8693 8694 bool inUnion() const { return MD->getParent()->isUnion(); } 8695 8696 Sema::CXXSpecialMember getEffectiveCSM() { 8697 return ICI ? Sema::CXXInvalid : CSM; 8698 } 8699 8700 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8701 8702 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8703 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8704 8705 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8706 bool shouldDeleteForField(FieldDecl *FD); 8707 bool shouldDeleteForAllConstMembers(); 8708 8709 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8710 unsigned Quals); 8711 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8712 Sema::SpecialMemberOverloadResult SMOR, 8713 bool IsDtorCallInCtor); 8714 8715 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8716 }; 8717 } 8718 8719 /// Is the given special member inaccessible when used on the given 8720 /// sub-object. 8721 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8722 CXXMethodDecl *target) { 8723 /// If we're operating on a base class, the object type is the 8724 /// type of this special member. 8725 QualType objectTy; 8726 AccessSpecifier access = target->getAccess(); 8727 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8728 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8729 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8730 8731 // If we're operating on a field, the object type is the type of the field. 8732 } else { 8733 objectTy = S.Context.getTypeDeclType(target->getParent()); 8734 } 8735 8736 return S.isMemberAccessibleForDeletion( 8737 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8738 } 8739 8740 /// Check whether we should delete a special member due to the implicit 8741 /// definition containing a call to a special member of a subobject. 8742 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8743 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8744 bool IsDtorCallInCtor) { 8745 CXXMethodDecl *Decl = SMOR.getMethod(); 8746 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8747 8748 int DiagKind = -1; 8749 8750 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8751 DiagKind = !Decl ? 0 : 1; 8752 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8753 DiagKind = 2; 8754 else if (!isAccessible(Subobj, Decl)) 8755 DiagKind = 3; 8756 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8757 !Decl->isTrivial()) { 8758 // A member of a union must have a trivial corresponding special member. 8759 // As a weird special case, a destructor call from a union's constructor 8760 // must be accessible and non-deleted, but need not be trivial. Such a 8761 // destructor is never actually called, but is semantically checked as 8762 // if it were. 8763 DiagKind = 4; 8764 } 8765 8766 if (DiagKind == -1) 8767 return false; 8768 8769 if (Diagnose) { 8770 if (Field) { 8771 S.Diag(Field->getLocation(), 8772 diag::note_deleted_special_member_class_subobject) 8773 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8774 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8775 } else { 8776 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8777 S.Diag(Base->getBeginLoc(), 8778 diag::note_deleted_special_member_class_subobject) 8779 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8780 << Base->getType() << DiagKind << IsDtorCallInCtor 8781 << /*IsObjCPtr*/false; 8782 } 8783 8784 if (DiagKind == 1) 8785 S.NoteDeletedFunction(Decl); 8786 // FIXME: Explain inaccessibility if DiagKind == 3. 8787 } 8788 8789 return true; 8790 } 8791 8792 /// Check whether we should delete a special member function due to having a 8793 /// direct or virtual base class or non-static data member of class type M. 8794 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8795 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8796 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8797 bool IsMutable = Field && Field->isMutable(); 8798 8799 // C++11 [class.ctor]p5: 8800 // -- any direct or virtual base class, or non-static data member with no 8801 // brace-or-equal-initializer, has class type M (or array thereof) and 8802 // either M has no default constructor or overload resolution as applied 8803 // to M's default constructor results in an ambiguity or in a function 8804 // that is deleted or inaccessible 8805 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8806 // -- a direct or virtual base class B that cannot be copied/moved because 8807 // overload resolution, as applied to B's corresponding special member, 8808 // results in an ambiguity or a function that is deleted or inaccessible 8809 // from the defaulted special member 8810 // C++11 [class.dtor]p5: 8811 // -- any direct or virtual base class [...] has a type with a destructor 8812 // that is deleted or inaccessible 8813 if (!(CSM == Sema::CXXDefaultConstructor && 8814 Field && Field->hasInClassInitializer()) && 8815 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8816 false)) 8817 return true; 8818 8819 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8820 // -- any direct or virtual base class or non-static data member has a 8821 // type with a destructor that is deleted or inaccessible 8822 if (IsConstructor) { 8823 Sema::SpecialMemberOverloadResult SMOR = 8824 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8825 false, false, false, false, false); 8826 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8827 return true; 8828 } 8829 8830 return false; 8831 } 8832 8833 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8834 FieldDecl *FD, QualType FieldType) { 8835 // The defaulted special functions are defined as deleted if this is a variant 8836 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8837 // type under ARC. 8838 if (!FieldType.hasNonTrivialObjCLifetime()) 8839 return false; 8840 8841 // Don't make the defaulted default constructor defined as deleted if the 8842 // member has an in-class initializer. 8843 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8844 return false; 8845 8846 if (Diagnose) { 8847 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8848 S.Diag(FD->getLocation(), 8849 diag::note_deleted_special_member_class_subobject) 8850 << getEffectiveCSM() << ParentClass << /*IsField*/true 8851 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8852 } 8853 8854 return true; 8855 } 8856 8857 /// Check whether we should delete a special member function due to the class 8858 /// having a particular direct or virtual base class. 8859 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8860 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8861 // If program is correct, BaseClass cannot be null, but if it is, the error 8862 // must be reported elsewhere. 8863 if (!BaseClass) 8864 return false; 8865 // If we have an inheriting constructor, check whether we're calling an 8866 // inherited constructor instead of a default constructor. 8867 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8868 if (auto *BaseCtor = SMOR.getMethod()) { 8869 // Note that we do not check access along this path; other than that, 8870 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8871 // FIXME: Check that the base has a usable destructor! Sink this into 8872 // shouldDeleteForClassSubobject. 8873 if (BaseCtor->isDeleted() && Diagnose) { 8874 S.Diag(Base->getBeginLoc(), 8875 diag::note_deleted_special_member_class_subobject) 8876 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8877 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8878 << /*IsObjCPtr*/false; 8879 S.NoteDeletedFunction(BaseCtor); 8880 } 8881 return BaseCtor->isDeleted(); 8882 } 8883 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8884 } 8885 8886 /// Check whether we should delete a special member function due to the class 8887 /// having a particular non-static data member. 8888 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8889 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8890 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8891 8892 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8893 return true; 8894 8895 if (CSM == Sema::CXXDefaultConstructor) { 8896 // For a default constructor, all references must be initialized in-class 8897 // and, if a union, it must have a non-const member. 8898 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8899 if (Diagnose) 8900 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8901 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8902 return true; 8903 } 8904 // C++11 [class.ctor]p5: any non-variant non-static data member of 8905 // const-qualified type (or array thereof) with no 8906 // brace-or-equal-initializer does not have a user-provided default 8907 // constructor. 8908 if (!inUnion() && FieldType.isConstQualified() && 8909 !FD->hasInClassInitializer() && 8910 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8911 if (Diagnose) 8912 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8913 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8914 return true; 8915 } 8916 8917 if (inUnion() && !FieldType.isConstQualified()) 8918 AllFieldsAreConst = false; 8919 } else if (CSM == Sema::CXXCopyConstructor) { 8920 // For a copy constructor, data members must not be of rvalue reference 8921 // type. 8922 if (FieldType->isRValueReferenceType()) { 8923 if (Diagnose) 8924 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8925 << MD->getParent() << FD << FieldType; 8926 return true; 8927 } 8928 } else if (IsAssignment) { 8929 // For an assignment operator, data members must not be of reference type. 8930 if (FieldType->isReferenceType()) { 8931 if (Diagnose) 8932 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8933 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8934 return true; 8935 } 8936 if (!FieldRecord && FieldType.isConstQualified()) { 8937 // C++11 [class.copy]p23: 8938 // -- a non-static data member of const non-class type (or array thereof) 8939 if (Diagnose) 8940 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8941 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8942 return true; 8943 } 8944 } 8945 8946 if (FieldRecord) { 8947 // Some additional restrictions exist on the variant members. 8948 if (!inUnion() && FieldRecord->isUnion() && 8949 FieldRecord->isAnonymousStructOrUnion()) { 8950 bool AllVariantFieldsAreConst = true; 8951 8952 // FIXME: Handle anonymous unions declared within anonymous unions. 8953 for (auto *UI : FieldRecord->fields()) { 8954 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8955 8956 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8957 return true; 8958 8959 if (!UnionFieldType.isConstQualified()) 8960 AllVariantFieldsAreConst = false; 8961 8962 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8963 if (UnionFieldRecord && 8964 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8965 UnionFieldType.getCVRQualifiers())) 8966 return true; 8967 } 8968 8969 // At least one member in each anonymous union must be non-const 8970 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8971 !FieldRecord->field_empty()) { 8972 if (Diagnose) 8973 S.Diag(FieldRecord->getLocation(), 8974 diag::note_deleted_default_ctor_all_const) 8975 << !!ICI << MD->getParent() << /*anonymous union*/1; 8976 return true; 8977 } 8978 8979 // Don't check the implicit member of the anonymous union type. 8980 // This is technically non-conformant, but sanity demands it. 8981 return false; 8982 } 8983 8984 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8985 FieldType.getCVRQualifiers())) 8986 return true; 8987 } 8988 8989 return false; 8990 } 8991 8992 /// C++11 [class.ctor] p5: 8993 /// A defaulted default constructor for a class X is defined as deleted if 8994 /// X is a union and all of its variant members are of const-qualified type. 8995 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8996 // This is a silly definition, because it gives an empty union a deleted 8997 // default constructor. Don't do that. 8998 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 8999 bool AnyFields = false; 9000 for (auto *F : MD->getParent()->fields()) 9001 if ((AnyFields = !F->isUnnamedBitfield())) 9002 break; 9003 if (!AnyFields) 9004 return false; 9005 if (Diagnose) 9006 S.Diag(MD->getParent()->getLocation(), 9007 diag::note_deleted_default_ctor_all_const) 9008 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9009 return true; 9010 } 9011 return false; 9012 } 9013 9014 /// Determine whether a defaulted special member function should be defined as 9015 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9016 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9017 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9018 InheritedConstructorInfo *ICI, 9019 bool Diagnose) { 9020 if (MD->isInvalidDecl()) 9021 return false; 9022 CXXRecordDecl *RD = MD->getParent(); 9023 assert(!RD->isDependentType() && "do deletion after instantiation"); 9024 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9025 return false; 9026 9027 // C++11 [expr.lambda.prim]p19: 9028 // The closure type associated with a lambda-expression has a 9029 // deleted (8.4.3) default constructor and a deleted copy 9030 // assignment operator. 9031 // C++2a adds back these operators if the lambda has no lambda-capture. 9032 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9033 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9034 if (Diagnose) 9035 Diag(RD->getLocation(), diag::note_lambda_decl); 9036 return true; 9037 } 9038 9039 // For an anonymous struct or union, the copy and assignment special members 9040 // will never be used, so skip the check. For an anonymous union declared at 9041 // namespace scope, the constructor and destructor are used. 9042 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9043 RD->isAnonymousStructOrUnion()) 9044 return false; 9045 9046 // C++11 [class.copy]p7, p18: 9047 // If the class definition declares a move constructor or move assignment 9048 // operator, an implicitly declared copy constructor or copy assignment 9049 // operator is defined as deleted. 9050 if (MD->isImplicit() && 9051 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9052 CXXMethodDecl *UserDeclaredMove = nullptr; 9053 9054 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9055 // deletion of the corresponding copy operation, not both copy operations. 9056 // MSVC 2015 has adopted the standards conforming behavior. 9057 bool DeletesOnlyMatchingCopy = 9058 getLangOpts().MSVCCompat && 9059 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9060 9061 if (RD->hasUserDeclaredMoveConstructor() && 9062 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9063 if (!Diagnose) return true; 9064 9065 // Find any user-declared move constructor. 9066 for (auto *I : RD->ctors()) { 9067 if (I->isMoveConstructor()) { 9068 UserDeclaredMove = I; 9069 break; 9070 } 9071 } 9072 assert(UserDeclaredMove); 9073 } else if (RD->hasUserDeclaredMoveAssignment() && 9074 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9075 if (!Diagnose) return true; 9076 9077 // Find any user-declared move assignment operator. 9078 for (auto *I : RD->methods()) { 9079 if (I->isMoveAssignmentOperator()) { 9080 UserDeclaredMove = I; 9081 break; 9082 } 9083 } 9084 assert(UserDeclaredMove); 9085 } 9086 9087 if (UserDeclaredMove) { 9088 Diag(UserDeclaredMove->getLocation(), 9089 diag::note_deleted_copy_user_declared_move) 9090 << (CSM == CXXCopyAssignment) << RD 9091 << UserDeclaredMove->isMoveAssignmentOperator(); 9092 return true; 9093 } 9094 } 9095 9096 // Do access control from the special member function 9097 ContextRAII MethodContext(*this, MD); 9098 9099 // C++11 [class.dtor]p5: 9100 // -- for a virtual destructor, lookup of the non-array deallocation function 9101 // results in an ambiguity or in a function that is deleted or inaccessible 9102 if (CSM == CXXDestructor && MD->isVirtual()) { 9103 FunctionDecl *OperatorDelete = nullptr; 9104 DeclarationName Name = 9105 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9106 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9107 OperatorDelete, /*Diagnose*/false)) { 9108 if (Diagnose) 9109 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9110 return true; 9111 } 9112 } 9113 9114 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9115 9116 // Per DR1611, do not consider virtual bases of constructors of abstract 9117 // classes, since we are not going to construct them. 9118 // Per DR1658, do not consider virtual bases of destructors of abstract 9119 // classes either. 9120 // Per DR2180, for assignment operators we only assign (and thus only 9121 // consider) direct bases. 9122 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9123 : SMI.VisitPotentiallyConstructedBases)) 9124 return true; 9125 9126 if (SMI.shouldDeleteForAllConstMembers()) 9127 return true; 9128 9129 if (getLangOpts().CUDA) { 9130 // We should delete the special member in CUDA mode if target inference 9131 // failed. 9132 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9133 // is treated as certain special member, which may not reflect what special 9134 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9135 // expects CSM to match MD, therefore recalculate CSM. 9136 assert(ICI || CSM == getSpecialMember(MD)); 9137 auto RealCSM = CSM; 9138 if (ICI) 9139 RealCSM = getSpecialMember(MD); 9140 9141 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9142 SMI.ConstArg, Diagnose); 9143 } 9144 9145 return false; 9146 } 9147 9148 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9149 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9150 assert(DFK && "not a defaultable function"); 9151 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9152 9153 if (DFK.isSpecialMember()) { 9154 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9155 nullptr, /*Diagnose=*/true); 9156 } else { 9157 DefaultedComparisonAnalyzer( 9158 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9159 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9160 .visit(); 9161 } 9162 } 9163 9164 /// Perform lookup for a special member of the specified kind, and determine 9165 /// whether it is trivial. If the triviality can be determined without the 9166 /// lookup, skip it. This is intended for use when determining whether a 9167 /// special member of a containing object is trivial, and thus does not ever 9168 /// perform overload resolution for default constructors. 9169 /// 9170 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9171 /// member that was most likely to be intended to be trivial, if any. 9172 /// 9173 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9174 /// determine whether the special member is trivial. 9175 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9176 Sema::CXXSpecialMember CSM, unsigned Quals, 9177 bool ConstRHS, 9178 Sema::TrivialABIHandling TAH, 9179 CXXMethodDecl **Selected) { 9180 if (Selected) 9181 *Selected = nullptr; 9182 9183 switch (CSM) { 9184 case Sema::CXXInvalid: 9185 llvm_unreachable("not a special member"); 9186 9187 case Sema::CXXDefaultConstructor: 9188 // C++11 [class.ctor]p5: 9189 // A default constructor is trivial if: 9190 // - all the [direct subobjects] have trivial default constructors 9191 // 9192 // Note, no overload resolution is performed in this case. 9193 if (RD->hasTrivialDefaultConstructor()) 9194 return true; 9195 9196 if (Selected) { 9197 // If there's a default constructor which could have been trivial, dig it 9198 // out. Otherwise, if there's any user-provided default constructor, point 9199 // to that as an example of why there's not a trivial one. 9200 CXXConstructorDecl *DefCtor = nullptr; 9201 if (RD->needsImplicitDefaultConstructor()) 9202 S.DeclareImplicitDefaultConstructor(RD); 9203 for (auto *CI : RD->ctors()) { 9204 if (!CI->isDefaultConstructor()) 9205 continue; 9206 DefCtor = CI; 9207 if (!DefCtor->isUserProvided()) 9208 break; 9209 } 9210 9211 *Selected = DefCtor; 9212 } 9213 9214 return false; 9215 9216 case Sema::CXXDestructor: 9217 // C++11 [class.dtor]p5: 9218 // A destructor is trivial if: 9219 // - all the direct [subobjects] have trivial destructors 9220 if (RD->hasTrivialDestructor() || 9221 (TAH == Sema::TAH_ConsiderTrivialABI && 9222 RD->hasTrivialDestructorForCall())) 9223 return true; 9224 9225 if (Selected) { 9226 if (RD->needsImplicitDestructor()) 9227 S.DeclareImplicitDestructor(RD); 9228 *Selected = RD->getDestructor(); 9229 } 9230 9231 return false; 9232 9233 case Sema::CXXCopyConstructor: 9234 // C++11 [class.copy]p12: 9235 // A copy constructor is trivial if: 9236 // - the constructor selected to copy each direct [subobject] is trivial 9237 if (RD->hasTrivialCopyConstructor() || 9238 (TAH == Sema::TAH_ConsiderTrivialABI && 9239 RD->hasTrivialCopyConstructorForCall())) { 9240 if (Quals == Qualifiers::Const) 9241 // We must either select the trivial copy constructor or reach an 9242 // ambiguity; no need to actually perform overload resolution. 9243 return true; 9244 } else if (!Selected) { 9245 return false; 9246 } 9247 // In C++98, we are not supposed to perform overload resolution here, but we 9248 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9249 // cases like B as having a non-trivial copy constructor: 9250 // struct A { template<typename T> A(T&); }; 9251 // struct B { mutable A a; }; 9252 goto NeedOverloadResolution; 9253 9254 case Sema::CXXCopyAssignment: 9255 // C++11 [class.copy]p25: 9256 // A copy assignment operator is trivial if: 9257 // - the assignment operator selected to copy each direct [subobject] is 9258 // trivial 9259 if (RD->hasTrivialCopyAssignment()) { 9260 if (Quals == Qualifiers::Const) 9261 return true; 9262 } else if (!Selected) { 9263 return false; 9264 } 9265 // In C++98, we are not supposed to perform overload resolution here, but we 9266 // treat that as a language defect. 9267 goto NeedOverloadResolution; 9268 9269 case Sema::CXXMoveConstructor: 9270 case Sema::CXXMoveAssignment: 9271 NeedOverloadResolution: 9272 Sema::SpecialMemberOverloadResult SMOR = 9273 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9274 9275 // The standard doesn't describe how to behave if the lookup is ambiguous. 9276 // We treat it as not making the member non-trivial, just like the standard 9277 // mandates for the default constructor. This should rarely matter, because 9278 // the member will also be deleted. 9279 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9280 return true; 9281 9282 if (!SMOR.getMethod()) { 9283 assert(SMOR.getKind() == 9284 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9285 return false; 9286 } 9287 9288 // We deliberately don't check if we found a deleted special member. We're 9289 // not supposed to! 9290 if (Selected) 9291 *Selected = SMOR.getMethod(); 9292 9293 if (TAH == Sema::TAH_ConsiderTrivialABI && 9294 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9295 return SMOR.getMethod()->isTrivialForCall(); 9296 return SMOR.getMethod()->isTrivial(); 9297 } 9298 9299 llvm_unreachable("unknown special method kind"); 9300 } 9301 9302 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9303 for (auto *CI : RD->ctors()) 9304 if (!CI->isImplicit()) 9305 return CI; 9306 9307 // Look for constructor templates. 9308 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9309 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9310 if (CXXConstructorDecl *CD = 9311 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9312 return CD; 9313 } 9314 9315 return nullptr; 9316 } 9317 9318 /// The kind of subobject we are checking for triviality. The values of this 9319 /// enumeration are used in diagnostics. 9320 enum TrivialSubobjectKind { 9321 /// The subobject is a base class. 9322 TSK_BaseClass, 9323 /// The subobject is a non-static data member. 9324 TSK_Field, 9325 /// The object is actually the complete object. 9326 TSK_CompleteObject 9327 }; 9328 9329 /// Check whether the special member selected for a given type would be trivial. 9330 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9331 QualType SubType, bool ConstRHS, 9332 Sema::CXXSpecialMember CSM, 9333 TrivialSubobjectKind Kind, 9334 Sema::TrivialABIHandling TAH, bool Diagnose) { 9335 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9336 if (!SubRD) 9337 return true; 9338 9339 CXXMethodDecl *Selected; 9340 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9341 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9342 return true; 9343 9344 if (Diagnose) { 9345 if (ConstRHS) 9346 SubType.addConst(); 9347 9348 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9349 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9350 << Kind << SubType.getUnqualifiedType(); 9351 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9352 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9353 } else if (!Selected) 9354 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9355 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9356 else if (Selected->isUserProvided()) { 9357 if (Kind == TSK_CompleteObject) 9358 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9359 << Kind << SubType.getUnqualifiedType() << CSM; 9360 else { 9361 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9362 << Kind << SubType.getUnqualifiedType() << CSM; 9363 S.Diag(Selected->getLocation(), diag::note_declared_at); 9364 } 9365 } else { 9366 if (Kind != TSK_CompleteObject) 9367 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9368 << Kind << SubType.getUnqualifiedType() << CSM; 9369 9370 // Explain why the defaulted or deleted special member isn't trivial. 9371 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9372 Diagnose); 9373 } 9374 } 9375 9376 return false; 9377 } 9378 9379 /// Check whether the members of a class type allow a special member to be 9380 /// trivial. 9381 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9382 Sema::CXXSpecialMember CSM, 9383 bool ConstArg, 9384 Sema::TrivialABIHandling TAH, 9385 bool Diagnose) { 9386 for (const auto *FI : RD->fields()) { 9387 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9388 continue; 9389 9390 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9391 9392 // Pretend anonymous struct or union members are members of this class. 9393 if (FI->isAnonymousStructOrUnion()) { 9394 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9395 CSM, ConstArg, TAH, Diagnose)) 9396 return false; 9397 continue; 9398 } 9399 9400 // C++11 [class.ctor]p5: 9401 // A default constructor is trivial if [...] 9402 // -- no non-static data member of its class has a 9403 // brace-or-equal-initializer 9404 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9405 if (Diagnose) 9406 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9407 << FI; 9408 return false; 9409 } 9410 9411 // Objective C ARC 4.3.5: 9412 // [...] nontrivally ownership-qualified types are [...] not trivially 9413 // default constructible, copy constructible, move constructible, copy 9414 // assignable, move assignable, or destructible [...] 9415 if (FieldType.hasNonTrivialObjCLifetime()) { 9416 if (Diagnose) 9417 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9418 << RD << FieldType.getObjCLifetime(); 9419 return false; 9420 } 9421 9422 bool ConstRHS = ConstArg && !FI->isMutable(); 9423 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9424 CSM, TSK_Field, TAH, Diagnose)) 9425 return false; 9426 } 9427 9428 return true; 9429 } 9430 9431 /// Diagnose why the specified class does not have a trivial special member of 9432 /// the given kind. 9433 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9434 QualType Ty = Context.getRecordType(RD); 9435 9436 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9437 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9438 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9439 /*Diagnose*/true); 9440 } 9441 9442 /// Determine whether a defaulted or deleted special member function is trivial, 9443 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9444 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9445 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9446 TrivialABIHandling TAH, bool Diagnose) { 9447 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9448 9449 CXXRecordDecl *RD = MD->getParent(); 9450 9451 bool ConstArg = false; 9452 9453 // C++11 [class.copy]p12, p25: [DR1593] 9454 // A [special member] is trivial if [...] its parameter-type-list is 9455 // equivalent to the parameter-type-list of an implicit declaration [...] 9456 switch (CSM) { 9457 case CXXDefaultConstructor: 9458 case CXXDestructor: 9459 // Trivial default constructors and destructors cannot have parameters. 9460 break; 9461 9462 case CXXCopyConstructor: 9463 case CXXCopyAssignment: { 9464 // Trivial copy operations always have const, non-volatile parameter types. 9465 ConstArg = true; 9466 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9467 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9468 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9469 if (Diagnose) 9470 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9471 << Param0->getSourceRange() << Param0->getType() 9472 << Context.getLValueReferenceType( 9473 Context.getRecordType(RD).withConst()); 9474 return false; 9475 } 9476 break; 9477 } 9478 9479 case CXXMoveConstructor: 9480 case CXXMoveAssignment: { 9481 // Trivial move operations always have non-cv-qualified parameters. 9482 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9483 const RValueReferenceType *RT = 9484 Param0->getType()->getAs<RValueReferenceType>(); 9485 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9486 if (Diagnose) 9487 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9488 << Param0->getSourceRange() << Param0->getType() 9489 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9490 return false; 9491 } 9492 break; 9493 } 9494 9495 case CXXInvalid: 9496 llvm_unreachable("not a special member"); 9497 } 9498 9499 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9500 if (Diagnose) 9501 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9502 diag::note_nontrivial_default_arg) 9503 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9504 return false; 9505 } 9506 if (MD->isVariadic()) { 9507 if (Diagnose) 9508 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9509 return false; 9510 } 9511 9512 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9513 // A copy/move [constructor or assignment operator] is trivial if 9514 // -- the [member] selected to copy/move each direct base class subobject 9515 // is trivial 9516 // 9517 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9518 // A [default constructor or destructor] is trivial if 9519 // -- all the direct base classes have trivial [default constructors or 9520 // destructors] 9521 for (const auto &BI : RD->bases()) 9522 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9523 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9524 return false; 9525 9526 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9527 // A copy/move [constructor or assignment operator] for a class X is 9528 // trivial if 9529 // -- for each non-static data member of X that is of class type (or array 9530 // thereof), the constructor selected to copy/move that member is 9531 // trivial 9532 // 9533 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9534 // A [default constructor or destructor] is trivial if 9535 // -- for all of the non-static data members of its class that are of class 9536 // type (or array thereof), each such class has a trivial [default 9537 // constructor or destructor] 9538 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9539 return false; 9540 9541 // C++11 [class.dtor]p5: 9542 // A destructor is trivial if [...] 9543 // -- the destructor is not virtual 9544 if (CSM == CXXDestructor && MD->isVirtual()) { 9545 if (Diagnose) 9546 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9547 return false; 9548 } 9549 9550 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9551 // A [special member] for class X is trivial if [...] 9552 // -- class X has no virtual functions and no virtual base classes 9553 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9554 if (!Diagnose) 9555 return false; 9556 9557 if (RD->getNumVBases()) { 9558 // Check for virtual bases. We already know that the corresponding 9559 // member in all bases is trivial, so vbases must all be direct. 9560 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9561 assert(BS.isVirtual()); 9562 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9563 return false; 9564 } 9565 9566 // Must have a virtual method. 9567 for (const auto *MI : RD->methods()) { 9568 if (MI->isVirtual()) { 9569 SourceLocation MLoc = MI->getBeginLoc(); 9570 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9571 return false; 9572 } 9573 } 9574 9575 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9576 } 9577 9578 // Looks like it's trivial! 9579 return true; 9580 } 9581 9582 namespace { 9583 struct FindHiddenVirtualMethod { 9584 Sema *S; 9585 CXXMethodDecl *Method; 9586 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9587 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9588 9589 private: 9590 /// Check whether any most overridden method from MD in Methods 9591 static bool CheckMostOverridenMethods( 9592 const CXXMethodDecl *MD, 9593 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9594 if (MD->size_overridden_methods() == 0) 9595 return Methods.count(MD->getCanonicalDecl()); 9596 for (const CXXMethodDecl *O : MD->overridden_methods()) 9597 if (CheckMostOverridenMethods(O, Methods)) 9598 return true; 9599 return false; 9600 } 9601 9602 public: 9603 /// Member lookup function that determines whether a given C++ 9604 /// method overloads virtual methods in a base class without overriding any, 9605 /// to be used with CXXRecordDecl::lookupInBases(). 9606 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9607 RecordDecl *BaseRecord = 9608 Specifier->getType()->castAs<RecordType>()->getDecl(); 9609 9610 DeclarationName Name = Method->getDeclName(); 9611 assert(Name.getNameKind() == DeclarationName::Identifier); 9612 9613 bool foundSameNameMethod = false; 9614 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9615 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9616 Path.Decls = Path.Decls.slice(1)) { 9617 NamedDecl *D = Path.Decls.front(); 9618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9619 MD = MD->getCanonicalDecl(); 9620 foundSameNameMethod = true; 9621 // Interested only in hidden virtual methods. 9622 if (!MD->isVirtual()) 9623 continue; 9624 // If the method we are checking overrides a method from its base 9625 // don't warn about the other overloaded methods. Clang deviates from 9626 // GCC by only diagnosing overloads of inherited virtual functions that 9627 // do not override any other virtual functions in the base. GCC's 9628 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9629 // function from a base class. These cases may be better served by a 9630 // warning (not specific to virtual functions) on call sites when the 9631 // call would select a different function from the base class, were it 9632 // visible. 9633 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9634 if (!S->IsOverload(Method, MD, false)) 9635 return true; 9636 // Collect the overload only if its hidden. 9637 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9638 overloadedMethods.push_back(MD); 9639 } 9640 } 9641 9642 if (foundSameNameMethod) 9643 OverloadedMethods.append(overloadedMethods.begin(), 9644 overloadedMethods.end()); 9645 return foundSameNameMethod; 9646 } 9647 }; 9648 } // end anonymous namespace 9649 9650 /// Add the most overriden methods from MD to Methods 9651 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9652 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9653 if (MD->size_overridden_methods() == 0) 9654 Methods.insert(MD->getCanonicalDecl()); 9655 else 9656 for (const CXXMethodDecl *O : MD->overridden_methods()) 9657 AddMostOverridenMethods(O, Methods); 9658 } 9659 9660 /// Check if a method overloads virtual methods in a base class without 9661 /// overriding any. 9662 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9663 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9664 if (!MD->getDeclName().isIdentifier()) 9665 return; 9666 9667 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9668 /*bool RecordPaths=*/false, 9669 /*bool DetectVirtual=*/false); 9670 FindHiddenVirtualMethod FHVM; 9671 FHVM.Method = MD; 9672 FHVM.S = this; 9673 9674 // Keep the base methods that were overridden or introduced in the subclass 9675 // by 'using' in a set. A base method not in this set is hidden. 9676 CXXRecordDecl *DC = MD->getParent(); 9677 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9678 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9679 NamedDecl *ND = *I; 9680 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9681 ND = shad->getTargetDecl(); 9682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9683 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9684 } 9685 9686 if (DC->lookupInBases(FHVM, Paths)) 9687 OverloadedMethods = FHVM.OverloadedMethods; 9688 } 9689 9690 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9691 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9692 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9693 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9694 PartialDiagnostic PD = PDiag( 9695 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9696 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9697 Diag(overloadedMD->getLocation(), PD); 9698 } 9699 } 9700 9701 /// Diagnose methods which overload virtual methods in a base class 9702 /// without overriding any. 9703 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9704 if (MD->isInvalidDecl()) 9705 return; 9706 9707 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9708 return; 9709 9710 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9711 FindHiddenVirtualMethods(MD, OverloadedMethods); 9712 if (!OverloadedMethods.empty()) { 9713 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9714 << MD << (OverloadedMethods.size() > 1); 9715 9716 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9717 } 9718 } 9719 9720 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9721 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9722 // No diagnostics if this is a template instantiation. 9723 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9724 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9725 diag::ext_cannot_use_trivial_abi) << &RD; 9726 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9727 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9728 } 9729 RD.dropAttr<TrivialABIAttr>(); 9730 }; 9731 9732 // Ill-formed if the copy and move constructors are deleted. 9733 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9734 // If the type is dependent, then assume it might have 9735 // implicit copy or move ctor because we won't know yet at this point. 9736 if (RD.isDependentType()) 9737 return true; 9738 if (RD.needsImplicitCopyConstructor() && 9739 !RD.defaultedCopyConstructorIsDeleted()) 9740 return true; 9741 if (RD.needsImplicitMoveConstructor() && 9742 !RD.defaultedMoveConstructorIsDeleted()) 9743 return true; 9744 for (const CXXConstructorDecl *CD : RD.ctors()) 9745 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9746 return true; 9747 return false; 9748 }; 9749 9750 if (!HasNonDeletedCopyOrMoveConstructor()) { 9751 PrintDiagAndRemoveAttr(0); 9752 return; 9753 } 9754 9755 // Ill-formed if the struct has virtual functions. 9756 if (RD.isPolymorphic()) { 9757 PrintDiagAndRemoveAttr(1); 9758 return; 9759 } 9760 9761 for (const auto &B : RD.bases()) { 9762 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9763 // virtual base. 9764 if (!B.getType()->isDependentType() && 9765 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9766 PrintDiagAndRemoveAttr(2); 9767 return; 9768 } 9769 9770 if (B.isVirtual()) { 9771 PrintDiagAndRemoveAttr(3); 9772 return; 9773 } 9774 } 9775 9776 for (const auto *FD : RD.fields()) { 9777 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9778 // non-trivial for the purpose of calls. 9779 QualType FT = FD->getType(); 9780 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9781 PrintDiagAndRemoveAttr(4); 9782 return; 9783 } 9784 9785 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9786 if (!RT->isDependentType() && 9787 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9788 PrintDiagAndRemoveAttr(5); 9789 return; 9790 } 9791 } 9792 } 9793 9794 void Sema::ActOnFinishCXXMemberSpecification( 9795 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9796 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9797 if (!TagDecl) 9798 return; 9799 9800 AdjustDeclIfTemplate(TagDecl); 9801 9802 for (const ParsedAttr &AL : AttrList) { 9803 if (AL.getKind() != ParsedAttr::AT_Visibility) 9804 continue; 9805 AL.setInvalid(); 9806 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9807 } 9808 9809 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9810 // strict aliasing violation! 9811 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9812 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9813 9814 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9815 } 9816 9817 /// Find the equality comparison functions that should be implicitly declared 9818 /// in a given class definition, per C++2a [class.compare.default]p3. 9819 static void findImplicitlyDeclaredEqualityComparisons( 9820 ASTContext &Ctx, CXXRecordDecl *RD, 9821 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9822 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9823 if (!RD->lookup(EqEq).empty()) 9824 // Member operator== explicitly declared: no implicit operator==s. 9825 return; 9826 9827 // Traverse friends looking for an '==' or a '<=>'. 9828 for (FriendDecl *Friend : RD->friends()) { 9829 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9830 if (!FD) continue; 9831 9832 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9833 // Friend operator== explicitly declared: no implicit operator==s. 9834 Spaceships.clear(); 9835 return; 9836 } 9837 9838 if (FD->getOverloadedOperator() == OO_Spaceship && 9839 FD->isExplicitlyDefaulted()) 9840 Spaceships.push_back(FD); 9841 } 9842 9843 // Look for members named 'operator<=>'. 9844 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9845 for (NamedDecl *ND : RD->lookup(Cmp)) { 9846 // Note that we could find a non-function here (either a function template 9847 // or a using-declaration). Neither case results in an implicit 9848 // 'operator=='. 9849 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9850 if (FD->isExplicitlyDefaulted()) 9851 Spaceships.push_back(FD); 9852 } 9853 } 9854 9855 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9856 /// special functions, such as the default constructor, copy 9857 /// constructor, or destructor, to the given C++ class (C++ 9858 /// [special]p1). This routine can only be executed just before the 9859 /// definition of the class is complete. 9860 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9861 // Don't add implicit special members to templated classes. 9862 // FIXME: This means unqualified lookups for 'operator=' within a class 9863 // template don't work properly. 9864 if (!ClassDecl->isDependentType()) { 9865 if (ClassDecl->needsImplicitDefaultConstructor()) { 9866 ++getASTContext().NumImplicitDefaultConstructors; 9867 9868 if (ClassDecl->hasInheritedConstructor()) 9869 DeclareImplicitDefaultConstructor(ClassDecl); 9870 } 9871 9872 if (ClassDecl->needsImplicitCopyConstructor()) { 9873 ++getASTContext().NumImplicitCopyConstructors; 9874 9875 // If the properties or semantics of the copy constructor couldn't be 9876 // determined while the class was being declared, force a declaration 9877 // of it now. 9878 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9879 ClassDecl->hasInheritedConstructor()) 9880 DeclareImplicitCopyConstructor(ClassDecl); 9881 // For the MS ABI we need to know whether the copy ctor is deleted. A 9882 // prerequisite for deleting the implicit copy ctor is that the class has 9883 // a move ctor or move assignment that is either user-declared or whose 9884 // semantics are inherited from a subobject. FIXME: We should provide a 9885 // more direct way for CodeGen to ask whether the constructor was deleted. 9886 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9887 (ClassDecl->hasUserDeclaredMoveConstructor() || 9888 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9889 ClassDecl->hasUserDeclaredMoveAssignment() || 9890 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9891 DeclareImplicitCopyConstructor(ClassDecl); 9892 } 9893 9894 if (getLangOpts().CPlusPlus11 && 9895 ClassDecl->needsImplicitMoveConstructor()) { 9896 ++getASTContext().NumImplicitMoveConstructors; 9897 9898 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9899 ClassDecl->hasInheritedConstructor()) 9900 DeclareImplicitMoveConstructor(ClassDecl); 9901 } 9902 9903 if (ClassDecl->needsImplicitCopyAssignment()) { 9904 ++getASTContext().NumImplicitCopyAssignmentOperators; 9905 9906 // If we have a dynamic class, then the copy assignment operator may be 9907 // virtual, so we have to declare it immediately. This ensures that, e.g., 9908 // it shows up in the right place in the vtable and that we diagnose 9909 // problems with the implicit exception specification. 9910 if (ClassDecl->isDynamicClass() || 9911 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9912 ClassDecl->hasInheritedAssignment()) 9913 DeclareImplicitCopyAssignment(ClassDecl); 9914 } 9915 9916 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9917 ++getASTContext().NumImplicitMoveAssignmentOperators; 9918 9919 // Likewise for the move assignment operator. 9920 if (ClassDecl->isDynamicClass() || 9921 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9922 ClassDecl->hasInheritedAssignment()) 9923 DeclareImplicitMoveAssignment(ClassDecl); 9924 } 9925 9926 if (ClassDecl->needsImplicitDestructor()) { 9927 ++getASTContext().NumImplicitDestructors; 9928 9929 // If we have a dynamic class, then the destructor may be virtual, so we 9930 // have to declare the destructor immediately. This ensures that, e.g., it 9931 // shows up in the right place in the vtable and that we diagnose problems 9932 // with the implicit exception specification. 9933 if (ClassDecl->isDynamicClass() || 9934 ClassDecl->needsOverloadResolutionForDestructor()) 9935 DeclareImplicitDestructor(ClassDecl); 9936 } 9937 } 9938 9939 // C++2a [class.compare.default]p3: 9940 // If the member-specification does not explicitly declare any member or 9941 // friend named operator==, an == operator function is declared implicitly 9942 // for each defaulted three-way comparison operator function defined in 9943 // the member-specification 9944 // FIXME: Consider doing this lazily. 9945 // We do this during the initial parse for a class template, not during 9946 // instantiation, so that we can handle unqualified lookups for 'operator==' 9947 // when parsing the template. 9948 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 9949 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 9950 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9951 DefaultedSpaceships); 9952 for (auto *FD : DefaultedSpaceships) 9953 DeclareImplicitEqualityComparison(ClassDecl, FD); 9954 } 9955 } 9956 9957 unsigned 9958 Sema::ActOnReenterTemplateScope(Decl *D, 9959 llvm::function_ref<Scope *()> EnterScope) { 9960 if (!D) 9961 return 0; 9962 AdjustDeclIfTemplate(D); 9963 9964 // In order to get name lookup right, reenter template scopes in order from 9965 // outermost to innermost. 9966 SmallVector<TemplateParameterList *, 4> ParameterLists; 9967 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 9968 9969 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9970 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9971 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9972 9973 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9974 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9975 ParameterLists.push_back(FTD->getTemplateParameters()); 9976 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 9977 LookupDC = VD->getDeclContext(); 9978 9979 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 9980 ParameterLists.push_back(VTD->getTemplateParameters()); 9981 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 9982 ParameterLists.push_back(PSD->getTemplateParameters()); 9983 } 9984 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9985 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9986 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9987 9988 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9989 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9990 ParameterLists.push_back(CTD->getTemplateParameters()); 9991 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9992 ParameterLists.push_back(PSD->getTemplateParameters()); 9993 } 9994 } 9995 // FIXME: Alias declarations and concepts. 9996 9997 unsigned Count = 0; 9998 Scope *InnermostTemplateScope = nullptr; 9999 for (TemplateParameterList *Params : ParameterLists) { 10000 // Ignore explicit specializations; they don't contribute to the template 10001 // depth. 10002 if (Params->size() == 0) 10003 continue; 10004 10005 InnermostTemplateScope = EnterScope(); 10006 for (NamedDecl *Param : *Params) { 10007 if (Param->getDeclName()) { 10008 InnermostTemplateScope->AddDecl(Param); 10009 IdResolver.AddDecl(Param); 10010 } 10011 } 10012 ++Count; 10013 } 10014 10015 // Associate the new template scopes with the corresponding entities. 10016 if (InnermostTemplateScope) { 10017 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10018 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10019 } 10020 10021 return Count; 10022 } 10023 10024 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10025 if (!RecordD) return; 10026 AdjustDeclIfTemplate(RecordD); 10027 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10028 PushDeclContext(S, Record); 10029 } 10030 10031 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10032 if (!RecordD) return; 10033 PopDeclContext(); 10034 } 10035 10036 /// This is used to implement the constant expression evaluation part of the 10037 /// attribute enable_if extension. There is nothing in standard C++ which would 10038 /// require reentering parameters. 10039 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10040 if (!Param) 10041 return; 10042 10043 S->AddDecl(Param); 10044 if (Param->getDeclName()) 10045 IdResolver.AddDecl(Param); 10046 } 10047 10048 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10049 /// parsing a top-level (non-nested) C++ class, and we are now 10050 /// parsing those parts of the given Method declaration that could 10051 /// not be parsed earlier (C++ [class.mem]p2), such as default 10052 /// arguments. This action should enter the scope of the given 10053 /// Method declaration as if we had just parsed the qualified method 10054 /// name. However, it should not bring the parameters into scope; 10055 /// that will be performed by ActOnDelayedCXXMethodParameter. 10056 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10057 } 10058 10059 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10060 /// C++ method declaration. We're (re-)introducing the given 10061 /// function parameter into scope for use in parsing later parts of 10062 /// the method declaration. For example, we could see an 10063 /// ActOnParamDefaultArgument event for this parameter. 10064 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10065 if (!ParamD) 10066 return; 10067 10068 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10069 10070 S->AddDecl(Param); 10071 if (Param->getDeclName()) 10072 IdResolver.AddDecl(Param); 10073 } 10074 10075 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10076 /// processing the delayed method declaration for Method. The method 10077 /// declaration is now considered finished. There may be a separate 10078 /// ActOnStartOfFunctionDef action later (not necessarily 10079 /// immediately!) for this method, if it was also defined inside the 10080 /// class body. 10081 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10082 if (!MethodD) 10083 return; 10084 10085 AdjustDeclIfTemplate(MethodD); 10086 10087 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10088 10089 // Now that we have our default arguments, check the constructor 10090 // again. It could produce additional diagnostics or affect whether 10091 // the class has implicitly-declared destructors, among other 10092 // things. 10093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10094 CheckConstructor(Constructor); 10095 10096 // Check the default arguments, which we may have added. 10097 if (!Method->isInvalidDecl()) 10098 CheckCXXDefaultArguments(Method); 10099 } 10100 10101 // Emit the given diagnostic for each non-address-space qualifier. 10102 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10103 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10104 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10105 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10106 bool DiagOccured = false; 10107 FTI.MethodQualifiers->forEachQualifier( 10108 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10109 SourceLocation SL) { 10110 // This diagnostic should be emitted on any qualifier except an addr 10111 // space qualifier. However, forEachQualifier currently doesn't visit 10112 // addr space qualifiers, so there's no way to write this condition 10113 // right now; we just diagnose on everything. 10114 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10115 DiagOccured = true; 10116 }); 10117 if (DiagOccured) 10118 D.setInvalidType(); 10119 } 10120 } 10121 10122 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10123 /// the well-formedness of the constructor declarator @p D with type @p 10124 /// R. If there are any errors in the declarator, this routine will 10125 /// emit diagnostics and set the invalid bit to true. In any case, the type 10126 /// will be updated to reflect a well-formed type for the constructor and 10127 /// returned. 10128 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10129 StorageClass &SC) { 10130 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10131 10132 // C++ [class.ctor]p3: 10133 // A constructor shall not be virtual (10.3) or static (9.4). A 10134 // constructor can be invoked for a const, volatile or const 10135 // volatile object. A constructor shall not be declared const, 10136 // volatile, or const volatile (9.3.2). 10137 if (isVirtual) { 10138 if (!D.isInvalidType()) 10139 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10140 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10141 << SourceRange(D.getIdentifierLoc()); 10142 D.setInvalidType(); 10143 } 10144 if (SC == SC_Static) { 10145 if (!D.isInvalidType()) 10146 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10147 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10148 << SourceRange(D.getIdentifierLoc()); 10149 D.setInvalidType(); 10150 SC = SC_None; 10151 } 10152 10153 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10154 diagnoseIgnoredQualifiers( 10155 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10156 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10157 D.getDeclSpec().getRestrictSpecLoc(), 10158 D.getDeclSpec().getAtomicSpecLoc()); 10159 D.setInvalidType(); 10160 } 10161 10162 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10163 10164 // C++0x [class.ctor]p4: 10165 // A constructor shall not be declared with a ref-qualifier. 10166 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10167 if (FTI.hasRefQualifier()) { 10168 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10169 << FTI.RefQualifierIsLValueRef 10170 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10171 D.setInvalidType(); 10172 } 10173 10174 // Rebuild the function type "R" without any type qualifiers (in 10175 // case any of the errors above fired) and with "void" as the 10176 // return type, since constructors don't have return types. 10177 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10178 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10179 return R; 10180 10181 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10182 EPI.TypeQuals = Qualifiers(); 10183 EPI.RefQualifier = RQ_None; 10184 10185 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10186 } 10187 10188 /// CheckConstructor - Checks a fully-formed constructor for 10189 /// well-formedness, issuing any diagnostics required. Returns true if 10190 /// the constructor declarator is invalid. 10191 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10192 CXXRecordDecl *ClassDecl 10193 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10194 if (!ClassDecl) 10195 return Constructor->setInvalidDecl(); 10196 10197 // C++ [class.copy]p3: 10198 // A declaration of a constructor for a class X is ill-formed if 10199 // its first parameter is of type (optionally cv-qualified) X and 10200 // either there are no other parameters or else all other 10201 // parameters have default arguments. 10202 if (!Constructor->isInvalidDecl() && 10203 Constructor->hasOneParamOrDefaultArgs() && 10204 Constructor->getTemplateSpecializationKind() != 10205 TSK_ImplicitInstantiation) { 10206 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10207 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10208 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10209 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10210 const char *ConstRef 10211 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10212 : " const &"; 10213 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10214 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10215 10216 // FIXME: Rather that making the constructor invalid, we should endeavor 10217 // to fix the type. 10218 Constructor->setInvalidDecl(); 10219 } 10220 } 10221 } 10222 10223 /// CheckDestructor - Checks a fully-formed destructor definition for 10224 /// well-formedness, issuing any diagnostics required. Returns true 10225 /// on error. 10226 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10227 CXXRecordDecl *RD = Destructor->getParent(); 10228 10229 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10230 SourceLocation Loc; 10231 10232 if (!Destructor->isImplicit()) 10233 Loc = Destructor->getLocation(); 10234 else 10235 Loc = RD->getLocation(); 10236 10237 // If we have a virtual destructor, look up the deallocation function 10238 if (FunctionDecl *OperatorDelete = 10239 FindDeallocationFunctionForDestructor(Loc, RD)) { 10240 Expr *ThisArg = nullptr; 10241 10242 // If the notional 'delete this' expression requires a non-trivial 10243 // conversion from 'this' to the type of a destroying operator delete's 10244 // first parameter, perform that conversion now. 10245 if (OperatorDelete->isDestroyingOperatorDelete()) { 10246 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10247 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10248 // C++ [class.dtor]p13: 10249 // ... as if for the expression 'delete this' appearing in a 10250 // non-virtual destructor of the destructor's class. 10251 ContextRAII SwitchContext(*this, Destructor); 10252 ExprResult This = 10253 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10254 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10255 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10256 if (This.isInvalid()) { 10257 // FIXME: Register this as a context note so that it comes out 10258 // in the right order. 10259 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10260 return true; 10261 } 10262 ThisArg = This.get(); 10263 } 10264 } 10265 10266 DiagnoseUseOfDecl(OperatorDelete, Loc); 10267 MarkFunctionReferenced(Loc, OperatorDelete); 10268 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10269 } 10270 } 10271 10272 return false; 10273 } 10274 10275 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10276 /// the well-formednes of the destructor declarator @p D with type @p 10277 /// R. If there are any errors in the declarator, this routine will 10278 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10279 /// will be updated to reflect a well-formed type for the destructor and 10280 /// returned. 10281 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10282 StorageClass& SC) { 10283 // C++ [class.dtor]p1: 10284 // [...] A typedef-name that names a class is a class-name 10285 // (7.1.3); however, a typedef-name that names a class shall not 10286 // be used as the identifier in the declarator for a destructor 10287 // declaration. 10288 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10289 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10290 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10291 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10292 else if (const TemplateSpecializationType *TST = 10293 DeclaratorType->getAs<TemplateSpecializationType>()) 10294 if (TST->isTypeAlias()) 10295 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10296 << DeclaratorType << 1; 10297 10298 // C++ [class.dtor]p2: 10299 // A destructor is used to destroy objects of its class type. A 10300 // destructor takes no parameters, and no return type can be 10301 // specified for it (not even void). The address of a destructor 10302 // shall not be taken. A destructor shall not be static. A 10303 // destructor can be invoked for a const, volatile or const 10304 // volatile object. A destructor shall not be declared const, 10305 // volatile or const volatile (9.3.2). 10306 if (SC == SC_Static) { 10307 if (!D.isInvalidType()) 10308 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10309 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10310 << SourceRange(D.getIdentifierLoc()) 10311 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10312 10313 SC = SC_None; 10314 } 10315 if (!D.isInvalidType()) { 10316 // Destructors don't have return types, but the parser will 10317 // happily parse something like: 10318 // 10319 // class X { 10320 // float ~X(); 10321 // }; 10322 // 10323 // The return type will be eliminated later. 10324 if (D.getDeclSpec().hasTypeSpecifier()) 10325 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10326 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10327 << SourceRange(D.getIdentifierLoc()); 10328 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10329 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10330 SourceLocation(), 10331 D.getDeclSpec().getConstSpecLoc(), 10332 D.getDeclSpec().getVolatileSpecLoc(), 10333 D.getDeclSpec().getRestrictSpecLoc(), 10334 D.getDeclSpec().getAtomicSpecLoc()); 10335 D.setInvalidType(); 10336 } 10337 } 10338 10339 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10340 10341 // C++0x [class.dtor]p2: 10342 // A destructor shall not be declared with a ref-qualifier. 10343 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10344 if (FTI.hasRefQualifier()) { 10345 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10346 << FTI.RefQualifierIsLValueRef 10347 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10348 D.setInvalidType(); 10349 } 10350 10351 // Make sure we don't have any parameters. 10352 if (FTIHasNonVoidParameters(FTI)) { 10353 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10354 10355 // Delete the parameters. 10356 FTI.freeParams(); 10357 D.setInvalidType(); 10358 } 10359 10360 // Make sure the destructor isn't variadic. 10361 if (FTI.isVariadic) { 10362 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10363 D.setInvalidType(); 10364 } 10365 10366 // Rebuild the function type "R" without any type qualifiers or 10367 // parameters (in case any of the errors above fired) and with 10368 // "void" as the return type, since destructors don't have return 10369 // types. 10370 if (!D.isInvalidType()) 10371 return R; 10372 10373 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10374 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10375 EPI.Variadic = false; 10376 EPI.TypeQuals = Qualifiers(); 10377 EPI.RefQualifier = RQ_None; 10378 return Context.getFunctionType(Context.VoidTy, None, EPI); 10379 } 10380 10381 static void extendLeft(SourceRange &R, SourceRange Before) { 10382 if (Before.isInvalid()) 10383 return; 10384 R.setBegin(Before.getBegin()); 10385 if (R.getEnd().isInvalid()) 10386 R.setEnd(Before.getEnd()); 10387 } 10388 10389 static void extendRight(SourceRange &R, SourceRange After) { 10390 if (After.isInvalid()) 10391 return; 10392 if (R.getBegin().isInvalid()) 10393 R.setBegin(After.getBegin()); 10394 R.setEnd(After.getEnd()); 10395 } 10396 10397 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10398 /// well-formednes of the conversion function declarator @p D with 10399 /// type @p R. If there are any errors in the declarator, this routine 10400 /// will emit diagnostics and return true. Otherwise, it will return 10401 /// false. Either way, the type @p R will be updated to reflect a 10402 /// well-formed type for the conversion operator. 10403 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10404 StorageClass& SC) { 10405 // C++ [class.conv.fct]p1: 10406 // Neither parameter types nor return type can be specified. The 10407 // type of a conversion function (8.3.5) is "function taking no 10408 // parameter returning conversion-type-id." 10409 if (SC == SC_Static) { 10410 if (!D.isInvalidType()) 10411 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10412 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10413 << D.getName().getSourceRange(); 10414 D.setInvalidType(); 10415 SC = SC_None; 10416 } 10417 10418 TypeSourceInfo *ConvTSI = nullptr; 10419 QualType ConvType = 10420 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10421 10422 const DeclSpec &DS = D.getDeclSpec(); 10423 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10424 // Conversion functions don't have return types, but the parser will 10425 // happily parse something like: 10426 // 10427 // class X { 10428 // float operator bool(); 10429 // }; 10430 // 10431 // The return type will be changed later anyway. 10432 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10433 << SourceRange(DS.getTypeSpecTypeLoc()) 10434 << SourceRange(D.getIdentifierLoc()); 10435 D.setInvalidType(); 10436 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10437 // It's also plausible that the user writes type qualifiers in the wrong 10438 // place, such as: 10439 // struct S { const operator int(); }; 10440 // FIXME: we could provide a fixit to move the qualifiers onto the 10441 // conversion type. 10442 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10443 << SourceRange(D.getIdentifierLoc()) << 0; 10444 D.setInvalidType(); 10445 } 10446 10447 const auto *Proto = R->castAs<FunctionProtoType>(); 10448 10449 // Make sure we don't have any parameters. 10450 if (Proto->getNumParams() > 0) { 10451 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10452 10453 // Delete the parameters. 10454 D.getFunctionTypeInfo().freeParams(); 10455 D.setInvalidType(); 10456 } else if (Proto->isVariadic()) { 10457 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10458 D.setInvalidType(); 10459 } 10460 10461 // Diagnose "&operator bool()" and other such nonsense. This 10462 // is actually a gcc extension which we don't support. 10463 if (Proto->getReturnType() != ConvType) { 10464 bool NeedsTypedef = false; 10465 SourceRange Before, After; 10466 10467 // Walk the chunks and extract information on them for our diagnostic. 10468 bool PastFunctionChunk = false; 10469 for (auto &Chunk : D.type_objects()) { 10470 switch (Chunk.Kind) { 10471 case DeclaratorChunk::Function: 10472 if (!PastFunctionChunk) { 10473 if (Chunk.Fun.HasTrailingReturnType) { 10474 TypeSourceInfo *TRT = nullptr; 10475 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10476 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10477 } 10478 PastFunctionChunk = true; 10479 break; 10480 } 10481 LLVM_FALLTHROUGH; 10482 case DeclaratorChunk::Array: 10483 NeedsTypedef = true; 10484 extendRight(After, Chunk.getSourceRange()); 10485 break; 10486 10487 case DeclaratorChunk::Pointer: 10488 case DeclaratorChunk::BlockPointer: 10489 case DeclaratorChunk::Reference: 10490 case DeclaratorChunk::MemberPointer: 10491 case DeclaratorChunk::Pipe: 10492 extendLeft(Before, Chunk.getSourceRange()); 10493 break; 10494 10495 case DeclaratorChunk::Paren: 10496 extendLeft(Before, Chunk.Loc); 10497 extendRight(After, Chunk.EndLoc); 10498 break; 10499 } 10500 } 10501 10502 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10503 After.isValid() ? After.getBegin() : 10504 D.getIdentifierLoc(); 10505 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10506 DB << Before << After; 10507 10508 if (!NeedsTypedef) { 10509 DB << /*don't need a typedef*/0; 10510 10511 // If we can provide a correct fix-it hint, do so. 10512 if (After.isInvalid() && ConvTSI) { 10513 SourceLocation InsertLoc = 10514 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10515 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10516 << FixItHint::CreateInsertionFromRange( 10517 InsertLoc, CharSourceRange::getTokenRange(Before)) 10518 << FixItHint::CreateRemoval(Before); 10519 } 10520 } else if (!Proto->getReturnType()->isDependentType()) { 10521 DB << /*typedef*/1 << Proto->getReturnType(); 10522 } else if (getLangOpts().CPlusPlus11) { 10523 DB << /*alias template*/2 << Proto->getReturnType(); 10524 } else { 10525 DB << /*might not be fixable*/3; 10526 } 10527 10528 // Recover by incorporating the other type chunks into the result type. 10529 // Note, this does *not* change the name of the function. This is compatible 10530 // with the GCC extension: 10531 // struct S { &operator int(); } s; 10532 // int &r = s.operator int(); // ok in GCC 10533 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10534 ConvType = Proto->getReturnType(); 10535 } 10536 10537 // C++ [class.conv.fct]p4: 10538 // The conversion-type-id shall not represent a function type nor 10539 // an array type. 10540 if (ConvType->isArrayType()) { 10541 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10542 ConvType = Context.getPointerType(ConvType); 10543 D.setInvalidType(); 10544 } else if (ConvType->isFunctionType()) { 10545 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10546 ConvType = Context.getPointerType(ConvType); 10547 D.setInvalidType(); 10548 } 10549 10550 // Rebuild the function type "R" without any parameters (in case any 10551 // of the errors above fired) and with the conversion type as the 10552 // return type. 10553 if (D.isInvalidType()) 10554 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10555 10556 // C++0x explicit conversion operators. 10557 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10558 Diag(DS.getExplicitSpecLoc(), 10559 getLangOpts().CPlusPlus11 10560 ? diag::warn_cxx98_compat_explicit_conversion_functions 10561 : diag::ext_explicit_conversion_functions) 10562 << SourceRange(DS.getExplicitSpecRange()); 10563 } 10564 10565 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10566 /// the declaration of the given C++ conversion function. This routine 10567 /// is responsible for recording the conversion function in the C++ 10568 /// class, if possible. 10569 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10570 assert(Conversion && "Expected to receive a conversion function declaration"); 10571 10572 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10573 10574 // Make sure we aren't redeclaring the conversion function. 10575 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10576 // C++ [class.conv.fct]p1: 10577 // [...] A conversion function is never used to convert a 10578 // (possibly cv-qualified) object to the (possibly cv-qualified) 10579 // same object type (or a reference to it), to a (possibly 10580 // cv-qualified) base class of that type (or a reference to it), 10581 // or to (possibly cv-qualified) void. 10582 QualType ClassType 10583 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10584 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10585 ConvType = ConvTypeRef->getPointeeType(); 10586 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10587 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10588 /* Suppress diagnostics for instantiations. */; 10589 else if (Conversion->size_overridden_methods() != 0) 10590 /* Suppress diagnostics for overriding virtual function in a base class. */; 10591 else if (ConvType->isRecordType()) { 10592 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10593 if (ConvType == ClassType) 10594 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10595 << ClassType; 10596 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10597 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10598 << ClassType << ConvType; 10599 } else if (ConvType->isVoidType()) { 10600 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10601 << ClassType << ConvType; 10602 } 10603 10604 if (FunctionTemplateDecl *ConversionTemplate 10605 = Conversion->getDescribedFunctionTemplate()) 10606 return ConversionTemplate; 10607 10608 return Conversion; 10609 } 10610 10611 namespace { 10612 /// Utility class to accumulate and print a diagnostic listing the invalid 10613 /// specifier(s) on a declaration. 10614 struct BadSpecifierDiagnoser { 10615 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10616 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10617 ~BadSpecifierDiagnoser() { 10618 Diagnostic << Specifiers; 10619 } 10620 10621 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10622 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10623 } 10624 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10625 return check(SpecLoc, 10626 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10627 } 10628 void check(SourceLocation SpecLoc, const char *Spec) { 10629 if (SpecLoc.isInvalid()) return; 10630 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10631 if (!Specifiers.empty()) Specifiers += " "; 10632 Specifiers += Spec; 10633 } 10634 10635 Sema &S; 10636 Sema::SemaDiagnosticBuilder Diagnostic; 10637 std::string Specifiers; 10638 }; 10639 } 10640 10641 /// Check the validity of a declarator that we parsed for a deduction-guide. 10642 /// These aren't actually declarators in the grammar, so we need to check that 10643 /// the user didn't specify any pieces that are not part of the deduction-guide 10644 /// grammar. 10645 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10646 StorageClass &SC) { 10647 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10648 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10649 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10650 10651 // C++ [temp.deduct.guide]p3: 10652 // A deduction-gide shall be declared in the same scope as the 10653 // corresponding class template. 10654 if (!CurContext->getRedeclContext()->Equals( 10655 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10656 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10657 << GuidedTemplateDecl; 10658 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10659 } 10660 10661 auto &DS = D.getMutableDeclSpec(); 10662 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10663 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10664 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10665 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10666 BadSpecifierDiagnoser Diagnoser( 10667 *this, D.getIdentifierLoc(), 10668 diag::err_deduction_guide_invalid_specifier); 10669 10670 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10671 DS.ClearStorageClassSpecs(); 10672 SC = SC_None; 10673 10674 // 'explicit' is permitted. 10675 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10676 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10677 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10678 DS.ClearConstexprSpec(); 10679 10680 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10681 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10682 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10683 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10684 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10685 DS.ClearTypeQualifiers(); 10686 10687 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10688 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10689 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10690 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10691 DS.ClearTypeSpecType(); 10692 } 10693 10694 if (D.isInvalidType()) 10695 return; 10696 10697 // Check the declarator is simple enough. 10698 bool FoundFunction = false; 10699 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10700 if (Chunk.Kind == DeclaratorChunk::Paren) 10701 continue; 10702 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10703 Diag(D.getDeclSpec().getBeginLoc(), 10704 diag::err_deduction_guide_with_complex_decl) 10705 << D.getSourceRange(); 10706 break; 10707 } 10708 if (!Chunk.Fun.hasTrailingReturnType()) { 10709 Diag(D.getName().getBeginLoc(), 10710 diag::err_deduction_guide_no_trailing_return_type); 10711 break; 10712 } 10713 10714 // Check that the return type is written as a specialization of 10715 // the template specified as the deduction-guide's name. 10716 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10717 TypeSourceInfo *TSI = nullptr; 10718 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10719 assert(TSI && "deduction guide has valid type but invalid return type?"); 10720 bool AcceptableReturnType = false; 10721 bool MightInstantiateToSpecialization = false; 10722 if (auto RetTST = 10723 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10724 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10725 bool TemplateMatches = 10726 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10727 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10728 AcceptableReturnType = true; 10729 else { 10730 // This could still instantiate to the right type, unless we know it 10731 // names the wrong class template. 10732 auto *TD = SpecifiedName.getAsTemplateDecl(); 10733 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10734 !TemplateMatches); 10735 } 10736 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10737 MightInstantiateToSpecialization = true; 10738 } 10739 10740 if (!AcceptableReturnType) { 10741 Diag(TSI->getTypeLoc().getBeginLoc(), 10742 diag::err_deduction_guide_bad_trailing_return_type) 10743 << GuidedTemplate << TSI->getType() 10744 << MightInstantiateToSpecialization 10745 << TSI->getTypeLoc().getSourceRange(); 10746 } 10747 10748 // Keep going to check that we don't have any inner declarator pieces (we 10749 // could still have a function returning a pointer to a function). 10750 FoundFunction = true; 10751 } 10752 10753 if (D.isFunctionDefinition()) 10754 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10755 } 10756 10757 //===----------------------------------------------------------------------===// 10758 // Namespace Handling 10759 //===----------------------------------------------------------------------===// 10760 10761 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10762 /// reopened. 10763 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10764 SourceLocation Loc, 10765 IdentifierInfo *II, bool *IsInline, 10766 NamespaceDecl *PrevNS) { 10767 assert(*IsInline != PrevNS->isInline()); 10768 10769 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10770 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10771 // inline namespaces, with the intention of bringing names into namespace std. 10772 // 10773 // We support this just well enough to get that case working; this is not 10774 // sufficient to support reopening namespaces as inline in general. 10775 if (*IsInline && II && II->getName().startswith("__atomic") && 10776 S.getSourceManager().isInSystemHeader(Loc)) { 10777 // Mark all prior declarations of the namespace as inline. 10778 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10779 NS = NS->getPreviousDecl()) 10780 NS->setInline(*IsInline); 10781 // Patch up the lookup table for the containing namespace. This isn't really 10782 // correct, but it's good enough for this particular case. 10783 for (auto *I : PrevNS->decls()) 10784 if (auto *ND = dyn_cast<NamedDecl>(I)) 10785 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10786 return; 10787 } 10788 10789 if (PrevNS->isInline()) 10790 // The user probably just forgot the 'inline', so suggest that it 10791 // be added back. 10792 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10793 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10794 else 10795 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10796 10797 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10798 *IsInline = PrevNS->isInline(); 10799 } 10800 10801 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10802 /// definition. 10803 Decl *Sema::ActOnStartNamespaceDef( 10804 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10805 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10806 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10807 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10808 // For anonymous namespace, take the location of the left brace. 10809 SourceLocation Loc = II ? IdentLoc : LBrace; 10810 bool IsInline = InlineLoc.isValid(); 10811 bool IsInvalid = false; 10812 bool IsStd = false; 10813 bool AddToKnown = false; 10814 Scope *DeclRegionScope = NamespcScope->getParent(); 10815 10816 NamespaceDecl *PrevNS = nullptr; 10817 if (II) { 10818 // C++ [namespace.def]p2: 10819 // The identifier in an original-namespace-definition shall not 10820 // have been previously defined in the declarative region in 10821 // which the original-namespace-definition appears. The 10822 // identifier in an original-namespace-definition is the name of 10823 // the namespace. Subsequently in that declarative region, it is 10824 // treated as an original-namespace-name. 10825 // 10826 // Since namespace names are unique in their scope, and we don't 10827 // look through using directives, just look for any ordinary names 10828 // as if by qualified name lookup. 10829 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10830 ForExternalRedeclaration); 10831 LookupQualifiedName(R, CurContext->getRedeclContext()); 10832 NamedDecl *PrevDecl = 10833 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10834 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10835 10836 if (PrevNS) { 10837 // This is an extended namespace definition. 10838 if (IsInline != PrevNS->isInline()) 10839 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10840 &IsInline, PrevNS); 10841 } else if (PrevDecl) { 10842 // This is an invalid name redefinition. 10843 Diag(Loc, diag::err_redefinition_different_kind) 10844 << II; 10845 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10846 IsInvalid = true; 10847 // Continue on to push Namespc as current DeclContext and return it. 10848 } else if (II->isStr("std") && 10849 CurContext->getRedeclContext()->isTranslationUnit()) { 10850 // This is the first "real" definition of the namespace "std", so update 10851 // our cache of the "std" namespace to point at this definition. 10852 PrevNS = getStdNamespace(); 10853 IsStd = true; 10854 AddToKnown = !IsInline; 10855 } else { 10856 // We've seen this namespace for the first time. 10857 AddToKnown = !IsInline; 10858 } 10859 } else { 10860 // Anonymous namespaces. 10861 10862 // Determine whether the parent already has an anonymous namespace. 10863 DeclContext *Parent = CurContext->getRedeclContext(); 10864 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10865 PrevNS = TU->getAnonymousNamespace(); 10866 } else { 10867 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10868 PrevNS = ND->getAnonymousNamespace(); 10869 } 10870 10871 if (PrevNS && IsInline != PrevNS->isInline()) 10872 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10873 &IsInline, PrevNS); 10874 } 10875 10876 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10877 StartLoc, Loc, II, PrevNS); 10878 if (IsInvalid) 10879 Namespc->setInvalidDecl(); 10880 10881 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10882 AddPragmaAttributes(DeclRegionScope, Namespc); 10883 10884 // FIXME: Should we be merging attributes? 10885 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10886 PushNamespaceVisibilityAttr(Attr, Loc); 10887 10888 if (IsStd) 10889 StdNamespace = Namespc; 10890 if (AddToKnown) 10891 KnownNamespaces[Namespc] = false; 10892 10893 if (II) { 10894 PushOnScopeChains(Namespc, DeclRegionScope); 10895 } else { 10896 // Link the anonymous namespace into its parent. 10897 DeclContext *Parent = CurContext->getRedeclContext(); 10898 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10899 TU->setAnonymousNamespace(Namespc); 10900 } else { 10901 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10902 } 10903 10904 CurContext->addDecl(Namespc); 10905 10906 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10907 // behaves as if it were replaced by 10908 // namespace unique { /* empty body */ } 10909 // using namespace unique; 10910 // namespace unique { namespace-body } 10911 // where all occurrences of 'unique' in a translation unit are 10912 // replaced by the same identifier and this identifier differs 10913 // from all other identifiers in the entire program. 10914 10915 // We just create the namespace with an empty name and then add an 10916 // implicit using declaration, just like the standard suggests. 10917 // 10918 // CodeGen enforces the "universally unique" aspect by giving all 10919 // declarations semantically contained within an anonymous 10920 // namespace internal linkage. 10921 10922 if (!PrevNS) { 10923 UD = UsingDirectiveDecl::Create(Context, Parent, 10924 /* 'using' */ LBrace, 10925 /* 'namespace' */ SourceLocation(), 10926 /* qualifier */ NestedNameSpecifierLoc(), 10927 /* identifier */ SourceLocation(), 10928 Namespc, 10929 /* Ancestor */ Parent); 10930 UD->setImplicit(); 10931 Parent->addDecl(UD); 10932 } 10933 } 10934 10935 ActOnDocumentableDecl(Namespc); 10936 10937 // Although we could have an invalid decl (i.e. the namespace name is a 10938 // redefinition), push it as current DeclContext and try to continue parsing. 10939 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10940 // for the namespace has the declarations that showed up in that particular 10941 // namespace definition. 10942 PushDeclContext(NamespcScope, Namespc); 10943 return Namespc; 10944 } 10945 10946 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10947 /// is a namespace alias, returns the namespace it points to. 10948 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10949 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10950 return AD->getNamespace(); 10951 return dyn_cast_or_null<NamespaceDecl>(D); 10952 } 10953 10954 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10955 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10956 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10957 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10958 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10959 Namespc->setRBraceLoc(RBrace); 10960 PopDeclContext(); 10961 if (Namespc->hasAttr<VisibilityAttr>()) 10962 PopPragmaVisibility(true, RBrace); 10963 // If this namespace contains an export-declaration, export it now. 10964 if (DeferredExportedNamespaces.erase(Namespc)) 10965 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10966 } 10967 10968 CXXRecordDecl *Sema::getStdBadAlloc() const { 10969 return cast_or_null<CXXRecordDecl>( 10970 StdBadAlloc.get(Context.getExternalSource())); 10971 } 10972 10973 EnumDecl *Sema::getStdAlignValT() const { 10974 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10975 } 10976 10977 NamespaceDecl *Sema::getStdNamespace() const { 10978 return cast_or_null<NamespaceDecl>( 10979 StdNamespace.get(Context.getExternalSource())); 10980 } 10981 10982 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10983 if (!StdExperimentalNamespaceCache) { 10984 if (auto Std = getStdNamespace()) { 10985 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10986 SourceLocation(), LookupNamespaceName); 10987 if (!LookupQualifiedName(Result, Std) || 10988 !(StdExperimentalNamespaceCache = 10989 Result.getAsSingle<NamespaceDecl>())) 10990 Result.suppressDiagnostics(); 10991 } 10992 } 10993 return StdExperimentalNamespaceCache; 10994 } 10995 10996 namespace { 10997 10998 enum UnsupportedSTLSelect { 10999 USS_InvalidMember, 11000 USS_MissingMember, 11001 USS_NonTrivial, 11002 USS_Other 11003 }; 11004 11005 struct InvalidSTLDiagnoser { 11006 Sema &S; 11007 SourceLocation Loc; 11008 QualType TyForDiags; 11009 11010 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11011 const VarDecl *VD = nullptr) { 11012 { 11013 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11014 << TyForDiags << ((int)Sel); 11015 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11016 assert(!Name.empty()); 11017 D << Name; 11018 } 11019 } 11020 if (Sel == USS_InvalidMember) { 11021 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11022 << VD << VD->getSourceRange(); 11023 } 11024 return QualType(); 11025 } 11026 }; 11027 } // namespace 11028 11029 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11030 SourceLocation Loc, 11031 ComparisonCategoryUsage Usage) { 11032 assert(getLangOpts().CPlusPlus && 11033 "Looking for comparison category type outside of C++."); 11034 11035 // Use an elaborated type for diagnostics which has a name containing the 11036 // prepended 'std' namespace but not any inline namespace names. 11037 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11038 auto *NNS = 11039 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11040 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11041 }; 11042 11043 // Check if we've already successfully checked the comparison category type 11044 // before. If so, skip checking it again. 11045 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11046 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11047 // The only thing we need to check is that the type has a reachable 11048 // definition in the current context. 11049 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11050 return QualType(); 11051 11052 return Info->getType(); 11053 } 11054 11055 // If lookup failed 11056 if (!Info) { 11057 std::string NameForDiags = "std::"; 11058 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11059 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11060 << NameForDiags << (int)Usage; 11061 return QualType(); 11062 } 11063 11064 assert(Info->Kind == Kind); 11065 assert(Info->Record); 11066 11067 // Update the Record decl in case we encountered a forward declaration on our 11068 // first pass. FIXME: This is a bit of a hack. 11069 if (Info->Record->hasDefinition()) 11070 Info->Record = Info->Record->getDefinition(); 11071 11072 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11073 return QualType(); 11074 11075 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11076 11077 if (!Info->Record->isTriviallyCopyable()) 11078 return UnsupportedSTLError(USS_NonTrivial); 11079 11080 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11081 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11082 // Tolerate empty base classes. 11083 if (Base->isEmpty()) 11084 continue; 11085 // Reject STL implementations which have at least one non-empty base. 11086 return UnsupportedSTLError(); 11087 } 11088 11089 // Check that the STL has implemented the types using a single integer field. 11090 // This expectation allows better codegen for builtin operators. We require: 11091 // (1) The class has exactly one field. 11092 // (2) The field is an integral or enumeration type. 11093 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11094 if (std::distance(FIt, FEnd) != 1 || 11095 !FIt->getType()->isIntegralOrEnumerationType()) { 11096 return UnsupportedSTLError(); 11097 } 11098 11099 // Build each of the require values and store them in Info. 11100 for (ComparisonCategoryResult CCR : 11101 ComparisonCategories::getPossibleResultsForType(Kind)) { 11102 StringRef MemName = ComparisonCategories::getResultString(CCR); 11103 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11104 11105 if (!ValInfo) 11106 return UnsupportedSTLError(USS_MissingMember, MemName); 11107 11108 VarDecl *VD = ValInfo->VD; 11109 assert(VD && "should not be null!"); 11110 11111 // Attempt to diagnose reasons why the STL definition of this type 11112 // might be foobar, including it failing to be a constant expression. 11113 // TODO Handle more ways the lookup or result can be invalid. 11114 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 11115 VD->isWeak() || !VD->checkInitIsICE()) 11116 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11117 11118 // Attempt to evaluate the var decl as a constant expression and extract 11119 // the value of its first field as a ICE. If this fails, the STL 11120 // implementation is not supported. 11121 if (!ValInfo->hasValidIntValue()) 11122 return UnsupportedSTLError(); 11123 11124 MarkVariableReferenced(Loc, VD); 11125 } 11126 11127 // We've successfully built the required types and expressions. Update 11128 // the cache and return the newly cached value. 11129 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11130 return Info->getType(); 11131 } 11132 11133 /// Retrieve the special "std" namespace, which may require us to 11134 /// implicitly define the namespace. 11135 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11136 if (!StdNamespace) { 11137 // The "std" namespace has not yet been defined, so build one implicitly. 11138 StdNamespace = NamespaceDecl::Create(Context, 11139 Context.getTranslationUnitDecl(), 11140 /*Inline=*/false, 11141 SourceLocation(), SourceLocation(), 11142 &PP.getIdentifierTable().get("std"), 11143 /*PrevDecl=*/nullptr); 11144 getStdNamespace()->setImplicit(true); 11145 } 11146 11147 return getStdNamespace(); 11148 } 11149 11150 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11151 assert(getLangOpts().CPlusPlus && 11152 "Looking for std::initializer_list outside of C++."); 11153 11154 // We're looking for implicit instantiations of 11155 // template <typename E> class std::initializer_list. 11156 11157 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11158 return false; 11159 11160 ClassTemplateDecl *Template = nullptr; 11161 const TemplateArgument *Arguments = nullptr; 11162 11163 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11164 11165 ClassTemplateSpecializationDecl *Specialization = 11166 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11167 if (!Specialization) 11168 return false; 11169 11170 Template = Specialization->getSpecializedTemplate(); 11171 Arguments = Specialization->getTemplateArgs().data(); 11172 } else if (const TemplateSpecializationType *TST = 11173 Ty->getAs<TemplateSpecializationType>()) { 11174 Template = dyn_cast_or_null<ClassTemplateDecl>( 11175 TST->getTemplateName().getAsTemplateDecl()); 11176 Arguments = TST->getArgs(); 11177 } 11178 if (!Template) 11179 return false; 11180 11181 if (!StdInitializerList) { 11182 // Haven't recognized std::initializer_list yet, maybe this is it. 11183 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11184 if (TemplateClass->getIdentifier() != 11185 &PP.getIdentifierTable().get("initializer_list") || 11186 !getStdNamespace()->InEnclosingNamespaceSetOf( 11187 TemplateClass->getDeclContext())) 11188 return false; 11189 // This is a template called std::initializer_list, but is it the right 11190 // template? 11191 TemplateParameterList *Params = Template->getTemplateParameters(); 11192 if (Params->getMinRequiredArguments() != 1) 11193 return false; 11194 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11195 return false; 11196 11197 // It's the right template. 11198 StdInitializerList = Template; 11199 } 11200 11201 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11202 return false; 11203 11204 // This is an instance of std::initializer_list. Find the argument type. 11205 if (Element) 11206 *Element = Arguments[0].getAsType(); 11207 return true; 11208 } 11209 11210 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11211 NamespaceDecl *Std = S.getStdNamespace(); 11212 if (!Std) { 11213 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11214 return nullptr; 11215 } 11216 11217 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11218 Loc, Sema::LookupOrdinaryName); 11219 if (!S.LookupQualifiedName(Result, Std)) { 11220 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11221 return nullptr; 11222 } 11223 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11224 if (!Template) { 11225 Result.suppressDiagnostics(); 11226 // We found something weird. Complain about the first thing we found. 11227 NamedDecl *Found = *Result.begin(); 11228 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11229 return nullptr; 11230 } 11231 11232 // We found some template called std::initializer_list. Now verify that it's 11233 // correct. 11234 TemplateParameterList *Params = Template->getTemplateParameters(); 11235 if (Params->getMinRequiredArguments() != 1 || 11236 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11237 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11238 return nullptr; 11239 } 11240 11241 return Template; 11242 } 11243 11244 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11245 if (!StdInitializerList) { 11246 StdInitializerList = LookupStdInitializerList(*this, Loc); 11247 if (!StdInitializerList) 11248 return QualType(); 11249 } 11250 11251 TemplateArgumentListInfo Args(Loc, Loc); 11252 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11253 Context.getTrivialTypeSourceInfo(Element, 11254 Loc))); 11255 return Context.getCanonicalType( 11256 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11257 } 11258 11259 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11260 // C++ [dcl.init.list]p2: 11261 // A constructor is an initializer-list constructor if its first parameter 11262 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11263 // std::initializer_list<E> for some type E, and either there are no other 11264 // parameters or else all other parameters have default arguments. 11265 if (!Ctor->hasOneParamOrDefaultArgs()) 11266 return false; 11267 11268 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11269 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11270 ArgType = RT->getPointeeType().getUnqualifiedType(); 11271 11272 return isStdInitializerList(ArgType, nullptr); 11273 } 11274 11275 /// Determine whether a using statement is in a context where it will be 11276 /// apply in all contexts. 11277 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11278 switch (CurContext->getDeclKind()) { 11279 case Decl::TranslationUnit: 11280 return true; 11281 case Decl::LinkageSpec: 11282 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11283 default: 11284 return false; 11285 } 11286 } 11287 11288 namespace { 11289 11290 // Callback to only accept typo corrections that are namespaces. 11291 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11292 public: 11293 bool ValidateCandidate(const TypoCorrection &candidate) override { 11294 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11295 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11296 return false; 11297 } 11298 11299 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11300 return std::make_unique<NamespaceValidatorCCC>(*this); 11301 } 11302 }; 11303 11304 } 11305 11306 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11307 CXXScopeSpec &SS, 11308 SourceLocation IdentLoc, 11309 IdentifierInfo *Ident) { 11310 R.clear(); 11311 NamespaceValidatorCCC CCC{}; 11312 if (TypoCorrection Corrected = 11313 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11314 Sema::CTK_ErrorRecovery)) { 11315 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11316 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11317 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11318 Ident->getName().equals(CorrectedStr); 11319 S.diagnoseTypo(Corrected, 11320 S.PDiag(diag::err_using_directive_member_suggest) 11321 << Ident << DC << DroppedSpecifier << SS.getRange(), 11322 S.PDiag(diag::note_namespace_defined_here)); 11323 } else { 11324 S.diagnoseTypo(Corrected, 11325 S.PDiag(diag::err_using_directive_suggest) << Ident, 11326 S.PDiag(diag::note_namespace_defined_here)); 11327 } 11328 R.addDecl(Corrected.getFoundDecl()); 11329 return true; 11330 } 11331 return false; 11332 } 11333 11334 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11335 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11336 SourceLocation IdentLoc, 11337 IdentifierInfo *NamespcName, 11338 const ParsedAttributesView &AttrList) { 11339 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11340 assert(NamespcName && "Invalid NamespcName."); 11341 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11342 11343 // This can only happen along a recovery path. 11344 while (S->isTemplateParamScope()) 11345 S = S->getParent(); 11346 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11347 11348 UsingDirectiveDecl *UDir = nullptr; 11349 NestedNameSpecifier *Qualifier = nullptr; 11350 if (SS.isSet()) 11351 Qualifier = SS.getScopeRep(); 11352 11353 // Lookup namespace name. 11354 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11355 LookupParsedName(R, S, &SS); 11356 if (R.isAmbiguous()) 11357 return nullptr; 11358 11359 if (R.empty()) { 11360 R.clear(); 11361 // Allow "using namespace std;" or "using namespace ::std;" even if 11362 // "std" hasn't been defined yet, for GCC compatibility. 11363 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11364 NamespcName->isStr("std")) { 11365 Diag(IdentLoc, diag::ext_using_undefined_std); 11366 R.addDecl(getOrCreateStdNamespace()); 11367 R.resolveKind(); 11368 } 11369 // Otherwise, attempt typo correction. 11370 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11371 } 11372 11373 if (!R.empty()) { 11374 NamedDecl *Named = R.getRepresentativeDecl(); 11375 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11376 assert(NS && "expected namespace decl"); 11377 11378 // The use of a nested name specifier may trigger deprecation warnings. 11379 DiagnoseUseOfDecl(Named, IdentLoc); 11380 11381 // C++ [namespace.udir]p1: 11382 // A using-directive specifies that the names in the nominated 11383 // namespace can be used in the scope in which the 11384 // using-directive appears after the using-directive. During 11385 // unqualified name lookup (3.4.1), the names appear as if they 11386 // were declared in the nearest enclosing namespace which 11387 // contains both the using-directive and the nominated 11388 // namespace. [Note: in this context, "contains" means "contains 11389 // directly or indirectly". ] 11390 11391 // Find enclosing context containing both using-directive and 11392 // nominated namespace. 11393 DeclContext *CommonAncestor = NS; 11394 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11395 CommonAncestor = CommonAncestor->getParent(); 11396 11397 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11398 SS.getWithLocInContext(Context), 11399 IdentLoc, Named, CommonAncestor); 11400 11401 if (IsUsingDirectiveInToplevelContext(CurContext) && 11402 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11403 Diag(IdentLoc, diag::warn_using_directive_in_header); 11404 } 11405 11406 PushUsingDirective(S, UDir); 11407 } else { 11408 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11409 } 11410 11411 if (UDir) 11412 ProcessDeclAttributeList(S, UDir, AttrList); 11413 11414 return UDir; 11415 } 11416 11417 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11418 // If the scope has an associated entity and the using directive is at 11419 // namespace or translation unit scope, add the UsingDirectiveDecl into 11420 // its lookup structure so qualified name lookup can find it. 11421 DeclContext *Ctx = S->getEntity(); 11422 if (Ctx && !Ctx->isFunctionOrMethod()) 11423 Ctx->addDecl(UDir); 11424 else 11425 // Otherwise, it is at block scope. The using-directives will affect lookup 11426 // only to the end of the scope. 11427 S->PushUsingDirective(UDir); 11428 } 11429 11430 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11431 SourceLocation UsingLoc, 11432 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11433 UnqualifiedId &Name, 11434 SourceLocation EllipsisLoc, 11435 const ParsedAttributesView &AttrList) { 11436 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11437 11438 if (SS.isEmpty()) { 11439 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11440 return nullptr; 11441 } 11442 11443 switch (Name.getKind()) { 11444 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11445 case UnqualifiedIdKind::IK_Identifier: 11446 case UnqualifiedIdKind::IK_OperatorFunctionId: 11447 case UnqualifiedIdKind::IK_LiteralOperatorId: 11448 case UnqualifiedIdKind::IK_ConversionFunctionId: 11449 break; 11450 11451 case UnqualifiedIdKind::IK_ConstructorName: 11452 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11453 // C++11 inheriting constructors. 11454 Diag(Name.getBeginLoc(), 11455 getLangOpts().CPlusPlus11 11456 ? diag::warn_cxx98_compat_using_decl_constructor 11457 : diag::err_using_decl_constructor) 11458 << SS.getRange(); 11459 11460 if (getLangOpts().CPlusPlus11) break; 11461 11462 return nullptr; 11463 11464 case UnqualifiedIdKind::IK_DestructorName: 11465 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11466 return nullptr; 11467 11468 case UnqualifiedIdKind::IK_TemplateId: 11469 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11470 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11471 return nullptr; 11472 11473 case UnqualifiedIdKind::IK_DeductionGuideName: 11474 llvm_unreachable("cannot parse qualified deduction guide name"); 11475 } 11476 11477 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11478 DeclarationName TargetName = TargetNameInfo.getName(); 11479 if (!TargetName) 11480 return nullptr; 11481 11482 // Warn about access declarations. 11483 if (UsingLoc.isInvalid()) { 11484 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11485 ? diag::err_access_decl 11486 : diag::warn_access_decl_deprecated) 11487 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11488 } 11489 11490 if (EllipsisLoc.isInvalid()) { 11491 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11492 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11493 return nullptr; 11494 } else { 11495 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11496 !TargetNameInfo.containsUnexpandedParameterPack()) { 11497 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11498 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11499 EllipsisLoc = SourceLocation(); 11500 } 11501 } 11502 11503 NamedDecl *UD = 11504 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11505 SS, TargetNameInfo, EllipsisLoc, AttrList, 11506 /*IsInstantiation*/false); 11507 if (UD) 11508 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11509 11510 return UD; 11511 } 11512 11513 /// Determine whether a using declaration considers the given 11514 /// declarations as "equivalent", e.g., if they are redeclarations of 11515 /// the same entity or are both typedefs of the same type. 11516 static bool 11517 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11518 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11519 return true; 11520 11521 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11522 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11523 return Context.hasSameType(TD1->getUnderlyingType(), 11524 TD2->getUnderlyingType()); 11525 11526 return false; 11527 } 11528 11529 11530 /// Determines whether to create a using shadow decl for a particular 11531 /// decl, given the set of decls existing prior to this using lookup. 11532 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11533 const LookupResult &Previous, 11534 UsingShadowDecl *&PrevShadow) { 11535 // Diagnose finding a decl which is not from a base class of the 11536 // current class. We do this now because there are cases where this 11537 // function will silently decide not to build a shadow decl, which 11538 // will pre-empt further diagnostics. 11539 // 11540 // We don't need to do this in C++11 because we do the check once on 11541 // the qualifier. 11542 // 11543 // FIXME: diagnose the following if we care enough: 11544 // struct A { int foo; }; 11545 // struct B : A { using A::foo; }; 11546 // template <class T> struct C : A {}; 11547 // template <class T> struct D : C<T> { using B::foo; } // <--- 11548 // This is invalid (during instantiation) in C++03 because B::foo 11549 // resolves to the using decl in B, which is not a base class of D<T>. 11550 // We can't diagnose it immediately because C<T> is an unknown 11551 // specialization. The UsingShadowDecl in D<T> then points directly 11552 // to A::foo, which will look well-formed when we instantiate. 11553 // The right solution is to not collapse the shadow-decl chain. 11554 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11555 DeclContext *OrigDC = Orig->getDeclContext(); 11556 11557 // Handle enums and anonymous structs. 11558 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11559 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11560 while (OrigRec->isAnonymousStructOrUnion()) 11561 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11562 11563 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11564 if (OrigDC == CurContext) { 11565 Diag(Using->getLocation(), 11566 diag::err_using_decl_nested_name_specifier_is_current_class) 11567 << Using->getQualifierLoc().getSourceRange(); 11568 Diag(Orig->getLocation(), diag::note_using_decl_target); 11569 Using->setInvalidDecl(); 11570 return true; 11571 } 11572 11573 Diag(Using->getQualifierLoc().getBeginLoc(), 11574 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11575 << Using->getQualifier() 11576 << cast<CXXRecordDecl>(CurContext) 11577 << Using->getQualifierLoc().getSourceRange(); 11578 Diag(Orig->getLocation(), diag::note_using_decl_target); 11579 Using->setInvalidDecl(); 11580 return true; 11581 } 11582 } 11583 11584 if (Previous.empty()) return false; 11585 11586 NamedDecl *Target = Orig; 11587 if (isa<UsingShadowDecl>(Target)) 11588 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11589 11590 // If the target happens to be one of the previous declarations, we 11591 // don't have a conflict. 11592 // 11593 // FIXME: but we might be increasing its access, in which case we 11594 // should redeclare it. 11595 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11596 bool FoundEquivalentDecl = false; 11597 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11598 I != E; ++I) { 11599 NamedDecl *D = (*I)->getUnderlyingDecl(); 11600 // We can have UsingDecls in our Previous results because we use the same 11601 // LookupResult for checking whether the UsingDecl itself is a valid 11602 // redeclaration. 11603 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11604 continue; 11605 11606 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11607 // C++ [class.mem]p19: 11608 // If T is the name of a class, then [every named member other than 11609 // a non-static data member] shall have a name different from T 11610 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11611 !isa<IndirectFieldDecl>(Target) && 11612 !isa<UnresolvedUsingValueDecl>(Target) && 11613 DiagnoseClassNameShadow( 11614 CurContext, 11615 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11616 return true; 11617 } 11618 11619 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11620 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11621 PrevShadow = Shadow; 11622 FoundEquivalentDecl = true; 11623 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11624 // We don't conflict with an existing using shadow decl of an equivalent 11625 // declaration, but we're not a redeclaration of it. 11626 FoundEquivalentDecl = true; 11627 } 11628 11629 if (isVisible(D)) 11630 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11631 } 11632 11633 if (FoundEquivalentDecl) 11634 return false; 11635 11636 if (FunctionDecl *FD = Target->getAsFunction()) { 11637 NamedDecl *OldDecl = nullptr; 11638 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11639 /*IsForUsingDecl*/ true)) { 11640 case Ovl_Overload: 11641 return false; 11642 11643 case Ovl_NonFunction: 11644 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11645 break; 11646 11647 // We found a decl with the exact signature. 11648 case Ovl_Match: 11649 // If we're in a record, we want to hide the target, so we 11650 // return true (without a diagnostic) to tell the caller not to 11651 // build a shadow decl. 11652 if (CurContext->isRecord()) 11653 return true; 11654 11655 // If we're not in a record, this is an error. 11656 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11657 break; 11658 } 11659 11660 Diag(Target->getLocation(), diag::note_using_decl_target); 11661 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11662 Using->setInvalidDecl(); 11663 return true; 11664 } 11665 11666 // Target is not a function. 11667 11668 if (isa<TagDecl>(Target)) { 11669 // No conflict between a tag and a non-tag. 11670 if (!Tag) return false; 11671 11672 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11673 Diag(Target->getLocation(), diag::note_using_decl_target); 11674 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11675 Using->setInvalidDecl(); 11676 return true; 11677 } 11678 11679 // No conflict between a tag and a non-tag. 11680 if (!NonTag) return false; 11681 11682 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11683 Diag(Target->getLocation(), diag::note_using_decl_target); 11684 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11685 Using->setInvalidDecl(); 11686 return true; 11687 } 11688 11689 /// Determine whether a direct base class is a virtual base class. 11690 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11691 if (!Derived->getNumVBases()) 11692 return false; 11693 for (auto &B : Derived->bases()) 11694 if (B.getType()->getAsCXXRecordDecl() == Base) 11695 return B.isVirtual(); 11696 llvm_unreachable("not a direct base class"); 11697 } 11698 11699 /// Builds a shadow declaration corresponding to a 'using' declaration. 11700 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11701 UsingDecl *UD, 11702 NamedDecl *Orig, 11703 UsingShadowDecl *PrevDecl) { 11704 // If we resolved to another shadow declaration, just coalesce them. 11705 NamedDecl *Target = Orig; 11706 if (isa<UsingShadowDecl>(Target)) { 11707 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11708 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11709 } 11710 11711 NamedDecl *NonTemplateTarget = Target; 11712 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11713 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11714 11715 UsingShadowDecl *Shadow; 11716 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11717 bool IsVirtualBase = 11718 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11719 UD->getQualifier()->getAsRecordDecl()); 11720 Shadow = ConstructorUsingShadowDecl::Create( 11721 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11722 } else { 11723 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11724 Target); 11725 } 11726 UD->addShadowDecl(Shadow); 11727 11728 Shadow->setAccess(UD->getAccess()); 11729 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11730 Shadow->setInvalidDecl(); 11731 11732 Shadow->setPreviousDecl(PrevDecl); 11733 11734 if (S) 11735 PushOnScopeChains(Shadow, S); 11736 else 11737 CurContext->addDecl(Shadow); 11738 11739 11740 return Shadow; 11741 } 11742 11743 /// Hides a using shadow declaration. This is required by the current 11744 /// using-decl implementation when a resolvable using declaration in a 11745 /// class is followed by a declaration which would hide or override 11746 /// one or more of the using decl's targets; for example: 11747 /// 11748 /// struct Base { void foo(int); }; 11749 /// struct Derived : Base { 11750 /// using Base::foo; 11751 /// void foo(int); 11752 /// }; 11753 /// 11754 /// The governing language is C++03 [namespace.udecl]p12: 11755 /// 11756 /// When a using-declaration brings names from a base class into a 11757 /// derived class scope, member functions in the derived class 11758 /// override and/or hide member functions with the same name and 11759 /// parameter types in a base class (rather than conflicting). 11760 /// 11761 /// There are two ways to implement this: 11762 /// (1) optimistically create shadow decls when they're not hidden 11763 /// by existing declarations, or 11764 /// (2) don't create any shadow decls (or at least don't make them 11765 /// visible) until we've fully parsed/instantiated the class. 11766 /// The problem with (1) is that we might have to retroactively remove 11767 /// a shadow decl, which requires several O(n) operations because the 11768 /// decl structures are (very reasonably) not designed for removal. 11769 /// (2) avoids this but is very fiddly and phase-dependent. 11770 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11771 if (Shadow->getDeclName().getNameKind() == 11772 DeclarationName::CXXConversionFunctionName) 11773 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11774 11775 // Remove it from the DeclContext... 11776 Shadow->getDeclContext()->removeDecl(Shadow); 11777 11778 // ...and the scope, if applicable... 11779 if (S) { 11780 S->RemoveDecl(Shadow); 11781 IdResolver.RemoveDecl(Shadow); 11782 } 11783 11784 // ...and the using decl. 11785 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11786 11787 // TODO: complain somehow if Shadow was used. It shouldn't 11788 // be possible for this to happen, because...? 11789 } 11790 11791 /// Find the base specifier for a base class with the given type. 11792 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11793 QualType DesiredBase, 11794 bool &AnyDependentBases) { 11795 // Check whether the named type is a direct base class. 11796 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11797 .getUnqualifiedType(); 11798 for (auto &Base : Derived->bases()) { 11799 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11800 if (CanonicalDesiredBase == BaseType) 11801 return &Base; 11802 if (BaseType->isDependentType()) 11803 AnyDependentBases = true; 11804 } 11805 return nullptr; 11806 } 11807 11808 namespace { 11809 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11810 public: 11811 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11812 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11813 : HasTypenameKeyword(HasTypenameKeyword), 11814 IsInstantiation(IsInstantiation), OldNNS(NNS), 11815 RequireMemberOf(RequireMemberOf) {} 11816 11817 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11818 NamedDecl *ND = Candidate.getCorrectionDecl(); 11819 11820 // Keywords are not valid here. 11821 if (!ND || isa<NamespaceDecl>(ND)) 11822 return false; 11823 11824 // Completely unqualified names are invalid for a 'using' declaration. 11825 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11826 return false; 11827 11828 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11829 // reject. 11830 11831 if (RequireMemberOf) { 11832 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11833 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11834 // No-one ever wants a using-declaration to name an injected-class-name 11835 // of a base class, unless they're declaring an inheriting constructor. 11836 ASTContext &Ctx = ND->getASTContext(); 11837 if (!Ctx.getLangOpts().CPlusPlus11) 11838 return false; 11839 QualType FoundType = Ctx.getRecordType(FoundRecord); 11840 11841 // Check that the injected-class-name is named as a member of its own 11842 // type; we don't want to suggest 'using Derived::Base;', since that 11843 // means something else. 11844 NestedNameSpecifier *Specifier = 11845 Candidate.WillReplaceSpecifier() 11846 ? Candidate.getCorrectionSpecifier() 11847 : OldNNS; 11848 if (!Specifier->getAsType() || 11849 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11850 return false; 11851 11852 // Check that this inheriting constructor declaration actually names a 11853 // direct base class of the current class. 11854 bool AnyDependentBases = false; 11855 if (!findDirectBaseWithType(RequireMemberOf, 11856 Ctx.getRecordType(FoundRecord), 11857 AnyDependentBases) && 11858 !AnyDependentBases) 11859 return false; 11860 } else { 11861 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11862 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11863 return false; 11864 11865 // FIXME: Check that the base class member is accessible? 11866 } 11867 } else { 11868 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11869 if (FoundRecord && FoundRecord->isInjectedClassName()) 11870 return false; 11871 } 11872 11873 if (isa<TypeDecl>(ND)) 11874 return HasTypenameKeyword || !IsInstantiation; 11875 11876 return !HasTypenameKeyword; 11877 } 11878 11879 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11880 return std::make_unique<UsingValidatorCCC>(*this); 11881 } 11882 11883 private: 11884 bool HasTypenameKeyword; 11885 bool IsInstantiation; 11886 NestedNameSpecifier *OldNNS; 11887 CXXRecordDecl *RequireMemberOf; 11888 }; 11889 } // end anonymous namespace 11890 11891 /// Builds a using declaration. 11892 /// 11893 /// \param IsInstantiation - Whether this call arises from an 11894 /// instantiation of an unresolved using declaration. We treat 11895 /// the lookup differently for these declarations. 11896 NamedDecl *Sema::BuildUsingDeclaration( 11897 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11898 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11899 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11900 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11901 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11902 SourceLocation IdentLoc = NameInfo.getLoc(); 11903 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11904 11905 // FIXME: We ignore attributes for now. 11906 11907 // For an inheriting constructor declaration, the name of the using 11908 // declaration is the name of a constructor in this class, not in the 11909 // base class. 11910 DeclarationNameInfo UsingName = NameInfo; 11911 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11912 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11913 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11914 Context.getCanonicalType(Context.getRecordType(RD)))); 11915 11916 // Do the redeclaration lookup in the current scope. 11917 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11918 ForVisibleRedeclaration); 11919 Previous.setHideTags(false); 11920 if (S) { 11921 LookupName(Previous, S); 11922 11923 // It is really dumb that we have to do this. 11924 LookupResult::Filter F = Previous.makeFilter(); 11925 while (F.hasNext()) { 11926 NamedDecl *D = F.next(); 11927 if (!isDeclInScope(D, CurContext, S)) 11928 F.erase(); 11929 // If we found a local extern declaration that's not ordinarily visible, 11930 // and this declaration is being added to a non-block scope, ignore it. 11931 // We're only checking for scope conflicts here, not also for violations 11932 // of the linkage rules. 11933 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11934 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11935 F.erase(); 11936 } 11937 F.done(); 11938 } else { 11939 assert(IsInstantiation && "no scope in non-instantiation"); 11940 if (CurContext->isRecord()) 11941 LookupQualifiedName(Previous, CurContext); 11942 else { 11943 // No redeclaration check is needed here; in non-member contexts we 11944 // diagnosed all possible conflicts with other using-declarations when 11945 // building the template: 11946 // 11947 // For a dependent non-type using declaration, the only valid case is 11948 // if we instantiate to a single enumerator. We check for conflicts 11949 // between shadow declarations we introduce, and we check in the template 11950 // definition for conflicts between a non-type using declaration and any 11951 // other declaration, which together covers all cases. 11952 // 11953 // A dependent typename using declaration will never successfully 11954 // instantiate, since it will always name a class member, so we reject 11955 // that in the template definition. 11956 } 11957 } 11958 11959 // Check for invalid redeclarations. 11960 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11961 SS, IdentLoc, Previous)) 11962 return nullptr; 11963 11964 // Check for bad qualifiers. 11965 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11966 IdentLoc)) 11967 return nullptr; 11968 11969 DeclContext *LookupContext = computeDeclContext(SS); 11970 NamedDecl *D; 11971 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11972 if (!LookupContext || EllipsisLoc.isValid()) { 11973 if (HasTypenameKeyword) { 11974 // FIXME: not all declaration name kinds are legal here 11975 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11976 UsingLoc, TypenameLoc, 11977 QualifierLoc, 11978 IdentLoc, NameInfo.getName(), 11979 EllipsisLoc); 11980 } else { 11981 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11982 QualifierLoc, NameInfo, EllipsisLoc); 11983 } 11984 D->setAccess(AS); 11985 CurContext->addDecl(D); 11986 return D; 11987 } 11988 11989 auto Build = [&](bool Invalid) { 11990 UsingDecl *UD = 11991 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11992 UsingName, HasTypenameKeyword); 11993 UD->setAccess(AS); 11994 CurContext->addDecl(UD); 11995 UD->setInvalidDecl(Invalid); 11996 return UD; 11997 }; 11998 auto BuildInvalid = [&]{ return Build(true); }; 11999 auto BuildValid = [&]{ return Build(false); }; 12000 12001 if (RequireCompleteDeclContext(SS, LookupContext)) 12002 return BuildInvalid(); 12003 12004 // Look up the target name. 12005 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12006 12007 // Unlike most lookups, we don't always want to hide tag 12008 // declarations: tag names are visible through the using declaration 12009 // even if hidden by ordinary names, *except* in a dependent context 12010 // where it's important for the sanity of two-phase lookup. 12011 if (!IsInstantiation) 12012 R.setHideTags(false); 12013 12014 // For the purposes of this lookup, we have a base object type 12015 // equal to that of the current context. 12016 if (CurContext->isRecord()) { 12017 R.setBaseObjectType( 12018 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12019 } 12020 12021 LookupQualifiedName(R, LookupContext); 12022 12023 // Try to correct typos if possible. If constructor name lookup finds no 12024 // results, that means the named class has no explicit constructors, and we 12025 // suppressed declaring implicit ones (probably because it's dependent or 12026 // invalid). 12027 if (R.empty() && 12028 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12029 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12030 // it will believe that glibc provides a ::gets in cases where it does not, 12031 // and will try to pull it into namespace std with a using-declaration. 12032 // Just ignore the using-declaration in that case. 12033 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12034 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12035 CurContext->isStdNamespace() && 12036 isa<TranslationUnitDecl>(LookupContext) && 12037 getSourceManager().isInSystemHeader(UsingLoc)) 12038 return nullptr; 12039 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12040 dyn_cast<CXXRecordDecl>(CurContext)); 12041 if (TypoCorrection Corrected = 12042 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12043 CTK_ErrorRecovery)) { 12044 // We reject candidates where DroppedSpecifier == true, hence the 12045 // literal '0' below. 12046 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12047 << NameInfo.getName() << LookupContext << 0 12048 << SS.getRange()); 12049 12050 // If we picked a correction with no attached Decl we can't do anything 12051 // useful with it, bail out. 12052 NamedDecl *ND = Corrected.getCorrectionDecl(); 12053 if (!ND) 12054 return BuildInvalid(); 12055 12056 // If we corrected to an inheriting constructor, handle it as one. 12057 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12058 if (RD && RD->isInjectedClassName()) { 12059 // The parent of the injected class name is the class itself. 12060 RD = cast<CXXRecordDecl>(RD->getParent()); 12061 12062 // Fix up the information we'll use to build the using declaration. 12063 if (Corrected.WillReplaceSpecifier()) { 12064 NestedNameSpecifierLocBuilder Builder; 12065 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12066 QualifierLoc.getSourceRange()); 12067 QualifierLoc = Builder.getWithLocInContext(Context); 12068 } 12069 12070 // In this case, the name we introduce is the name of a derived class 12071 // constructor. 12072 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12073 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12074 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12075 UsingName.setNamedTypeInfo(nullptr); 12076 for (auto *Ctor : LookupConstructors(RD)) 12077 R.addDecl(Ctor); 12078 R.resolveKind(); 12079 } else { 12080 // FIXME: Pick up all the declarations if we found an overloaded 12081 // function. 12082 UsingName.setName(ND->getDeclName()); 12083 R.addDecl(ND); 12084 } 12085 } else { 12086 Diag(IdentLoc, diag::err_no_member) 12087 << NameInfo.getName() << LookupContext << SS.getRange(); 12088 return BuildInvalid(); 12089 } 12090 } 12091 12092 if (R.isAmbiguous()) 12093 return BuildInvalid(); 12094 12095 if (HasTypenameKeyword) { 12096 // If we asked for a typename and got a non-type decl, error out. 12097 if (!R.getAsSingle<TypeDecl>()) { 12098 Diag(IdentLoc, diag::err_using_typename_non_type); 12099 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12100 Diag((*I)->getUnderlyingDecl()->getLocation(), 12101 diag::note_using_decl_target); 12102 return BuildInvalid(); 12103 } 12104 } else { 12105 // If we asked for a non-typename and we got a type, error out, 12106 // but only if this is an instantiation of an unresolved using 12107 // decl. Otherwise just silently find the type name. 12108 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12109 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12110 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12111 return BuildInvalid(); 12112 } 12113 } 12114 12115 // C++14 [namespace.udecl]p6: 12116 // A using-declaration shall not name a namespace. 12117 if (R.getAsSingle<NamespaceDecl>()) { 12118 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12119 << SS.getRange(); 12120 return BuildInvalid(); 12121 } 12122 12123 // C++14 [namespace.udecl]p7: 12124 // A using-declaration shall not name a scoped enumerator. 12125 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12126 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12127 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12128 << SS.getRange(); 12129 return BuildInvalid(); 12130 } 12131 } 12132 12133 UsingDecl *UD = BuildValid(); 12134 12135 // Some additional rules apply to inheriting constructors. 12136 if (UsingName.getName().getNameKind() == 12137 DeclarationName::CXXConstructorName) { 12138 // Suppress access diagnostics; the access check is instead performed at the 12139 // point of use for an inheriting constructor. 12140 R.suppressDiagnostics(); 12141 if (CheckInheritingConstructorUsingDecl(UD)) 12142 return UD; 12143 } 12144 12145 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12146 UsingShadowDecl *PrevDecl = nullptr; 12147 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12148 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12149 } 12150 12151 return UD; 12152 } 12153 12154 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12155 ArrayRef<NamedDecl *> Expansions) { 12156 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12157 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12158 isa<UsingPackDecl>(InstantiatedFrom)); 12159 12160 auto *UPD = 12161 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12162 UPD->setAccess(InstantiatedFrom->getAccess()); 12163 CurContext->addDecl(UPD); 12164 return UPD; 12165 } 12166 12167 /// Additional checks for a using declaration referring to a constructor name. 12168 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12169 assert(!UD->hasTypename() && "expecting a constructor name"); 12170 12171 const Type *SourceType = UD->getQualifier()->getAsType(); 12172 assert(SourceType && 12173 "Using decl naming constructor doesn't have type in scope spec."); 12174 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12175 12176 // Check whether the named type is a direct base class. 12177 bool AnyDependentBases = false; 12178 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12179 AnyDependentBases); 12180 if (!Base && !AnyDependentBases) { 12181 Diag(UD->getUsingLoc(), 12182 diag::err_using_decl_constructor_not_in_direct_base) 12183 << UD->getNameInfo().getSourceRange() 12184 << QualType(SourceType, 0) << TargetClass; 12185 UD->setInvalidDecl(); 12186 return true; 12187 } 12188 12189 if (Base) 12190 Base->setInheritConstructors(); 12191 12192 return false; 12193 } 12194 12195 /// Checks that the given using declaration is not an invalid 12196 /// redeclaration. Note that this is checking only for the using decl 12197 /// itself, not for any ill-formedness among the UsingShadowDecls. 12198 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12199 bool HasTypenameKeyword, 12200 const CXXScopeSpec &SS, 12201 SourceLocation NameLoc, 12202 const LookupResult &Prev) { 12203 NestedNameSpecifier *Qual = SS.getScopeRep(); 12204 12205 // C++03 [namespace.udecl]p8: 12206 // C++0x [namespace.udecl]p10: 12207 // A using-declaration is a declaration and can therefore be used 12208 // repeatedly where (and only where) multiple declarations are 12209 // allowed. 12210 // 12211 // That's in non-member contexts. 12212 if (!CurContext->getRedeclContext()->isRecord()) { 12213 // A dependent qualifier outside a class can only ever resolve to an 12214 // enumeration type. Therefore it conflicts with any other non-type 12215 // declaration in the same scope. 12216 // FIXME: How should we check for dependent type-type conflicts at block 12217 // scope? 12218 if (Qual->isDependent() && !HasTypenameKeyword) { 12219 for (auto *D : Prev) { 12220 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12221 bool OldCouldBeEnumerator = 12222 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12223 Diag(NameLoc, 12224 OldCouldBeEnumerator ? diag::err_redefinition 12225 : diag::err_redefinition_different_kind) 12226 << Prev.getLookupName(); 12227 Diag(D->getLocation(), diag::note_previous_definition); 12228 return true; 12229 } 12230 } 12231 } 12232 return false; 12233 } 12234 12235 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12236 NamedDecl *D = *I; 12237 12238 bool DTypename; 12239 NestedNameSpecifier *DQual; 12240 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12241 DTypename = UD->hasTypename(); 12242 DQual = UD->getQualifier(); 12243 } else if (UnresolvedUsingValueDecl *UD 12244 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12245 DTypename = false; 12246 DQual = UD->getQualifier(); 12247 } else if (UnresolvedUsingTypenameDecl *UD 12248 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12249 DTypename = true; 12250 DQual = UD->getQualifier(); 12251 } else continue; 12252 12253 // using decls differ if one says 'typename' and the other doesn't. 12254 // FIXME: non-dependent using decls? 12255 if (HasTypenameKeyword != DTypename) continue; 12256 12257 // using decls differ if they name different scopes (but note that 12258 // template instantiation can cause this check to trigger when it 12259 // didn't before instantiation). 12260 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12261 Context.getCanonicalNestedNameSpecifier(DQual)) 12262 continue; 12263 12264 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12265 Diag(D->getLocation(), diag::note_using_decl) << 1; 12266 return true; 12267 } 12268 12269 return false; 12270 } 12271 12272 12273 /// Checks that the given nested-name qualifier used in a using decl 12274 /// in the current context is appropriately related to the current 12275 /// scope. If an error is found, diagnoses it and returns true. 12276 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12277 bool HasTypename, 12278 const CXXScopeSpec &SS, 12279 const DeclarationNameInfo &NameInfo, 12280 SourceLocation NameLoc) { 12281 DeclContext *NamedContext = computeDeclContext(SS); 12282 12283 if (!CurContext->isRecord()) { 12284 // C++03 [namespace.udecl]p3: 12285 // C++0x [namespace.udecl]p8: 12286 // A using-declaration for a class member shall be a member-declaration. 12287 12288 // If we weren't able to compute a valid scope, it might validly be a 12289 // dependent class scope or a dependent enumeration unscoped scope. If 12290 // we have a 'typename' keyword, the scope must resolve to a class type. 12291 if ((HasTypename && !NamedContext) || 12292 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12293 auto *RD = NamedContext 12294 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12295 : nullptr; 12296 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12297 RD = nullptr; 12298 12299 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12300 << SS.getRange(); 12301 12302 // If we have a complete, non-dependent source type, try to suggest a 12303 // way to get the same effect. 12304 if (!RD) 12305 return true; 12306 12307 // Find what this using-declaration was referring to. 12308 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12309 R.setHideTags(false); 12310 R.suppressDiagnostics(); 12311 LookupQualifiedName(R, RD); 12312 12313 if (R.getAsSingle<TypeDecl>()) { 12314 if (getLangOpts().CPlusPlus11) { 12315 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12316 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12317 << 0 // alias declaration 12318 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12319 NameInfo.getName().getAsString() + 12320 " = "); 12321 } else { 12322 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12323 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12324 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12325 << 1 // typedef declaration 12326 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12327 << FixItHint::CreateInsertion( 12328 InsertLoc, " " + NameInfo.getName().getAsString()); 12329 } 12330 } else if (R.getAsSingle<VarDecl>()) { 12331 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12332 // repeating the type of the static data member here. 12333 FixItHint FixIt; 12334 if (getLangOpts().CPlusPlus11) { 12335 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12336 FixIt = FixItHint::CreateReplacement( 12337 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12338 } 12339 12340 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12341 << 2 // reference declaration 12342 << FixIt; 12343 } else if (R.getAsSingle<EnumConstantDecl>()) { 12344 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12345 // repeating the type of the enumeration here, and we can't do so if 12346 // the type is anonymous. 12347 FixItHint FixIt; 12348 if (getLangOpts().CPlusPlus11) { 12349 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12350 FixIt = FixItHint::CreateReplacement( 12351 UsingLoc, 12352 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12353 } 12354 12355 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12356 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12357 << FixIt; 12358 } 12359 return true; 12360 } 12361 12362 // Otherwise, this might be valid. 12363 return false; 12364 } 12365 12366 // The current scope is a record. 12367 12368 // If the named context is dependent, we can't decide much. 12369 if (!NamedContext) { 12370 // FIXME: in C++0x, we can diagnose if we can prove that the 12371 // nested-name-specifier does not refer to a base class, which is 12372 // still possible in some cases. 12373 12374 // Otherwise we have to conservatively report that things might be 12375 // okay. 12376 return false; 12377 } 12378 12379 if (!NamedContext->isRecord()) { 12380 // Ideally this would point at the last name in the specifier, 12381 // but we don't have that level of source info. 12382 Diag(SS.getRange().getBegin(), 12383 diag::err_using_decl_nested_name_specifier_is_not_class) 12384 << SS.getScopeRep() << SS.getRange(); 12385 return true; 12386 } 12387 12388 if (!NamedContext->isDependentContext() && 12389 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12390 return true; 12391 12392 if (getLangOpts().CPlusPlus11) { 12393 // C++11 [namespace.udecl]p3: 12394 // In a using-declaration used as a member-declaration, the 12395 // nested-name-specifier shall name a base class of the class 12396 // being defined. 12397 12398 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12399 cast<CXXRecordDecl>(NamedContext))) { 12400 if (CurContext == NamedContext) { 12401 Diag(NameLoc, 12402 diag::err_using_decl_nested_name_specifier_is_current_class) 12403 << SS.getRange(); 12404 return true; 12405 } 12406 12407 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12408 Diag(SS.getRange().getBegin(), 12409 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12410 << SS.getScopeRep() 12411 << cast<CXXRecordDecl>(CurContext) 12412 << SS.getRange(); 12413 } 12414 return true; 12415 } 12416 12417 return false; 12418 } 12419 12420 // C++03 [namespace.udecl]p4: 12421 // A using-declaration used as a member-declaration shall refer 12422 // to a member of a base class of the class being defined [etc.]. 12423 12424 // Salient point: SS doesn't have to name a base class as long as 12425 // lookup only finds members from base classes. Therefore we can 12426 // diagnose here only if we can prove that that can't happen, 12427 // i.e. if the class hierarchies provably don't intersect. 12428 12429 // TODO: it would be nice if "definitely valid" results were cached 12430 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12431 // need to be repeated. 12432 12433 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12434 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12435 Bases.insert(Base); 12436 return true; 12437 }; 12438 12439 // Collect all bases. Return false if we find a dependent base. 12440 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12441 return false; 12442 12443 // Returns true if the base is dependent or is one of the accumulated base 12444 // classes. 12445 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12446 return !Bases.count(Base); 12447 }; 12448 12449 // Return false if the class has a dependent base or if it or one 12450 // of its bases is present in the base set of the current context. 12451 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12452 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12453 return false; 12454 12455 Diag(SS.getRange().getBegin(), 12456 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12457 << SS.getScopeRep() 12458 << cast<CXXRecordDecl>(CurContext) 12459 << SS.getRange(); 12460 12461 return true; 12462 } 12463 12464 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12465 MultiTemplateParamsArg TemplateParamLists, 12466 SourceLocation UsingLoc, UnqualifiedId &Name, 12467 const ParsedAttributesView &AttrList, 12468 TypeResult Type, Decl *DeclFromDeclSpec) { 12469 // Skip up to the relevant declaration scope. 12470 while (S->isTemplateParamScope()) 12471 S = S->getParent(); 12472 assert((S->getFlags() & Scope::DeclScope) && 12473 "got alias-declaration outside of declaration scope"); 12474 12475 if (Type.isInvalid()) 12476 return nullptr; 12477 12478 bool Invalid = false; 12479 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12480 TypeSourceInfo *TInfo = nullptr; 12481 GetTypeFromParser(Type.get(), &TInfo); 12482 12483 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12484 return nullptr; 12485 12486 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12487 UPPC_DeclarationType)) { 12488 Invalid = true; 12489 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12490 TInfo->getTypeLoc().getBeginLoc()); 12491 } 12492 12493 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12494 TemplateParamLists.size() 12495 ? forRedeclarationInCurContext() 12496 : ForVisibleRedeclaration); 12497 LookupName(Previous, S); 12498 12499 // Warn about shadowing the name of a template parameter. 12500 if (Previous.isSingleResult() && 12501 Previous.getFoundDecl()->isTemplateParameter()) { 12502 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12503 Previous.clear(); 12504 } 12505 12506 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12507 "name in alias declaration must be an identifier"); 12508 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12509 Name.StartLocation, 12510 Name.Identifier, TInfo); 12511 12512 NewTD->setAccess(AS); 12513 12514 if (Invalid) 12515 NewTD->setInvalidDecl(); 12516 12517 ProcessDeclAttributeList(S, NewTD, AttrList); 12518 AddPragmaAttributes(S, NewTD); 12519 12520 CheckTypedefForVariablyModifiedType(S, NewTD); 12521 Invalid |= NewTD->isInvalidDecl(); 12522 12523 bool Redeclaration = false; 12524 12525 NamedDecl *NewND; 12526 if (TemplateParamLists.size()) { 12527 TypeAliasTemplateDecl *OldDecl = nullptr; 12528 TemplateParameterList *OldTemplateParams = nullptr; 12529 12530 if (TemplateParamLists.size() != 1) { 12531 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12532 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12533 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12534 } 12535 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12536 12537 // Check that we can declare a template here. 12538 if (CheckTemplateDeclScope(S, TemplateParams)) 12539 return nullptr; 12540 12541 // Only consider previous declarations in the same scope. 12542 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12543 /*ExplicitInstantiationOrSpecialization*/false); 12544 if (!Previous.empty()) { 12545 Redeclaration = true; 12546 12547 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12548 if (!OldDecl && !Invalid) { 12549 Diag(UsingLoc, diag::err_redefinition_different_kind) 12550 << Name.Identifier; 12551 12552 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12553 if (OldD->getLocation().isValid()) 12554 Diag(OldD->getLocation(), diag::note_previous_definition); 12555 12556 Invalid = true; 12557 } 12558 12559 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12560 if (TemplateParameterListsAreEqual(TemplateParams, 12561 OldDecl->getTemplateParameters(), 12562 /*Complain=*/true, 12563 TPL_TemplateMatch)) 12564 OldTemplateParams = 12565 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12566 else 12567 Invalid = true; 12568 12569 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12570 if (!Invalid && 12571 !Context.hasSameType(OldTD->getUnderlyingType(), 12572 NewTD->getUnderlyingType())) { 12573 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12574 // but we can't reasonably accept it. 12575 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12576 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12577 if (OldTD->getLocation().isValid()) 12578 Diag(OldTD->getLocation(), diag::note_previous_definition); 12579 Invalid = true; 12580 } 12581 } 12582 } 12583 12584 // Merge any previous default template arguments into our parameters, 12585 // and check the parameter list. 12586 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12587 TPC_TypeAliasTemplate)) 12588 return nullptr; 12589 12590 TypeAliasTemplateDecl *NewDecl = 12591 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12592 Name.Identifier, TemplateParams, 12593 NewTD); 12594 NewTD->setDescribedAliasTemplate(NewDecl); 12595 12596 NewDecl->setAccess(AS); 12597 12598 if (Invalid) 12599 NewDecl->setInvalidDecl(); 12600 else if (OldDecl) { 12601 NewDecl->setPreviousDecl(OldDecl); 12602 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12603 } 12604 12605 NewND = NewDecl; 12606 } else { 12607 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12608 setTagNameForLinkagePurposes(TD, NewTD); 12609 handleTagNumbering(TD, S); 12610 } 12611 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12612 NewND = NewTD; 12613 } 12614 12615 PushOnScopeChains(NewND, S); 12616 ActOnDocumentableDecl(NewND); 12617 return NewND; 12618 } 12619 12620 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12621 SourceLocation AliasLoc, 12622 IdentifierInfo *Alias, CXXScopeSpec &SS, 12623 SourceLocation IdentLoc, 12624 IdentifierInfo *Ident) { 12625 12626 // Lookup the namespace name. 12627 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12628 LookupParsedName(R, S, &SS); 12629 12630 if (R.isAmbiguous()) 12631 return nullptr; 12632 12633 if (R.empty()) { 12634 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12635 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12636 return nullptr; 12637 } 12638 } 12639 assert(!R.isAmbiguous() && !R.empty()); 12640 NamedDecl *ND = R.getRepresentativeDecl(); 12641 12642 // Check if we have a previous declaration with the same name. 12643 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12644 ForVisibleRedeclaration); 12645 LookupName(PrevR, S); 12646 12647 // Check we're not shadowing a template parameter. 12648 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12649 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12650 PrevR.clear(); 12651 } 12652 12653 // Filter out any other lookup result from an enclosing scope. 12654 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12655 /*AllowInlineNamespace*/false); 12656 12657 // Find the previous declaration and check that we can redeclare it. 12658 NamespaceAliasDecl *Prev = nullptr; 12659 if (PrevR.isSingleResult()) { 12660 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12661 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12662 // We already have an alias with the same name that points to the same 12663 // namespace; check that it matches. 12664 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12665 Prev = AD; 12666 } else if (isVisible(PrevDecl)) { 12667 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12668 << Alias; 12669 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12670 << AD->getNamespace(); 12671 return nullptr; 12672 } 12673 } else if (isVisible(PrevDecl)) { 12674 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12675 ? diag::err_redefinition 12676 : diag::err_redefinition_different_kind; 12677 Diag(AliasLoc, DiagID) << Alias; 12678 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12679 return nullptr; 12680 } 12681 } 12682 12683 // The use of a nested name specifier may trigger deprecation warnings. 12684 DiagnoseUseOfDecl(ND, IdentLoc); 12685 12686 NamespaceAliasDecl *AliasDecl = 12687 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12688 Alias, SS.getWithLocInContext(Context), 12689 IdentLoc, ND); 12690 if (Prev) 12691 AliasDecl->setPreviousDecl(Prev); 12692 12693 PushOnScopeChains(AliasDecl, S); 12694 return AliasDecl; 12695 } 12696 12697 namespace { 12698 struct SpecialMemberExceptionSpecInfo 12699 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12700 SourceLocation Loc; 12701 Sema::ImplicitExceptionSpecification ExceptSpec; 12702 12703 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12704 Sema::CXXSpecialMember CSM, 12705 Sema::InheritedConstructorInfo *ICI, 12706 SourceLocation Loc) 12707 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12708 12709 bool visitBase(CXXBaseSpecifier *Base); 12710 bool visitField(FieldDecl *FD); 12711 12712 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12713 unsigned Quals); 12714 12715 void visitSubobjectCall(Subobject Subobj, 12716 Sema::SpecialMemberOverloadResult SMOR); 12717 }; 12718 } 12719 12720 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12721 auto *RT = Base->getType()->getAs<RecordType>(); 12722 if (!RT) 12723 return false; 12724 12725 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12726 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12727 if (auto *BaseCtor = SMOR.getMethod()) { 12728 visitSubobjectCall(Base, BaseCtor); 12729 return false; 12730 } 12731 12732 visitClassSubobject(BaseClass, Base, 0); 12733 return false; 12734 } 12735 12736 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12737 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12738 Expr *E = FD->getInClassInitializer(); 12739 if (!E) 12740 // FIXME: It's a little wasteful to build and throw away a 12741 // CXXDefaultInitExpr here. 12742 // FIXME: We should have a single context note pointing at Loc, and 12743 // this location should be MD->getLocation() instead, since that's 12744 // the location where we actually use the default init expression. 12745 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12746 if (E) 12747 ExceptSpec.CalledExpr(E); 12748 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12749 ->getAs<RecordType>()) { 12750 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12751 FD->getType().getCVRQualifiers()); 12752 } 12753 return false; 12754 } 12755 12756 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12757 Subobject Subobj, 12758 unsigned Quals) { 12759 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12760 bool IsMutable = Field && Field->isMutable(); 12761 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12762 } 12763 12764 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12765 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12766 // Note, if lookup fails, it doesn't matter what exception specification we 12767 // choose because the special member will be deleted. 12768 if (CXXMethodDecl *MD = SMOR.getMethod()) 12769 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12770 } 12771 12772 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12773 llvm::APSInt Result; 12774 ExprResult Converted = CheckConvertedConstantExpression( 12775 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12776 ExplicitSpec.setExpr(Converted.get()); 12777 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12778 ExplicitSpec.setKind(Result.getBoolValue() 12779 ? ExplicitSpecKind::ResolvedTrue 12780 : ExplicitSpecKind::ResolvedFalse); 12781 return true; 12782 } 12783 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12784 return false; 12785 } 12786 12787 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12788 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12789 if (!ExplicitExpr->isTypeDependent()) 12790 tryResolveExplicitSpecifier(ES); 12791 return ES; 12792 } 12793 12794 static Sema::ImplicitExceptionSpecification 12795 ComputeDefaultedSpecialMemberExceptionSpec( 12796 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12797 Sema::InheritedConstructorInfo *ICI) { 12798 ComputingExceptionSpec CES(S, MD, Loc); 12799 12800 CXXRecordDecl *ClassDecl = MD->getParent(); 12801 12802 // C++ [except.spec]p14: 12803 // An implicitly declared special member function (Clause 12) shall have an 12804 // exception-specification. [...] 12805 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12806 if (ClassDecl->isInvalidDecl()) 12807 return Info.ExceptSpec; 12808 12809 // FIXME: If this diagnostic fires, we're probably missing a check for 12810 // attempting to resolve an exception specification before it's known 12811 // at a higher level. 12812 if (S.RequireCompleteType(MD->getLocation(), 12813 S.Context.getRecordType(ClassDecl), 12814 diag::err_exception_spec_incomplete_type)) 12815 return Info.ExceptSpec; 12816 12817 // C++1z [except.spec]p7: 12818 // [Look for exceptions thrown by] a constructor selected [...] to 12819 // initialize a potentially constructed subobject, 12820 // C++1z [except.spec]p8: 12821 // The exception specification for an implicitly-declared destructor, or a 12822 // destructor without a noexcept-specifier, is potentially-throwing if and 12823 // only if any of the destructors for any of its potentially constructed 12824 // subojects is potentially throwing. 12825 // FIXME: We respect the first rule but ignore the "potentially constructed" 12826 // in the second rule to resolve a core issue (no number yet) that would have 12827 // us reject: 12828 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12829 // struct B : A {}; 12830 // struct C : B { void f(); }; 12831 // ... due to giving B::~B() a non-throwing exception specification. 12832 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12833 : Info.VisitAllBases); 12834 12835 return Info.ExceptSpec; 12836 } 12837 12838 namespace { 12839 /// RAII object to register a special member as being currently declared. 12840 struct DeclaringSpecialMember { 12841 Sema &S; 12842 Sema::SpecialMemberDecl D; 12843 Sema::ContextRAII SavedContext; 12844 bool WasAlreadyBeingDeclared; 12845 12846 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12847 : S(S), D(RD, CSM), SavedContext(S, RD) { 12848 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12849 if (WasAlreadyBeingDeclared) 12850 // This almost never happens, but if it does, ensure that our cache 12851 // doesn't contain a stale result. 12852 S.SpecialMemberCache.clear(); 12853 else { 12854 // Register a note to be produced if we encounter an error while 12855 // declaring the special member. 12856 Sema::CodeSynthesisContext Ctx; 12857 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12858 // FIXME: We don't have a location to use here. Using the class's 12859 // location maintains the fiction that we declare all special members 12860 // with the class, but (1) it's not clear that lying about that helps our 12861 // users understand what's going on, and (2) there may be outer contexts 12862 // on the stack (some of which are relevant) and printing them exposes 12863 // our lies. 12864 Ctx.PointOfInstantiation = RD->getLocation(); 12865 Ctx.Entity = RD; 12866 Ctx.SpecialMember = CSM; 12867 S.pushCodeSynthesisContext(Ctx); 12868 } 12869 } 12870 ~DeclaringSpecialMember() { 12871 if (!WasAlreadyBeingDeclared) { 12872 S.SpecialMembersBeingDeclared.erase(D); 12873 S.popCodeSynthesisContext(); 12874 } 12875 } 12876 12877 /// Are we already trying to declare this special member? 12878 bool isAlreadyBeingDeclared() const { 12879 return WasAlreadyBeingDeclared; 12880 } 12881 }; 12882 } 12883 12884 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12885 // Look up any existing declarations, but don't trigger declaration of all 12886 // implicit special members with this name. 12887 DeclarationName Name = FD->getDeclName(); 12888 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12889 ForExternalRedeclaration); 12890 for (auto *D : FD->getParent()->lookup(Name)) 12891 if (auto *Acceptable = R.getAcceptableDecl(D)) 12892 R.addDecl(Acceptable); 12893 R.resolveKind(); 12894 R.suppressDiagnostics(); 12895 12896 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12897 } 12898 12899 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12900 QualType ResultTy, 12901 ArrayRef<QualType> Args) { 12902 // Build an exception specification pointing back at this constructor. 12903 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12904 12905 LangAS AS = getDefaultCXXMethodAddrSpace(); 12906 if (AS != LangAS::Default) { 12907 EPI.TypeQuals.addAddressSpace(AS); 12908 } 12909 12910 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12911 SpecialMem->setType(QT); 12912 } 12913 12914 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12915 CXXRecordDecl *ClassDecl) { 12916 // C++ [class.ctor]p5: 12917 // A default constructor for a class X is a constructor of class X 12918 // that can be called without an argument. If there is no 12919 // user-declared constructor for class X, a default constructor is 12920 // implicitly declared. An implicitly-declared default constructor 12921 // is an inline public member of its class. 12922 assert(ClassDecl->needsImplicitDefaultConstructor() && 12923 "Should not build implicit default constructor!"); 12924 12925 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12926 if (DSM.isAlreadyBeingDeclared()) 12927 return nullptr; 12928 12929 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12930 CXXDefaultConstructor, 12931 false); 12932 12933 // Create the actual constructor declaration. 12934 CanQualType ClassType 12935 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12936 SourceLocation ClassLoc = ClassDecl->getLocation(); 12937 DeclarationName Name 12938 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12939 DeclarationNameInfo NameInfo(Name, ClassLoc); 12940 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12941 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12942 /*TInfo=*/nullptr, ExplicitSpecifier(), 12943 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12944 Constexpr ? CSK_constexpr : CSK_unspecified); 12945 DefaultCon->setAccess(AS_public); 12946 DefaultCon->setDefaulted(); 12947 12948 if (getLangOpts().CUDA) { 12949 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12950 DefaultCon, 12951 /* ConstRHS */ false, 12952 /* Diagnose */ false); 12953 } 12954 12955 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12956 12957 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12958 // constructors is easy to compute. 12959 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12960 12961 // Note that we have declared this constructor. 12962 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12963 12964 Scope *S = getScopeForContext(ClassDecl); 12965 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12966 12967 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12968 SetDeclDeleted(DefaultCon, ClassLoc); 12969 12970 if (S) 12971 PushOnScopeChains(DefaultCon, S, false); 12972 ClassDecl->addDecl(DefaultCon); 12973 12974 return DefaultCon; 12975 } 12976 12977 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12978 CXXConstructorDecl *Constructor) { 12979 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12980 !Constructor->doesThisDeclarationHaveABody() && 12981 !Constructor->isDeleted()) && 12982 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12983 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12984 return; 12985 12986 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12987 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12988 12989 SynthesizedFunctionScope Scope(*this, Constructor); 12990 12991 // The exception specification is needed because we are defining the 12992 // function. 12993 ResolveExceptionSpec(CurrentLocation, 12994 Constructor->getType()->castAs<FunctionProtoType>()); 12995 MarkVTableUsed(CurrentLocation, ClassDecl); 12996 12997 // Add a context note for diagnostics produced after this point. 12998 Scope.addContextNote(CurrentLocation); 12999 13000 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13001 Constructor->setInvalidDecl(); 13002 return; 13003 } 13004 13005 SourceLocation Loc = Constructor->getEndLoc().isValid() 13006 ? Constructor->getEndLoc() 13007 : Constructor->getLocation(); 13008 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13009 Constructor->markUsed(Context); 13010 13011 if (ASTMutationListener *L = getASTMutationListener()) { 13012 L->CompletedImplicitDefinition(Constructor); 13013 } 13014 13015 DiagnoseUninitializedFields(*this, Constructor); 13016 } 13017 13018 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13019 // Perform any delayed checks on exception specifications. 13020 CheckDelayedMemberExceptionSpecs(); 13021 } 13022 13023 /// Find or create the fake constructor we synthesize to model constructing an 13024 /// object of a derived class via a constructor of a base class. 13025 CXXConstructorDecl * 13026 Sema::findInheritingConstructor(SourceLocation Loc, 13027 CXXConstructorDecl *BaseCtor, 13028 ConstructorUsingShadowDecl *Shadow) { 13029 CXXRecordDecl *Derived = Shadow->getParent(); 13030 SourceLocation UsingLoc = Shadow->getLocation(); 13031 13032 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13033 // For now we use the name of the base class constructor as a member of the 13034 // derived class to indicate a (fake) inherited constructor name. 13035 DeclarationName Name = BaseCtor->getDeclName(); 13036 13037 // Check to see if we already have a fake constructor for this inherited 13038 // constructor call. 13039 for (NamedDecl *Ctor : Derived->lookup(Name)) 13040 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13041 ->getInheritedConstructor() 13042 .getConstructor(), 13043 BaseCtor)) 13044 return cast<CXXConstructorDecl>(Ctor); 13045 13046 DeclarationNameInfo NameInfo(Name, UsingLoc); 13047 TypeSourceInfo *TInfo = 13048 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13049 FunctionProtoTypeLoc ProtoLoc = 13050 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13051 13052 // Check the inherited constructor is valid and find the list of base classes 13053 // from which it was inherited. 13054 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13055 13056 bool Constexpr = 13057 BaseCtor->isConstexpr() && 13058 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13059 false, BaseCtor, &ICI); 13060 13061 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13062 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13063 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13064 /*isImplicitlyDeclared=*/true, 13065 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 13066 InheritedConstructor(Shadow, BaseCtor), 13067 BaseCtor->getTrailingRequiresClause()); 13068 if (Shadow->isInvalidDecl()) 13069 DerivedCtor->setInvalidDecl(); 13070 13071 // Build an unevaluated exception specification for this fake constructor. 13072 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13073 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13074 EPI.ExceptionSpec.Type = EST_Unevaluated; 13075 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13076 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13077 FPT->getParamTypes(), EPI)); 13078 13079 // Build the parameter declarations. 13080 SmallVector<ParmVarDecl *, 16> ParamDecls; 13081 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13082 TypeSourceInfo *TInfo = 13083 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13084 ParmVarDecl *PD = ParmVarDecl::Create( 13085 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13086 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13087 PD->setScopeInfo(0, I); 13088 PD->setImplicit(); 13089 // Ensure attributes are propagated onto parameters (this matters for 13090 // format, pass_object_size, ...). 13091 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13092 ParamDecls.push_back(PD); 13093 ProtoLoc.setParam(I, PD); 13094 } 13095 13096 // Set up the new constructor. 13097 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13098 DerivedCtor->setAccess(BaseCtor->getAccess()); 13099 DerivedCtor->setParams(ParamDecls); 13100 Derived->addDecl(DerivedCtor); 13101 13102 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13103 SetDeclDeleted(DerivedCtor, UsingLoc); 13104 13105 return DerivedCtor; 13106 } 13107 13108 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13109 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13110 Ctor->getInheritedConstructor().getShadowDecl()); 13111 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13112 /*Diagnose*/true); 13113 } 13114 13115 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13116 CXXConstructorDecl *Constructor) { 13117 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13118 assert(Constructor->getInheritedConstructor() && 13119 !Constructor->doesThisDeclarationHaveABody() && 13120 !Constructor->isDeleted()); 13121 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13122 return; 13123 13124 // Initializations are performed "as if by a defaulted default constructor", 13125 // so enter the appropriate scope. 13126 SynthesizedFunctionScope Scope(*this, Constructor); 13127 13128 // The exception specification is needed because we are defining the 13129 // function. 13130 ResolveExceptionSpec(CurrentLocation, 13131 Constructor->getType()->castAs<FunctionProtoType>()); 13132 MarkVTableUsed(CurrentLocation, ClassDecl); 13133 13134 // Add a context note for diagnostics produced after this point. 13135 Scope.addContextNote(CurrentLocation); 13136 13137 ConstructorUsingShadowDecl *Shadow = 13138 Constructor->getInheritedConstructor().getShadowDecl(); 13139 CXXConstructorDecl *InheritedCtor = 13140 Constructor->getInheritedConstructor().getConstructor(); 13141 13142 // [class.inhctor.init]p1: 13143 // initialization proceeds as if a defaulted default constructor is used to 13144 // initialize the D object and each base class subobject from which the 13145 // constructor was inherited 13146 13147 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13148 CXXRecordDecl *RD = Shadow->getParent(); 13149 SourceLocation InitLoc = Shadow->getLocation(); 13150 13151 // Build explicit initializers for all base classes from which the 13152 // constructor was inherited. 13153 SmallVector<CXXCtorInitializer*, 8> Inits; 13154 for (bool VBase : {false, true}) { 13155 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13156 if (B.isVirtual() != VBase) 13157 continue; 13158 13159 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13160 if (!BaseRD) 13161 continue; 13162 13163 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13164 if (!BaseCtor.first) 13165 continue; 13166 13167 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13168 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13169 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13170 13171 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13172 Inits.push_back(new (Context) CXXCtorInitializer( 13173 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13174 SourceLocation())); 13175 } 13176 } 13177 13178 // We now proceed as if for a defaulted default constructor, with the relevant 13179 // initializers replaced. 13180 13181 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13182 Constructor->setInvalidDecl(); 13183 return; 13184 } 13185 13186 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13187 Constructor->markUsed(Context); 13188 13189 if (ASTMutationListener *L = getASTMutationListener()) { 13190 L->CompletedImplicitDefinition(Constructor); 13191 } 13192 13193 DiagnoseUninitializedFields(*this, Constructor); 13194 } 13195 13196 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13197 // C++ [class.dtor]p2: 13198 // If a class has no user-declared destructor, a destructor is 13199 // declared implicitly. An implicitly-declared destructor is an 13200 // inline public member of its class. 13201 assert(ClassDecl->needsImplicitDestructor()); 13202 13203 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13204 if (DSM.isAlreadyBeingDeclared()) 13205 return nullptr; 13206 13207 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13208 CXXDestructor, 13209 false); 13210 13211 // Create the actual destructor declaration. 13212 CanQualType ClassType 13213 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13214 SourceLocation ClassLoc = ClassDecl->getLocation(); 13215 DeclarationName Name 13216 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13217 DeclarationNameInfo NameInfo(Name, ClassLoc); 13218 CXXDestructorDecl *Destructor = 13219 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13220 QualType(), nullptr, /*isInline=*/true, 13221 /*isImplicitlyDeclared=*/true, 13222 Constexpr ? CSK_constexpr : CSK_unspecified); 13223 Destructor->setAccess(AS_public); 13224 Destructor->setDefaulted(); 13225 13226 if (getLangOpts().CUDA) { 13227 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13228 Destructor, 13229 /* ConstRHS */ false, 13230 /* Diagnose */ false); 13231 } 13232 13233 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13234 13235 // We don't need to use SpecialMemberIsTrivial here; triviality for 13236 // destructors is easy to compute. 13237 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13238 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13239 ClassDecl->hasTrivialDestructorForCall()); 13240 13241 // Note that we have declared this destructor. 13242 ++getASTContext().NumImplicitDestructorsDeclared; 13243 13244 Scope *S = getScopeForContext(ClassDecl); 13245 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13246 13247 // We can't check whether an implicit destructor is deleted before we complete 13248 // the definition of the class, because its validity depends on the alignment 13249 // of the class. We'll check this from ActOnFields once the class is complete. 13250 if (ClassDecl->isCompleteDefinition() && 13251 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13252 SetDeclDeleted(Destructor, ClassLoc); 13253 13254 // Introduce this destructor into its scope. 13255 if (S) 13256 PushOnScopeChains(Destructor, S, false); 13257 ClassDecl->addDecl(Destructor); 13258 13259 return Destructor; 13260 } 13261 13262 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13263 CXXDestructorDecl *Destructor) { 13264 assert((Destructor->isDefaulted() && 13265 !Destructor->doesThisDeclarationHaveABody() && 13266 !Destructor->isDeleted()) && 13267 "DefineImplicitDestructor - call it for implicit default dtor"); 13268 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13269 return; 13270 13271 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13272 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13273 13274 SynthesizedFunctionScope Scope(*this, Destructor); 13275 13276 // The exception specification is needed because we are defining the 13277 // function. 13278 ResolveExceptionSpec(CurrentLocation, 13279 Destructor->getType()->castAs<FunctionProtoType>()); 13280 MarkVTableUsed(CurrentLocation, ClassDecl); 13281 13282 // Add a context note for diagnostics produced after this point. 13283 Scope.addContextNote(CurrentLocation); 13284 13285 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13286 Destructor->getParent()); 13287 13288 if (CheckDestructor(Destructor)) { 13289 Destructor->setInvalidDecl(); 13290 return; 13291 } 13292 13293 SourceLocation Loc = Destructor->getEndLoc().isValid() 13294 ? Destructor->getEndLoc() 13295 : Destructor->getLocation(); 13296 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13297 Destructor->markUsed(Context); 13298 13299 if (ASTMutationListener *L = getASTMutationListener()) { 13300 L->CompletedImplicitDefinition(Destructor); 13301 } 13302 } 13303 13304 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13305 CXXDestructorDecl *Destructor) { 13306 if (Destructor->isInvalidDecl()) 13307 return; 13308 13309 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13310 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13311 "implicit complete dtors unneeded outside MS ABI"); 13312 assert(ClassDecl->getNumVBases() > 0 && 13313 "complete dtor only exists for classes with vbases"); 13314 13315 SynthesizedFunctionScope Scope(*this, Destructor); 13316 13317 // Add a context note for diagnostics produced after this point. 13318 Scope.addContextNote(CurrentLocation); 13319 13320 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13321 } 13322 13323 /// Perform any semantic analysis which needs to be delayed until all 13324 /// pending class member declarations have been parsed. 13325 void Sema::ActOnFinishCXXMemberDecls() { 13326 // If the context is an invalid C++ class, just suppress these checks. 13327 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13328 if (Record->isInvalidDecl()) { 13329 DelayedOverridingExceptionSpecChecks.clear(); 13330 DelayedEquivalentExceptionSpecChecks.clear(); 13331 return; 13332 } 13333 checkForMultipleExportedDefaultConstructors(*this, Record); 13334 } 13335 } 13336 13337 void Sema::ActOnFinishCXXNonNestedClass() { 13338 referenceDLLExportedClassMethods(); 13339 13340 if (!DelayedDllExportMemberFunctions.empty()) { 13341 SmallVector<CXXMethodDecl*, 4> WorkList; 13342 std::swap(DelayedDllExportMemberFunctions, WorkList); 13343 for (CXXMethodDecl *M : WorkList) { 13344 DefineDefaultedFunction(*this, M, M->getLocation()); 13345 13346 // Pass the method to the consumer to get emitted. This is not necessary 13347 // for explicit instantiation definitions, as they will get emitted 13348 // anyway. 13349 if (M->getParent()->getTemplateSpecializationKind() != 13350 TSK_ExplicitInstantiationDefinition) 13351 ActOnFinishInlineFunctionDef(M); 13352 } 13353 } 13354 } 13355 13356 void Sema::referenceDLLExportedClassMethods() { 13357 if (!DelayedDllExportClasses.empty()) { 13358 // Calling ReferenceDllExportedMembers might cause the current function to 13359 // be called again, so use a local copy of DelayedDllExportClasses. 13360 SmallVector<CXXRecordDecl *, 4> WorkList; 13361 std::swap(DelayedDllExportClasses, WorkList); 13362 for (CXXRecordDecl *Class : WorkList) 13363 ReferenceDllExportedMembers(*this, Class); 13364 } 13365 } 13366 13367 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13368 assert(getLangOpts().CPlusPlus11 && 13369 "adjusting dtor exception specs was introduced in c++11"); 13370 13371 if (Destructor->isDependentContext()) 13372 return; 13373 13374 // C++11 [class.dtor]p3: 13375 // A declaration of a destructor that does not have an exception- 13376 // specification is implicitly considered to have the same exception- 13377 // specification as an implicit declaration. 13378 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13379 if (DtorType->hasExceptionSpec()) 13380 return; 13381 13382 // Replace the destructor's type, building off the existing one. Fortunately, 13383 // the only thing of interest in the destructor type is its extended info. 13384 // The return and arguments are fixed. 13385 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13386 EPI.ExceptionSpec.Type = EST_Unevaluated; 13387 EPI.ExceptionSpec.SourceDecl = Destructor; 13388 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13389 13390 // FIXME: If the destructor has a body that could throw, and the newly created 13391 // spec doesn't allow exceptions, we should emit a warning, because this 13392 // change in behavior can break conforming C++03 programs at runtime. 13393 // However, we don't have a body or an exception specification yet, so it 13394 // needs to be done somewhere else. 13395 } 13396 13397 namespace { 13398 /// An abstract base class for all helper classes used in building the 13399 // copy/move operators. These classes serve as factory functions and help us 13400 // avoid using the same Expr* in the AST twice. 13401 class ExprBuilder { 13402 ExprBuilder(const ExprBuilder&) = delete; 13403 ExprBuilder &operator=(const ExprBuilder&) = delete; 13404 13405 protected: 13406 static Expr *assertNotNull(Expr *E) { 13407 assert(E && "Expression construction must not fail."); 13408 return E; 13409 } 13410 13411 public: 13412 ExprBuilder() {} 13413 virtual ~ExprBuilder() {} 13414 13415 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13416 }; 13417 13418 class RefBuilder: public ExprBuilder { 13419 VarDecl *Var; 13420 QualType VarType; 13421 13422 public: 13423 Expr *build(Sema &S, SourceLocation Loc) const override { 13424 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13425 } 13426 13427 RefBuilder(VarDecl *Var, QualType VarType) 13428 : Var(Var), VarType(VarType) {} 13429 }; 13430 13431 class ThisBuilder: public ExprBuilder { 13432 public: 13433 Expr *build(Sema &S, SourceLocation Loc) const override { 13434 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13435 } 13436 }; 13437 13438 class CastBuilder: public ExprBuilder { 13439 const ExprBuilder &Builder; 13440 QualType Type; 13441 ExprValueKind Kind; 13442 const CXXCastPath &Path; 13443 13444 public: 13445 Expr *build(Sema &S, SourceLocation Loc) const override { 13446 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13447 CK_UncheckedDerivedToBase, Kind, 13448 &Path).get()); 13449 } 13450 13451 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13452 const CXXCastPath &Path) 13453 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13454 }; 13455 13456 class DerefBuilder: public ExprBuilder { 13457 const ExprBuilder &Builder; 13458 13459 public: 13460 Expr *build(Sema &S, SourceLocation Loc) const override { 13461 return assertNotNull( 13462 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13463 } 13464 13465 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13466 }; 13467 13468 class MemberBuilder: public ExprBuilder { 13469 const ExprBuilder &Builder; 13470 QualType Type; 13471 CXXScopeSpec SS; 13472 bool IsArrow; 13473 LookupResult &MemberLookup; 13474 13475 public: 13476 Expr *build(Sema &S, SourceLocation Loc) const override { 13477 return assertNotNull(S.BuildMemberReferenceExpr( 13478 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13479 nullptr, MemberLookup, nullptr, nullptr).get()); 13480 } 13481 13482 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13483 LookupResult &MemberLookup) 13484 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13485 MemberLookup(MemberLookup) {} 13486 }; 13487 13488 class MoveCastBuilder: public ExprBuilder { 13489 const ExprBuilder &Builder; 13490 13491 public: 13492 Expr *build(Sema &S, SourceLocation Loc) const override { 13493 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13494 } 13495 13496 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13497 }; 13498 13499 class LvalueConvBuilder: public ExprBuilder { 13500 const ExprBuilder &Builder; 13501 13502 public: 13503 Expr *build(Sema &S, SourceLocation Loc) const override { 13504 return assertNotNull( 13505 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13506 } 13507 13508 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13509 }; 13510 13511 class SubscriptBuilder: public ExprBuilder { 13512 const ExprBuilder &Base; 13513 const ExprBuilder &Index; 13514 13515 public: 13516 Expr *build(Sema &S, SourceLocation Loc) const override { 13517 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13518 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13519 } 13520 13521 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13522 : Base(Base), Index(Index) {} 13523 }; 13524 13525 } // end anonymous namespace 13526 13527 /// When generating a defaulted copy or move assignment operator, if a field 13528 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13529 /// do so. This optimization only applies for arrays of scalars, and for arrays 13530 /// of class type where the selected copy/move-assignment operator is trivial. 13531 static StmtResult 13532 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13533 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13534 // Compute the size of the memory buffer to be copied. 13535 QualType SizeType = S.Context.getSizeType(); 13536 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13537 S.Context.getTypeSizeInChars(T).getQuantity()); 13538 13539 // Take the address of the field references for "from" and "to". We 13540 // directly construct UnaryOperators here because semantic analysis 13541 // does not permit us to take the address of an xvalue. 13542 Expr *From = FromB.build(S, Loc); 13543 From = UnaryOperator::Create( 13544 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13545 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13546 Expr *To = ToB.build(S, Loc); 13547 To = UnaryOperator::Create( 13548 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13549 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13550 13551 const Type *E = T->getBaseElementTypeUnsafe(); 13552 bool NeedsCollectableMemCpy = 13553 E->isRecordType() && 13554 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13555 13556 // Create a reference to the __builtin_objc_memmove_collectable function 13557 StringRef MemCpyName = NeedsCollectableMemCpy ? 13558 "__builtin_objc_memmove_collectable" : 13559 "__builtin_memcpy"; 13560 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13561 Sema::LookupOrdinaryName); 13562 S.LookupName(R, S.TUScope, true); 13563 13564 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13565 if (!MemCpy) 13566 // Something went horribly wrong earlier, and we will have complained 13567 // about it. 13568 return StmtError(); 13569 13570 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13571 VK_RValue, Loc, nullptr); 13572 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13573 13574 Expr *CallArgs[] = { 13575 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13576 }; 13577 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13578 Loc, CallArgs, Loc); 13579 13580 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13581 return Call.getAs<Stmt>(); 13582 } 13583 13584 /// Builds a statement that copies/moves the given entity from \p From to 13585 /// \c To. 13586 /// 13587 /// This routine is used to copy/move the members of a class with an 13588 /// implicitly-declared copy/move assignment operator. When the entities being 13589 /// copied are arrays, this routine builds for loops to copy them. 13590 /// 13591 /// \param S The Sema object used for type-checking. 13592 /// 13593 /// \param Loc The location where the implicit copy/move is being generated. 13594 /// 13595 /// \param T The type of the expressions being copied/moved. Both expressions 13596 /// must have this type. 13597 /// 13598 /// \param To The expression we are copying/moving to. 13599 /// 13600 /// \param From The expression we are copying/moving from. 13601 /// 13602 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13603 /// Otherwise, it's a non-static member subobject. 13604 /// 13605 /// \param Copying Whether we're copying or moving. 13606 /// 13607 /// \param Depth Internal parameter recording the depth of the recursion. 13608 /// 13609 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13610 /// if a memcpy should be used instead. 13611 static StmtResult 13612 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13613 const ExprBuilder &To, const ExprBuilder &From, 13614 bool CopyingBaseSubobject, bool Copying, 13615 unsigned Depth = 0) { 13616 // C++11 [class.copy]p28: 13617 // Each subobject is assigned in the manner appropriate to its type: 13618 // 13619 // - if the subobject is of class type, as if by a call to operator= with 13620 // the subobject as the object expression and the corresponding 13621 // subobject of x as a single function argument (as if by explicit 13622 // qualification; that is, ignoring any possible virtual overriding 13623 // functions in more derived classes); 13624 // 13625 // C++03 [class.copy]p13: 13626 // - if the subobject is of class type, the copy assignment operator for 13627 // the class is used (as if by explicit qualification; that is, 13628 // ignoring any possible virtual overriding functions in more derived 13629 // classes); 13630 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13631 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13632 13633 // Look for operator=. 13634 DeclarationName Name 13635 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13636 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13637 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13638 13639 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13640 // operator. 13641 if (!S.getLangOpts().CPlusPlus11) { 13642 LookupResult::Filter F = OpLookup.makeFilter(); 13643 while (F.hasNext()) { 13644 NamedDecl *D = F.next(); 13645 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13646 if (Method->isCopyAssignmentOperator() || 13647 (!Copying && Method->isMoveAssignmentOperator())) 13648 continue; 13649 13650 F.erase(); 13651 } 13652 F.done(); 13653 } 13654 13655 // Suppress the protected check (C++ [class.protected]) for each of the 13656 // assignment operators we found. This strange dance is required when 13657 // we're assigning via a base classes's copy-assignment operator. To 13658 // ensure that we're getting the right base class subobject (without 13659 // ambiguities), we need to cast "this" to that subobject type; to 13660 // ensure that we don't go through the virtual call mechanism, we need 13661 // to qualify the operator= name with the base class (see below). However, 13662 // this means that if the base class has a protected copy assignment 13663 // operator, the protected member access check will fail. So, we 13664 // rewrite "protected" access to "public" access in this case, since we 13665 // know by construction that we're calling from a derived class. 13666 if (CopyingBaseSubobject) { 13667 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13668 L != LEnd; ++L) { 13669 if (L.getAccess() == AS_protected) 13670 L.setAccess(AS_public); 13671 } 13672 } 13673 13674 // Create the nested-name-specifier that will be used to qualify the 13675 // reference to operator=; this is required to suppress the virtual 13676 // call mechanism. 13677 CXXScopeSpec SS; 13678 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13679 SS.MakeTrivial(S.Context, 13680 NestedNameSpecifier::Create(S.Context, nullptr, false, 13681 CanonicalT), 13682 Loc); 13683 13684 // Create the reference to operator=. 13685 ExprResult OpEqualRef 13686 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13687 SS, /*TemplateKWLoc=*/SourceLocation(), 13688 /*FirstQualifierInScope=*/nullptr, 13689 OpLookup, 13690 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13691 /*SuppressQualifierCheck=*/true); 13692 if (OpEqualRef.isInvalid()) 13693 return StmtError(); 13694 13695 // Build the call to the assignment operator. 13696 13697 Expr *FromInst = From.build(S, Loc); 13698 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13699 OpEqualRef.getAs<Expr>(), 13700 Loc, FromInst, Loc); 13701 if (Call.isInvalid()) 13702 return StmtError(); 13703 13704 // If we built a call to a trivial 'operator=' while copying an array, 13705 // bail out. We'll replace the whole shebang with a memcpy. 13706 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13707 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13708 return StmtResult((Stmt*)nullptr); 13709 13710 // Convert to an expression-statement, and clean up any produced 13711 // temporaries. 13712 return S.ActOnExprStmt(Call); 13713 } 13714 13715 // - if the subobject is of scalar type, the built-in assignment 13716 // operator is used. 13717 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13718 if (!ArrayTy) { 13719 ExprResult Assignment = S.CreateBuiltinBinOp( 13720 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13721 if (Assignment.isInvalid()) 13722 return StmtError(); 13723 return S.ActOnExprStmt(Assignment); 13724 } 13725 13726 // - if the subobject is an array, each element is assigned, in the 13727 // manner appropriate to the element type; 13728 13729 // Construct a loop over the array bounds, e.g., 13730 // 13731 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13732 // 13733 // that will copy each of the array elements. 13734 QualType SizeType = S.Context.getSizeType(); 13735 13736 // Create the iteration variable. 13737 IdentifierInfo *IterationVarName = nullptr; 13738 { 13739 SmallString<8> Str; 13740 llvm::raw_svector_ostream OS(Str); 13741 OS << "__i" << Depth; 13742 IterationVarName = &S.Context.Idents.get(OS.str()); 13743 } 13744 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13745 IterationVarName, SizeType, 13746 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13747 SC_None); 13748 13749 // Initialize the iteration variable to zero. 13750 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13751 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13752 13753 // Creates a reference to the iteration variable. 13754 RefBuilder IterationVarRef(IterationVar, SizeType); 13755 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13756 13757 // Create the DeclStmt that holds the iteration variable. 13758 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13759 13760 // Subscript the "from" and "to" expressions with the iteration variable. 13761 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13762 MoveCastBuilder FromIndexMove(FromIndexCopy); 13763 const ExprBuilder *FromIndex; 13764 if (Copying) 13765 FromIndex = &FromIndexCopy; 13766 else 13767 FromIndex = &FromIndexMove; 13768 13769 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13770 13771 // Build the copy/move for an individual element of the array. 13772 StmtResult Copy = 13773 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13774 ToIndex, *FromIndex, CopyingBaseSubobject, 13775 Copying, Depth + 1); 13776 // Bail out if copying fails or if we determined that we should use memcpy. 13777 if (Copy.isInvalid() || !Copy.get()) 13778 return Copy; 13779 13780 // Create the comparison against the array bound. 13781 llvm::APInt Upper 13782 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13783 Expr *Comparison = BinaryOperator::Create( 13784 S.Context, IterationVarRefRVal.build(S, Loc), 13785 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13786 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13787 13788 // Create the pre-increment of the iteration variable. We can determine 13789 // whether the increment will overflow based on the value of the array 13790 // bound. 13791 Expr *Increment = UnaryOperator::Create( 13792 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13793 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13794 13795 // Construct the loop that copies all elements of this array. 13796 return S.ActOnForStmt( 13797 Loc, Loc, InitStmt, 13798 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13799 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13800 } 13801 13802 static StmtResult 13803 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13804 const ExprBuilder &To, const ExprBuilder &From, 13805 bool CopyingBaseSubobject, bool Copying) { 13806 // Maybe we should use a memcpy? 13807 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13808 T.isTriviallyCopyableType(S.Context)) 13809 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13810 13811 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13812 CopyingBaseSubobject, 13813 Copying, 0)); 13814 13815 // If we ended up picking a trivial assignment operator for an array of a 13816 // non-trivially-copyable class type, just emit a memcpy. 13817 if (!Result.isInvalid() && !Result.get()) 13818 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13819 13820 return Result; 13821 } 13822 13823 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13824 // Note: The following rules are largely analoguous to the copy 13825 // constructor rules. Note that virtual bases are not taken into account 13826 // for determining the argument type of the operator. Note also that 13827 // operators taking an object instead of a reference are allowed. 13828 assert(ClassDecl->needsImplicitCopyAssignment()); 13829 13830 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13831 if (DSM.isAlreadyBeingDeclared()) 13832 return nullptr; 13833 13834 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13835 LangAS AS = getDefaultCXXMethodAddrSpace(); 13836 if (AS != LangAS::Default) 13837 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13838 QualType RetType = Context.getLValueReferenceType(ArgType); 13839 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13840 if (Const) 13841 ArgType = ArgType.withConst(); 13842 13843 ArgType = Context.getLValueReferenceType(ArgType); 13844 13845 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13846 CXXCopyAssignment, 13847 Const); 13848 13849 // An implicitly-declared copy assignment operator is an inline public 13850 // member of its class. 13851 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13852 SourceLocation ClassLoc = ClassDecl->getLocation(); 13853 DeclarationNameInfo NameInfo(Name, ClassLoc); 13854 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13855 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13856 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13857 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13858 SourceLocation()); 13859 CopyAssignment->setAccess(AS_public); 13860 CopyAssignment->setDefaulted(); 13861 CopyAssignment->setImplicit(); 13862 13863 if (getLangOpts().CUDA) { 13864 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13865 CopyAssignment, 13866 /* ConstRHS */ Const, 13867 /* Diagnose */ false); 13868 } 13869 13870 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13871 13872 // Add the parameter to the operator. 13873 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13874 ClassLoc, ClassLoc, 13875 /*Id=*/nullptr, ArgType, 13876 /*TInfo=*/nullptr, SC_None, 13877 nullptr); 13878 CopyAssignment->setParams(FromParam); 13879 13880 CopyAssignment->setTrivial( 13881 ClassDecl->needsOverloadResolutionForCopyAssignment() 13882 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13883 : ClassDecl->hasTrivialCopyAssignment()); 13884 13885 // Note that we have added this copy-assignment operator. 13886 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13887 13888 Scope *S = getScopeForContext(ClassDecl); 13889 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13890 13891 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13892 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13893 SetDeclDeleted(CopyAssignment, ClassLoc); 13894 } 13895 13896 if (S) 13897 PushOnScopeChains(CopyAssignment, S, false); 13898 ClassDecl->addDecl(CopyAssignment); 13899 13900 return CopyAssignment; 13901 } 13902 13903 /// Diagnose an implicit copy operation for a class which is odr-used, but 13904 /// which is deprecated because the class has a user-declared copy constructor, 13905 /// copy assignment operator, or destructor. 13906 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13907 assert(CopyOp->isImplicit()); 13908 13909 CXXRecordDecl *RD = CopyOp->getParent(); 13910 CXXMethodDecl *UserDeclaredOperation = nullptr; 13911 13912 // In Microsoft mode, assignment operations don't affect constructors and 13913 // vice versa. 13914 if (RD->hasUserDeclaredDestructor()) { 13915 UserDeclaredOperation = RD->getDestructor(); 13916 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13917 RD->hasUserDeclaredCopyConstructor() && 13918 !S.getLangOpts().MSVCCompat) { 13919 // Find any user-declared copy constructor. 13920 for (auto *I : RD->ctors()) { 13921 if (I->isCopyConstructor()) { 13922 UserDeclaredOperation = I; 13923 break; 13924 } 13925 } 13926 assert(UserDeclaredOperation); 13927 } else if (isa<CXXConstructorDecl>(CopyOp) && 13928 RD->hasUserDeclaredCopyAssignment() && 13929 !S.getLangOpts().MSVCCompat) { 13930 // Find any user-declared move assignment operator. 13931 for (auto *I : RD->methods()) { 13932 if (I->isCopyAssignmentOperator()) { 13933 UserDeclaredOperation = I; 13934 break; 13935 } 13936 } 13937 assert(UserDeclaredOperation); 13938 } 13939 13940 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13941 S.Diag(UserDeclaredOperation->getLocation(), 13942 isa<CXXDestructorDecl>(UserDeclaredOperation) 13943 ? diag::warn_deprecated_copy_dtor_operation 13944 : diag::warn_deprecated_copy_operation) 13945 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13946 } 13947 } 13948 13949 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13950 CXXMethodDecl *CopyAssignOperator) { 13951 assert((CopyAssignOperator->isDefaulted() && 13952 CopyAssignOperator->isOverloadedOperator() && 13953 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13954 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13955 !CopyAssignOperator->isDeleted()) && 13956 "DefineImplicitCopyAssignment called for wrong function"); 13957 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13958 return; 13959 13960 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13961 if (ClassDecl->isInvalidDecl()) { 13962 CopyAssignOperator->setInvalidDecl(); 13963 return; 13964 } 13965 13966 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13967 13968 // The exception specification is needed because we are defining the 13969 // function. 13970 ResolveExceptionSpec(CurrentLocation, 13971 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13972 13973 // Add a context note for diagnostics produced after this point. 13974 Scope.addContextNote(CurrentLocation); 13975 13976 // C++11 [class.copy]p18: 13977 // The [definition of an implicitly declared copy assignment operator] is 13978 // deprecated if the class has a user-declared copy constructor or a 13979 // user-declared destructor. 13980 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13981 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13982 13983 // C++0x [class.copy]p30: 13984 // The implicitly-defined or explicitly-defaulted copy assignment operator 13985 // for a non-union class X performs memberwise copy assignment of its 13986 // subobjects. The direct base classes of X are assigned first, in the 13987 // order of their declaration in the base-specifier-list, and then the 13988 // immediate non-static data members of X are assigned, in the order in 13989 // which they were declared in the class definition. 13990 13991 // The statements that form the synthesized function body. 13992 SmallVector<Stmt*, 8> Statements; 13993 13994 // The parameter for the "other" object, which we are copying from. 13995 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13996 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13997 QualType OtherRefType = Other->getType(); 13998 if (const LValueReferenceType *OtherRef 13999 = OtherRefType->getAs<LValueReferenceType>()) { 14000 OtherRefType = OtherRef->getPointeeType(); 14001 OtherQuals = OtherRefType.getQualifiers(); 14002 } 14003 14004 // Our location for everything implicitly-generated. 14005 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14006 ? CopyAssignOperator->getEndLoc() 14007 : CopyAssignOperator->getLocation(); 14008 14009 // Builds a DeclRefExpr for the "other" object. 14010 RefBuilder OtherRef(Other, OtherRefType); 14011 14012 // Builds the "this" pointer. 14013 ThisBuilder This; 14014 14015 // Assign base classes. 14016 bool Invalid = false; 14017 for (auto &Base : ClassDecl->bases()) { 14018 // Form the assignment: 14019 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14020 QualType BaseType = Base.getType().getUnqualifiedType(); 14021 if (!BaseType->isRecordType()) { 14022 Invalid = true; 14023 continue; 14024 } 14025 14026 CXXCastPath BasePath; 14027 BasePath.push_back(&Base); 14028 14029 // Construct the "from" expression, which is an implicit cast to the 14030 // appropriately-qualified base type. 14031 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14032 VK_LValue, BasePath); 14033 14034 // Dereference "this". 14035 DerefBuilder DerefThis(This); 14036 CastBuilder To(DerefThis, 14037 Context.getQualifiedType( 14038 BaseType, CopyAssignOperator->getMethodQualifiers()), 14039 VK_LValue, BasePath); 14040 14041 // Build the copy. 14042 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14043 To, From, 14044 /*CopyingBaseSubobject=*/true, 14045 /*Copying=*/true); 14046 if (Copy.isInvalid()) { 14047 CopyAssignOperator->setInvalidDecl(); 14048 return; 14049 } 14050 14051 // Success! Record the copy. 14052 Statements.push_back(Copy.getAs<Expr>()); 14053 } 14054 14055 // Assign non-static members. 14056 for (auto *Field : ClassDecl->fields()) { 14057 // FIXME: We should form some kind of AST representation for the implied 14058 // memcpy in a union copy operation. 14059 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14060 continue; 14061 14062 if (Field->isInvalidDecl()) { 14063 Invalid = true; 14064 continue; 14065 } 14066 14067 // Check for members of reference type; we can't copy those. 14068 if (Field->getType()->isReferenceType()) { 14069 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14070 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14071 Diag(Field->getLocation(), diag::note_declared_at); 14072 Invalid = true; 14073 continue; 14074 } 14075 14076 // Check for members of const-qualified, non-class type. 14077 QualType BaseType = Context.getBaseElementType(Field->getType()); 14078 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14079 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14080 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14081 Diag(Field->getLocation(), diag::note_declared_at); 14082 Invalid = true; 14083 continue; 14084 } 14085 14086 // Suppress assigning zero-width bitfields. 14087 if (Field->isZeroLengthBitField(Context)) 14088 continue; 14089 14090 QualType FieldType = Field->getType().getNonReferenceType(); 14091 if (FieldType->isIncompleteArrayType()) { 14092 assert(ClassDecl->hasFlexibleArrayMember() && 14093 "Incomplete array type is not valid"); 14094 continue; 14095 } 14096 14097 // Build references to the field in the object we're copying from and to. 14098 CXXScopeSpec SS; // Intentionally empty 14099 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14100 LookupMemberName); 14101 MemberLookup.addDecl(Field); 14102 MemberLookup.resolveKind(); 14103 14104 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14105 14106 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14107 14108 // Build the copy of this field. 14109 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14110 To, From, 14111 /*CopyingBaseSubobject=*/false, 14112 /*Copying=*/true); 14113 if (Copy.isInvalid()) { 14114 CopyAssignOperator->setInvalidDecl(); 14115 return; 14116 } 14117 14118 // Success! Record the copy. 14119 Statements.push_back(Copy.getAs<Stmt>()); 14120 } 14121 14122 if (!Invalid) { 14123 // Add a "return *this;" 14124 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14125 14126 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14127 if (Return.isInvalid()) 14128 Invalid = true; 14129 else 14130 Statements.push_back(Return.getAs<Stmt>()); 14131 } 14132 14133 if (Invalid) { 14134 CopyAssignOperator->setInvalidDecl(); 14135 return; 14136 } 14137 14138 StmtResult Body; 14139 { 14140 CompoundScopeRAII CompoundScope(*this); 14141 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14142 /*isStmtExpr=*/false); 14143 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14144 } 14145 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14146 CopyAssignOperator->markUsed(Context); 14147 14148 if (ASTMutationListener *L = getASTMutationListener()) { 14149 L->CompletedImplicitDefinition(CopyAssignOperator); 14150 } 14151 } 14152 14153 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14154 assert(ClassDecl->needsImplicitMoveAssignment()); 14155 14156 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14157 if (DSM.isAlreadyBeingDeclared()) 14158 return nullptr; 14159 14160 // Note: The following rules are largely analoguous to the move 14161 // constructor rules. 14162 14163 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14164 LangAS AS = getDefaultCXXMethodAddrSpace(); 14165 if (AS != LangAS::Default) 14166 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14167 QualType RetType = Context.getLValueReferenceType(ArgType); 14168 ArgType = Context.getRValueReferenceType(ArgType); 14169 14170 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14171 CXXMoveAssignment, 14172 false); 14173 14174 // An implicitly-declared move assignment operator is an inline public 14175 // member of its class. 14176 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14177 SourceLocation ClassLoc = ClassDecl->getLocation(); 14178 DeclarationNameInfo NameInfo(Name, ClassLoc); 14179 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14180 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14181 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14182 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 14183 SourceLocation()); 14184 MoveAssignment->setAccess(AS_public); 14185 MoveAssignment->setDefaulted(); 14186 MoveAssignment->setImplicit(); 14187 14188 if (getLangOpts().CUDA) { 14189 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14190 MoveAssignment, 14191 /* ConstRHS */ false, 14192 /* Diagnose */ false); 14193 } 14194 14195 // Build an exception specification pointing back at this member. 14196 FunctionProtoType::ExtProtoInfo EPI = 14197 getImplicitMethodEPI(*this, MoveAssignment); 14198 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14199 14200 // Add the parameter to the operator. 14201 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14202 ClassLoc, ClassLoc, 14203 /*Id=*/nullptr, ArgType, 14204 /*TInfo=*/nullptr, SC_None, 14205 nullptr); 14206 MoveAssignment->setParams(FromParam); 14207 14208 MoveAssignment->setTrivial( 14209 ClassDecl->needsOverloadResolutionForMoveAssignment() 14210 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14211 : ClassDecl->hasTrivialMoveAssignment()); 14212 14213 // Note that we have added this copy-assignment operator. 14214 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14215 14216 Scope *S = getScopeForContext(ClassDecl); 14217 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14218 14219 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14220 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14221 SetDeclDeleted(MoveAssignment, ClassLoc); 14222 } 14223 14224 if (S) 14225 PushOnScopeChains(MoveAssignment, S, false); 14226 ClassDecl->addDecl(MoveAssignment); 14227 14228 return MoveAssignment; 14229 } 14230 14231 /// Check if we're implicitly defining a move assignment operator for a class 14232 /// with virtual bases. Such a move assignment might move-assign the virtual 14233 /// base multiple times. 14234 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14235 SourceLocation CurrentLocation) { 14236 assert(!Class->isDependentContext() && "should not define dependent move"); 14237 14238 // Only a virtual base could get implicitly move-assigned multiple times. 14239 // Only a non-trivial move assignment can observe this. We only want to 14240 // diagnose if we implicitly define an assignment operator that assigns 14241 // two base classes, both of which move-assign the same virtual base. 14242 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14243 Class->getNumBases() < 2) 14244 return; 14245 14246 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14247 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14248 VBaseMap VBases; 14249 14250 for (auto &BI : Class->bases()) { 14251 Worklist.push_back(&BI); 14252 while (!Worklist.empty()) { 14253 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14254 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14255 14256 // If the base has no non-trivial move assignment operators, 14257 // we don't care about moves from it. 14258 if (!Base->hasNonTrivialMoveAssignment()) 14259 continue; 14260 14261 // If there's nothing virtual here, skip it. 14262 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14263 continue; 14264 14265 // If we're not actually going to call a move assignment for this base, 14266 // or the selected move assignment is trivial, skip it. 14267 Sema::SpecialMemberOverloadResult SMOR = 14268 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14269 /*ConstArg*/false, /*VolatileArg*/false, 14270 /*RValueThis*/true, /*ConstThis*/false, 14271 /*VolatileThis*/false); 14272 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14273 !SMOR.getMethod()->isMoveAssignmentOperator()) 14274 continue; 14275 14276 if (BaseSpec->isVirtual()) { 14277 // We're going to move-assign this virtual base, and its move 14278 // assignment operator is not trivial. If this can happen for 14279 // multiple distinct direct bases of Class, diagnose it. (If it 14280 // only happens in one base, we'll diagnose it when synthesizing 14281 // that base class's move assignment operator.) 14282 CXXBaseSpecifier *&Existing = 14283 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14284 .first->second; 14285 if (Existing && Existing != &BI) { 14286 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14287 << Class << Base; 14288 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14289 << (Base->getCanonicalDecl() == 14290 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14291 << Base << Existing->getType() << Existing->getSourceRange(); 14292 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14293 << (Base->getCanonicalDecl() == 14294 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14295 << Base << BI.getType() << BaseSpec->getSourceRange(); 14296 14297 // Only diagnose each vbase once. 14298 Existing = nullptr; 14299 } 14300 } else { 14301 // Only walk over bases that have defaulted move assignment operators. 14302 // We assume that any user-provided move assignment operator handles 14303 // the multiple-moves-of-vbase case itself somehow. 14304 if (!SMOR.getMethod()->isDefaulted()) 14305 continue; 14306 14307 // We're going to move the base classes of Base. Add them to the list. 14308 for (auto &BI : Base->bases()) 14309 Worklist.push_back(&BI); 14310 } 14311 } 14312 } 14313 } 14314 14315 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14316 CXXMethodDecl *MoveAssignOperator) { 14317 assert((MoveAssignOperator->isDefaulted() && 14318 MoveAssignOperator->isOverloadedOperator() && 14319 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14320 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14321 !MoveAssignOperator->isDeleted()) && 14322 "DefineImplicitMoveAssignment called for wrong function"); 14323 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14324 return; 14325 14326 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14327 if (ClassDecl->isInvalidDecl()) { 14328 MoveAssignOperator->setInvalidDecl(); 14329 return; 14330 } 14331 14332 // C++0x [class.copy]p28: 14333 // The implicitly-defined or move assignment operator for a non-union class 14334 // X performs memberwise move assignment of its subobjects. The direct base 14335 // classes of X are assigned first, in the order of their declaration in the 14336 // base-specifier-list, and then the immediate non-static data members of X 14337 // are assigned, in the order in which they were declared in the class 14338 // definition. 14339 14340 // Issue a warning if our implicit move assignment operator will move 14341 // from a virtual base more than once. 14342 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14343 14344 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14345 14346 // The exception specification is needed because we are defining the 14347 // function. 14348 ResolveExceptionSpec(CurrentLocation, 14349 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14350 14351 // Add a context note for diagnostics produced after this point. 14352 Scope.addContextNote(CurrentLocation); 14353 14354 // The statements that form the synthesized function body. 14355 SmallVector<Stmt*, 8> Statements; 14356 14357 // The parameter for the "other" object, which we are move from. 14358 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14359 QualType OtherRefType = 14360 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14361 14362 // Our location for everything implicitly-generated. 14363 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14364 ? MoveAssignOperator->getEndLoc() 14365 : MoveAssignOperator->getLocation(); 14366 14367 // Builds a reference to the "other" object. 14368 RefBuilder OtherRef(Other, OtherRefType); 14369 // Cast to rvalue. 14370 MoveCastBuilder MoveOther(OtherRef); 14371 14372 // Builds the "this" pointer. 14373 ThisBuilder This; 14374 14375 // Assign base classes. 14376 bool Invalid = false; 14377 for (auto &Base : ClassDecl->bases()) { 14378 // C++11 [class.copy]p28: 14379 // It is unspecified whether subobjects representing virtual base classes 14380 // are assigned more than once by the implicitly-defined copy assignment 14381 // operator. 14382 // FIXME: Do not assign to a vbase that will be assigned by some other base 14383 // class. For a move-assignment, this can result in the vbase being moved 14384 // multiple times. 14385 14386 // Form the assignment: 14387 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14388 QualType BaseType = Base.getType().getUnqualifiedType(); 14389 if (!BaseType->isRecordType()) { 14390 Invalid = true; 14391 continue; 14392 } 14393 14394 CXXCastPath BasePath; 14395 BasePath.push_back(&Base); 14396 14397 // Construct the "from" expression, which is an implicit cast to the 14398 // appropriately-qualified base type. 14399 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14400 14401 // Dereference "this". 14402 DerefBuilder DerefThis(This); 14403 14404 // Implicitly cast "this" to the appropriately-qualified base type. 14405 CastBuilder To(DerefThis, 14406 Context.getQualifiedType( 14407 BaseType, MoveAssignOperator->getMethodQualifiers()), 14408 VK_LValue, BasePath); 14409 14410 // Build the move. 14411 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14412 To, From, 14413 /*CopyingBaseSubobject=*/true, 14414 /*Copying=*/false); 14415 if (Move.isInvalid()) { 14416 MoveAssignOperator->setInvalidDecl(); 14417 return; 14418 } 14419 14420 // Success! Record the move. 14421 Statements.push_back(Move.getAs<Expr>()); 14422 } 14423 14424 // Assign non-static members. 14425 for (auto *Field : ClassDecl->fields()) { 14426 // FIXME: We should form some kind of AST representation for the implied 14427 // memcpy in a union copy operation. 14428 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14429 continue; 14430 14431 if (Field->isInvalidDecl()) { 14432 Invalid = true; 14433 continue; 14434 } 14435 14436 // Check for members of reference type; we can't move those. 14437 if (Field->getType()->isReferenceType()) { 14438 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14439 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14440 Diag(Field->getLocation(), diag::note_declared_at); 14441 Invalid = true; 14442 continue; 14443 } 14444 14445 // Check for members of const-qualified, non-class type. 14446 QualType BaseType = Context.getBaseElementType(Field->getType()); 14447 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14448 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14449 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14450 Diag(Field->getLocation(), diag::note_declared_at); 14451 Invalid = true; 14452 continue; 14453 } 14454 14455 // Suppress assigning zero-width bitfields. 14456 if (Field->isZeroLengthBitField(Context)) 14457 continue; 14458 14459 QualType FieldType = Field->getType().getNonReferenceType(); 14460 if (FieldType->isIncompleteArrayType()) { 14461 assert(ClassDecl->hasFlexibleArrayMember() && 14462 "Incomplete array type is not valid"); 14463 continue; 14464 } 14465 14466 // Build references to the field in the object we're copying from and to. 14467 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14468 LookupMemberName); 14469 MemberLookup.addDecl(Field); 14470 MemberLookup.resolveKind(); 14471 MemberBuilder From(MoveOther, OtherRefType, 14472 /*IsArrow=*/false, MemberLookup); 14473 MemberBuilder To(This, getCurrentThisType(), 14474 /*IsArrow=*/true, MemberLookup); 14475 14476 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14477 "Member reference with rvalue base must be rvalue except for reference " 14478 "members, which aren't allowed for move assignment."); 14479 14480 // Build the move of this field. 14481 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14482 To, From, 14483 /*CopyingBaseSubobject=*/false, 14484 /*Copying=*/false); 14485 if (Move.isInvalid()) { 14486 MoveAssignOperator->setInvalidDecl(); 14487 return; 14488 } 14489 14490 // Success! Record the copy. 14491 Statements.push_back(Move.getAs<Stmt>()); 14492 } 14493 14494 if (!Invalid) { 14495 // Add a "return *this;" 14496 ExprResult ThisObj = 14497 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14498 14499 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14500 if (Return.isInvalid()) 14501 Invalid = true; 14502 else 14503 Statements.push_back(Return.getAs<Stmt>()); 14504 } 14505 14506 if (Invalid) { 14507 MoveAssignOperator->setInvalidDecl(); 14508 return; 14509 } 14510 14511 StmtResult Body; 14512 { 14513 CompoundScopeRAII CompoundScope(*this); 14514 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14515 /*isStmtExpr=*/false); 14516 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14517 } 14518 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14519 MoveAssignOperator->markUsed(Context); 14520 14521 if (ASTMutationListener *L = getASTMutationListener()) { 14522 L->CompletedImplicitDefinition(MoveAssignOperator); 14523 } 14524 } 14525 14526 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14527 CXXRecordDecl *ClassDecl) { 14528 // C++ [class.copy]p4: 14529 // If the class definition does not explicitly declare a copy 14530 // constructor, one is declared implicitly. 14531 assert(ClassDecl->needsImplicitCopyConstructor()); 14532 14533 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14534 if (DSM.isAlreadyBeingDeclared()) 14535 return nullptr; 14536 14537 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14538 QualType ArgType = ClassType; 14539 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14540 if (Const) 14541 ArgType = ArgType.withConst(); 14542 14543 LangAS AS = getDefaultCXXMethodAddrSpace(); 14544 if (AS != LangAS::Default) 14545 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14546 14547 ArgType = Context.getLValueReferenceType(ArgType); 14548 14549 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14550 CXXCopyConstructor, 14551 Const); 14552 14553 DeclarationName Name 14554 = Context.DeclarationNames.getCXXConstructorName( 14555 Context.getCanonicalType(ClassType)); 14556 SourceLocation ClassLoc = ClassDecl->getLocation(); 14557 DeclarationNameInfo NameInfo(Name, ClassLoc); 14558 14559 // An implicitly-declared copy constructor is an inline public 14560 // member of its class. 14561 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14562 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14563 ExplicitSpecifier(), 14564 /*isInline=*/true, 14565 /*isImplicitlyDeclared=*/true, 14566 Constexpr ? CSK_constexpr : CSK_unspecified); 14567 CopyConstructor->setAccess(AS_public); 14568 CopyConstructor->setDefaulted(); 14569 14570 if (getLangOpts().CUDA) { 14571 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14572 CopyConstructor, 14573 /* ConstRHS */ Const, 14574 /* Diagnose */ false); 14575 } 14576 14577 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14578 14579 // Add the parameter to the constructor. 14580 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14581 ClassLoc, ClassLoc, 14582 /*IdentifierInfo=*/nullptr, 14583 ArgType, /*TInfo=*/nullptr, 14584 SC_None, nullptr); 14585 CopyConstructor->setParams(FromParam); 14586 14587 CopyConstructor->setTrivial( 14588 ClassDecl->needsOverloadResolutionForCopyConstructor() 14589 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14590 : ClassDecl->hasTrivialCopyConstructor()); 14591 14592 CopyConstructor->setTrivialForCall( 14593 ClassDecl->hasAttr<TrivialABIAttr>() || 14594 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14595 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14596 TAH_ConsiderTrivialABI) 14597 : ClassDecl->hasTrivialCopyConstructorForCall())); 14598 14599 // Note that we have declared this constructor. 14600 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14601 14602 Scope *S = getScopeForContext(ClassDecl); 14603 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14604 14605 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14606 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14607 SetDeclDeleted(CopyConstructor, ClassLoc); 14608 } 14609 14610 if (S) 14611 PushOnScopeChains(CopyConstructor, S, false); 14612 ClassDecl->addDecl(CopyConstructor); 14613 14614 return CopyConstructor; 14615 } 14616 14617 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14618 CXXConstructorDecl *CopyConstructor) { 14619 assert((CopyConstructor->isDefaulted() && 14620 CopyConstructor->isCopyConstructor() && 14621 !CopyConstructor->doesThisDeclarationHaveABody() && 14622 !CopyConstructor->isDeleted()) && 14623 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14624 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14625 return; 14626 14627 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14628 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14629 14630 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14631 14632 // The exception specification is needed because we are defining the 14633 // function. 14634 ResolveExceptionSpec(CurrentLocation, 14635 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14636 MarkVTableUsed(CurrentLocation, ClassDecl); 14637 14638 // Add a context note for diagnostics produced after this point. 14639 Scope.addContextNote(CurrentLocation); 14640 14641 // C++11 [class.copy]p7: 14642 // The [definition of an implicitly declared copy constructor] is 14643 // deprecated if the class has a user-declared copy assignment operator 14644 // or a user-declared destructor. 14645 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14646 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14647 14648 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14649 CopyConstructor->setInvalidDecl(); 14650 } else { 14651 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14652 ? CopyConstructor->getEndLoc() 14653 : CopyConstructor->getLocation(); 14654 Sema::CompoundScopeRAII CompoundScope(*this); 14655 CopyConstructor->setBody( 14656 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14657 CopyConstructor->markUsed(Context); 14658 } 14659 14660 if (ASTMutationListener *L = getASTMutationListener()) { 14661 L->CompletedImplicitDefinition(CopyConstructor); 14662 } 14663 } 14664 14665 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14666 CXXRecordDecl *ClassDecl) { 14667 assert(ClassDecl->needsImplicitMoveConstructor()); 14668 14669 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14670 if (DSM.isAlreadyBeingDeclared()) 14671 return nullptr; 14672 14673 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14674 14675 QualType ArgType = ClassType; 14676 LangAS AS = getDefaultCXXMethodAddrSpace(); 14677 if (AS != LangAS::Default) 14678 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14679 ArgType = Context.getRValueReferenceType(ArgType); 14680 14681 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14682 CXXMoveConstructor, 14683 false); 14684 14685 DeclarationName Name 14686 = Context.DeclarationNames.getCXXConstructorName( 14687 Context.getCanonicalType(ClassType)); 14688 SourceLocation ClassLoc = ClassDecl->getLocation(); 14689 DeclarationNameInfo NameInfo(Name, ClassLoc); 14690 14691 // C++11 [class.copy]p11: 14692 // An implicitly-declared copy/move constructor is an inline public 14693 // member of its class. 14694 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14695 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14696 ExplicitSpecifier(), 14697 /*isInline=*/true, 14698 /*isImplicitlyDeclared=*/true, 14699 Constexpr ? CSK_constexpr : CSK_unspecified); 14700 MoveConstructor->setAccess(AS_public); 14701 MoveConstructor->setDefaulted(); 14702 14703 if (getLangOpts().CUDA) { 14704 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14705 MoveConstructor, 14706 /* ConstRHS */ false, 14707 /* Diagnose */ false); 14708 } 14709 14710 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14711 14712 // Add the parameter to the constructor. 14713 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14714 ClassLoc, ClassLoc, 14715 /*IdentifierInfo=*/nullptr, 14716 ArgType, /*TInfo=*/nullptr, 14717 SC_None, nullptr); 14718 MoveConstructor->setParams(FromParam); 14719 14720 MoveConstructor->setTrivial( 14721 ClassDecl->needsOverloadResolutionForMoveConstructor() 14722 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14723 : ClassDecl->hasTrivialMoveConstructor()); 14724 14725 MoveConstructor->setTrivialForCall( 14726 ClassDecl->hasAttr<TrivialABIAttr>() || 14727 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14728 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14729 TAH_ConsiderTrivialABI) 14730 : ClassDecl->hasTrivialMoveConstructorForCall())); 14731 14732 // Note that we have declared this constructor. 14733 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14734 14735 Scope *S = getScopeForContext(ClassDecl); 14736 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14737 14738 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14739 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14740 SetDeclDeleted(MoveConstructor, ClassLoc); 14741 } 14742 14743 if (S) 14744 PushOnScopeChains(MoveConstructor, S, false); 14745 ClassDecl->addDecl(MoveConstructor); 14746 14747 return MoveConstructor; 14748 } 14749 14750 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14751 CXXConstructorDecl *MoveConstructor) { 14752 assert((MoveConstructor->isDefaulted() && 14753 MoveConstructor->isMoveConstructor() && 14754 !MoveConstructor->doesThisDeclarationHaveABody() && 14755 !MoveConstructor->isDeleted()) && 14756 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14757 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14758 return; 14759 14760 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14761 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14762 14763 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14764 14765 // The exception specification is needed because we are defining the 14766 // function. 14767 ResolveExceptionSpec(CurrentLocation, 14768 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14769 MarkVTableUsed(CurrentLocation, ClassDecl); 14770 14771 // Add a context note for diagnostics produced after this point. 14772 Scope.addContextNote(CurrentLocation); 14773 14774 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14775 MoveConstructor->setInvalidDecl(); 14776 } else { 14777 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14778 ? MoveConstructor->getEndLoc() 14779 : MoveConstructor->getLocation(); 14780 Sema::CompoundScopeRAII CompoundScope(*this); 14781 MoveConstructor->setBody(ActOnCompoundStmt( 14782 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14783 MoveConstructor->markUsed(Context); 14784 } 14785 14786 if (ASTMutationListener *L = getASTMutationListener()) { 14787 L->CompletedImplicitDefinition(MoveConstructor); 14788 } 14789 } 14790 14791 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14792 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14793 } 14794 14795 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14796 SourceLocation CurrentLocation, 14797 CXXConversionDecl *Conv) { 14798 SynthesizedFunctionScope Scope(*this, Conv); 14799 assert(!Conv->getReturnType()->isUndeducedType()); 14800 14801 CXXRecordDecl *Lambda = Conv->getParent(); 14802 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14803 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14804 14805 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14806 CallOp = InstantiateFunctionDeclaration( 14807 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14808 if (!CallOp) 14809 return; 14810 14811 Invoker = InstantiateFunctionDeclaration( 14812 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14813 if (!Invoker) 14814 return; 14815 } 14816 14817 if (CallOp->isInvalidDecl()) 14818 return; 14819 14820 // Mark the call operator referenced (and add to pending instantiations 14821 // if necessary). 14822 // For both the conversion and static-invoker template specializations 14823 // we construct their body's in this function, so no need to add them 14824 // to the PendingInstantiations. 14825 MarkFunctionReferenced(CurrentLocation, CallOp); 14826 14827 // Fill in the __invoke function with a dummy implementation. IR generation 14828 // will fill in the actual details. Update its type in case it contained 14829 // an 'auto'. 14830 Invoker->markUsed(Context); 14831 Invoker->setReferenced(); 14832 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14833 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14834 14835 // Construct the body of the conversion function { return __invoke; }. 14836 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14837 VK_LValue, Conv->getLocation()); 14838 assert(FunctionRef && "Can't refer to __invoke function?"); 14839 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14840 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14841 Conv->getLocation())); 14842 Conv->markUsed(Context); 14843 Conv->setReferenced(); 14844 14845 if (ASTMutationListener *L = getASTMutationListener()) { 14846 L->CompletedImplicitDefinition(Conv); 14847 L->CompletedImplicitDefinition(Invoker); 14848 } 14849 } 14850 14851 14852 14853 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14854 SourceLocation CurrentLocation, 14855 CXXConversionDecl *Conv) 14856 { 14857 assert(!Conv->getParent()->isGenericLambda()); 14858 14859 SynthesizedFunctionScope Scope(*this, Conv); 14860 14861 // Copy-initialize the lambda object as needed to capture it. 14862 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14863 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14864 14865 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14866 Conv->getLocation(), 14867 Conv, DerefThis); 14868 14869 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14870 // behavior. Note that only the general conversion function does this 14871 // (since it's unusable otherwise); in the case where we inline the 14872 // block literal, it has block literal lifetime semantics. 14873 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14874 BuildBlock = ImplicitCastExpr::Create( 14875 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14876 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14877 14878 if (BuildBlock.isInvalid()) { 14879 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14880 Conv->setInvalidDecl(); 14881 return; 14882 } 14883 14884 // Create the return statement that returns the block from the conversion 14885 // function. 14886 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14887 if (Return.isInvalid()) { 14888 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14889 Conv->setInvalidDecl(); 14890 return; 14891 } 14892 14893 // Set the body of the conversion function. 14894 Stmt *ReturnS = Return.get(); 14895 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14896 Conv->getLocation())); 14897 Conv->markUsed(Context); 14898 14899 // We're done; notify the mutation listener, if any. 14900 if (ASTMutationListener *L = getASTMutationListener()) { 14901 L->CompletedImplicitDefinition(Conv); 14902 } 14903 } 14904 14905 /// Determine whether the given list arguments contains exactly one 14906 /// "real" (non-default) argument. 14907 static bool hasOneRealArgument(MultiExprArg Args) { 14908 switch (Args.size()) { 14909 case 0: 14910 return false; 14911 14912 default: 14913 if (!Args[1]->isDefaultArgument()) 14914 return false; 14915 14916 LLVM_FALLTHROUGH; 14917 case 1: 14918 return !Args[0]->isDefaultArgument(); 14919 } 14920 14921 return false; 14922 } 14923 14924 ExprResult 14925 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14926 NamedDecl *FoundDecl, 14927 CXXConstructorDecl *Constructor, 14928 MultiExprArg ExprArgs, 14929 bool HadMultipleCandidates, 14930 bool IsListInitialization, 14931 bool IsStdInitListInitialization, 14932 bool RequiresZeroInit, 14933 unsigned ConstructKind, 14934 SourceRange ParenRange) { 14935 bool Elidable = false; 14936 14937 // C++0x [class.copy]p34: 14938 // When certain criteria are met, an implementation is allowed to 14939 // omit the copy/move construction of a class object, even if the 14940 // copy/move constructor and/or destructor for the object have 14941 // side effects. [...] 14942 // - when a temporary class object that has not been bound to a 14943 // reference (12.2) would be copied/moved to a class object 14944 // with the same cv-unqualified type, the copy/move operation 14945 // can be omitted by constructing the temporary object 14946 // directly into the target of the omitted copy/move 14947 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14948 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14949 Expr *SubExpr = ExprArgs[0]; 14950 Elidable = SubExpr->isTemporaryObject( 14951 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14952 } 14953 14954 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14955 FoundDecl, Constructor, 14956 Elidable, ExprArgs, HadMultipleCandidates, 14957 IsListInitialization, 14958 IsStdInitListInitialization, RequiresZeroInit, 14959 ConstructKind, ParenRange); 14960 } 14961 14962 ExprResult 14963 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14964 NamedDecl *FoundDecl, 14965 CXXConstructorDecl *Constructor, 14966 bool Elidable, 14967 MultiExprArg ExprArgs, 14968 bool HadMultipleCandidates, 14969 bool IsListInitialization, 14970 bool IsStdInitListInitialization, 14971 bool RequiresZeroInit, 14972 unsigned ConstructKind, 14973 SourceRange ParenRange) { 14974 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14975 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14976 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14977 return ExprError(); 14978 } 14979 14980 return BuildCXXConstructExpr( 14981 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14982 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14983 RequiresZeroInit, ConstructKind, ParenRange); 14984 } 14985 14986 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14987 /// including handling of its default argument expressions. 14988 ExprResult 14989 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14990 CXXConstructorDecl *Constructor, 14991 bool Elidable, 14992 MultiExprArg ExprArgs, 14993 bool HadMultipleCandidates, 14994 bool IsListInitialization, 14995 bool IsStdInitListInitialization, 14996 bool RequiresZeroInit, 14997 unsigned ConstructKind, 14998 SourceRange ParenRange) { 14999 assert(declaresSameEntity( 15000 Constructor->getParent(), 15001 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15002 "given constructor for wrong type"); 15003 MarkFunctionReferenced(ConstructLoc, Constructor); 15004 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15005 return ExprError(); 15006 if (getLangOpts().SYCLIsDevice && 15007 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15008 return ExprError(); 15009 15010 return CheckForImmediateInvocation( 15011 CXXConstructExpr::Create( 15012 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15013 HadMultipleCandidates, IsListInitialization, 15014 IsStdInitListInitialization, RequiresZeroInit, 15015 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15016 ParenRange), 15017 Constructor); 15018 } 15019 15020 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15021 assert(Field->hasInClassInitializer()); 15022 15023 // If we already have the in-class initializer nothing needs to be done. 15024 if (Field->getInClassInitializer()) 15025 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15026 15027 // If we might have already tried and failed to instantiate, don't try again. 15028 if (Field->isInvalidDecl()) 15029 return ExprError(); 15030 15031 // Maybe we haven't instantiated the in-class initializer. Go check the 15032 // pattern FieldDecl to see if it has one. 15033 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15034 15035 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15036 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15037 DeclContext::lookup_result Lookup = 15038 ClassPattern->lookup(Field->getDeclName()); 15039 15040 // Lookup can return at most two results: the pattern for the field, or the 15041 // injected class name of the parent record. No other member can have the 15042 // same name as the field. 15043 // In modules mode, lookup can return multiple results (coming from 15044 // different modules). 15045 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 15046 "more than two lookup results for field name"); 15047 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 15048 if (!Pattern) { 15049 assert(isa<CXXRecordDecl>(Lookup[0]) && 15050 "cannot have other non-field member with same name"); 15051 for (auto L : Lookup) 15052 if (isa<FieldDecl>(L)) { 15053 Pattern = cast<FieldDecl>(L); 15054 break; 15055 } 15056 assert(Pattern && "We must have set the Pattern!"); 15057 } 15058 15059 if (!Pattern->hasInClassInitializer() || 15060 InstantiateInClassInitializer(Loc, Field, Pattern, 15061 getTemplateInstantiationArgs(Field))) { 15062 // Don't diagnose this again. 15063 Field->setInvalidDecl(); 15064 return ExprError(); 15065 } 15066 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15067 } 15068 15069 // DR1351: 15070 // If the brace-or-equal-initializer of a non-static data member 15071 // invokes a defaulted default constructor of its class or of an 15072 // enclosing class in a potentially evaluated subexpression, the 15073 // program is ill-formed. 15074 // 15075 // This resolution is unworkable: the exception specification of the 15076 // default constructor can be needed in an unevaluated context, in 15077 // particular, in the operand of a noexcept-expression, and we can be 15078 // unable to compute an exception specification for an enclosed class. 15079 // 15080 // Any attempt to resolve the exception specification of a defaulted default 15081 // constructor before the initializer is lexically complete will ultimately 15082 // come here at which point we can diagnose it. 15083 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15084 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15085 << OutermostClass << Field; 15086 Diag(Field->getEndLoc(), 15087 diag::note_default_member_initializer_not_yet_parsed); 15088 // Recover by marking the field invalid, unless we're in a SFINAE context. 15089 if (!isSFINAEContext()) 15090 Field->setInvalidDecl(); 15091 return ExprError(); 15092 } 15093 15094 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15095 if (VD->isInvalidDecl()) return; 15096 // If initializing the variable failed, don't also diagnose problems with 15097 // the desctructor, they're likely related. 15098 if (VD->getInit() && VD->getInit()->containsErrors()) 15099 return; 15100 15101 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15102 if (ClassDecl->isInvalidDecl()) return; 15103 if (ClassDecl->hasIrrelevantDestructor()) return; 15104 if (ClassDecl->isDependentContext()) return; 15105 15106 if (VD->isNoDestroy(getASTContext())) 15107 return; 15108 15109 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15110 15111 // If this is an array, we'll require the destructor during initialization, so 15112 // we can skip over this. We still want to emit exit-time destructor warnings 15113 // though. 15114 if (!VD->getType()->isArrayType()) { 15115 MarkFunctionReferenced(VD->getLocation(), Destructor); 15116 CheckDestructorAccess(VD->getLocation(), Destructor, 15117 PDiag(diag::err_access_dtor_var) 15118 << VD->getDeclName() << VD->getType()); 15119 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15120 } 15121 15122 if (Destructor->isTrivial()) return; 15123 15124 // If the destructor is constexpr, check whether the variable has constant 15125 // destruction now. 15126 if (Destructor->isConstexpr()) { 15127 bool HasConstantInit = false; 15128 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15129 HasConstantInit = VD->evaluateValue(); 15130 SmallVector<PartialDiagnosticAt, 8> Notes; 15131 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15132 HasConstantInit) { 15133 Diag(VD->getLocation(), 15134 diag::err_constexpr_var_requires_const_destruction) << VD; 15135 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15136 Diag(Notes[I].first, Notes[I].second); 15137 } 15138 } 15139 15140 if (!VD->hasGlobalStorage()) return; 15141 15142 // Emit warning for non-trivial dtor in global scope (a real global, 15143 // class-static, function-static). 15144 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15145 15146 // TODO: this should be re-enabled for static locals by !CXAAtExit 15147 if (!VD->isStaticLocal()) 15148 Diag(VD->getLocation(), diag::warn_global_destructor); 15149 } 15150 15151 /// Given a constructor and the set of arguments provided for the 15152 /// constructor, convert the arguments and add any required default arguments 15153 /// to form a proper call to this constructor. 15154 /// 15155 /// \returns true if an error occurred, false otherwise. 15156 bool 15157 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15158 MultiExprArg ArgsPtr, 15159 SourceLocation Loc, 15160 SmallVectorImpl<Expr*> &ConvertedArgs, 15161 bool AllowExplicit, 15162 bool IsListInitialization) { 15163 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15164 unsigned NumArgs = ArgsPtr.size(); 15165 Expr **Args = ArgsPtr.data(); 15166 15167 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15168 unsigned NumParams = Proto->getNumParams(); 15169 15170 // If too few arguments are available, we'll fill in the rest with defaults. 15171 if (NumArgs < NumParams) 15172 ConvertedArgs.reserve(NumParams); 15173 else 15174 ConvertedArgs.reserve(NumArgs); 15175 15176 VariadicCallType CallType = 15177 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15178 SmallVector<Expr *, 8> AllArgs; 15179 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15180 Proto, 0, 15181 llvm::makeArrayRef(Args, NumArgs), 15182 AllArgs, 15183 CallType, AllowExplicit, 15184 IsListInitialization); 15185 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15186 15187 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15188 15189 CheckConstructorCall(Constructor, 15190 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15191 Proto, Loc); 15192 15193 return Invalid; 15194 } 15195 15196 static inline bool 15197 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15198 const FunctionDecl *FnDecl) { 15199 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15200 if (isa<NamespaceDecl>(DC)) { 15201 return SemaRef.Diag(FnDecl->getLocation(), 15202 diag::err_operator_new_delete_declared_in_namespace) 15203 << FnDecl->getDeclName(); 15204 } 15205 15206 if (isa<TranslationUnitDecl>(DC) && 15207 FnDecl->getStorageClass() == SC_Static) { 15208 return SemaRef.Diag(FnDecl->getLocation(), 15209 diag::err_operator_new_delete_declared_static) 15210 << FnDecl->getDeclName(); 15211 } 15212 15213 return false; 15214 } 15215 15216 static QualType 15217 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 15218 QualType QTy = PtrTy->getPointeeType(); 15219 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 15220 return SemaRef.Context.getPointerType(QTy); 15221 } 15222 15223 static inline bool 15224 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15225 CanQualType ExpectedResultType, 15226 CanQualType ExpectedFirstParamType, 15227 unsigned DependentParamTypeDiag, 15228 unsigned InvalidParamTypeDiag) { 15229 QualType ResultType = 15230 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15231 15232 // The operator is valid on any address space for OpenCL. 15233 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15234 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 15235 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15236 } 15237 } 15238 15239 // Check that the result type is what we expect. 15240 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15241 // Reject even if the type is dependent; an operator delete function is 15242 // required to have a non-dependent result type. 15243 return SemaRef.Diag( 15244 FnDecl->getLocation(), 15245 ResultType->isDependentType() 15246 ? diag::err_operator_new_delete_dependent_result_type 15247 : diag::err_operator_new_delete_invalid_result_type) 15248 << FnDecl->getDeclName() << ExpectedResultType; 15249 } 15250 15251 // A function template must have at least 2 parameters. 15252 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15253 return SemaRef.Diag(FnDecl->getLocation(), 15254 diag::err_operator_new_delete_template_too_few_parameters) 15255 << FnDecl->getDeclName(); 15256 15257 // The function decl must have at least 1 parameter. 15258 if (FnDecl->getNumParams() == 0) 15259 return SemaRef.Diag(FnDecl->getLocation(), 15260 diag::err_operator_new_delete_too_few_parameters) 15261 << FnDecl->getDeclName(); 15262 15263 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15264 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15265 // The operator is valid on any address space for OpenCL. 15266 if (auto *PtrTy = 15267 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 15268 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15269 } 15270 } 15271 15272 // Check that the first parameter type is what we expect. 15273 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15274 ExpectedFirstParamType) { 15275 // The first parameter type is not allowed to be dependent. As a tentative 15276 // DR resolution, we allow a dependent parameter type if it is the right 15277 // type anyway, to allow destroying operator delete in class templates. 15278 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15279 ? DependentParamTypeDiag 15280 : InvalidParamTypeDiag) 15281 << FnDecl->getDeclName() << ExpectedFirstParamType; 15282 } 15283 15284 return false; 15285 } 15286 15287 static bool 15288 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15289 // C++ [basic.stc.dynamic.allocation]p1: 15290 // A program is ill-formed if an allocation function is declared in a 15291 // namespace scope other than global scope or declared static in global 15292 // scope. 15293 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15294 return true; 15295 15296 CanQualType SizeTy = 15297 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15298 15299 // C++ [basic.stc.dynamic.allocation]p1: 15300 // The return type shall be void*. The first parameter shall have type 15301 // std::size_t. 15302 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15303 SizeTy, 15304 diag::err_operator_new_dependent_param_type, 15305 diag::err_operator_new_param_type)) 15306 return true; 15307 15308 // C++ [basic.stc.dynamic.allocation]p1: 15309 // The first parameter shall not have an associated default argument. 15310 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15311 return SemaRef.Diag(FnDecl->getLocation(), 15312 diag::err_operator_new_default_arg) 15313 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15314 15315 return false; 15316 } 15317 15318 static bool 15319 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15320 // C++ [basic.stc.dynamic.deallocation]p1: 15321 // A program is ill-formed if deallocation functions are declared in a 15322 // namespace scope other than global scope or declared static in global 15323 // scope. 15324 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15325 return true; 15326 15327 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15328 15329 // C++ P0722: 15330 // Within a class C, the first parameter of a destroying operator delete 15331 // shall be of type C *. The first parameter of any other deallocation 15332 // function shall be of type void *. 15333 CanQualType ExpectedFirstParamType = 15334 MD && MD->isDestroyingOperatorDelete() 15335 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15336 SemaRef.Context.getRecordType(MD->getParent()))) 15337 : SemaRef.Context.VoidPtrTy; 15338 15339 // C++ [basic.stc.dynamic.deallocation]p2: 15340 // Each deallocation function shall return void 15341 if (CheckOperatorNewDeleteTypes( 15342 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15343 diag::err_operator_delete_dependent_param_type, 15344 diag::err_operator_delete_param_type)) 15345 return true; 15346 15347 // C++ P0722: 15348 // A destroying operator delete shall be a usual deallocation function. 15349 if (MD && !MD->getParent()->isDependentContext() && 15350 MD->isDestroyingOperatorDelete() && 15351 !SemaRef.isUsualDeallocationFunction(MD)) { 15352 SemaRef.Diag(MD->getLocation(), 15353 diag::err_destroying_operator_delete_not_usual); 15354 return true; 15355 } 15356 15357 return false; 15358 } 15359 15360 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15361 /// of this overloaded operator is well-formed. If so, returns false; 15362 /// otherwise, emits appropriate diagnostics and returns true. 15363 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15364 assert(FnDecl && FnDecl->isOverloadedOperator() && 15365 "Expected an overloaded operator declaration"); 15366 15367 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15368 15369 // C++ [over.oper]p5: 15370 // The allocation and deallocation functions, operator new, 15371 // operator new[], operator delete and operator delete[], are 15372 // described completely in 3.7.3. The attributes and restrictions 15373 // found in the rest of this subclause do not apply to them unless 15374 // explicitly stated in 3.7.3. 15375 if (Op == OO_Delete || Op == OO_Array_Delete) 15376 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15377 15378 if (Op == OO_New || Op == OO_Array_New) 15379 return CheckOperatorNewDeclaration(*this, FnDecl); 15380 15381 // C++ [over.oper]p6: 15382 // An operator function shall either be a non-static member 15383 // function or be a non-member function and have at least one 15384 // parameter whose type is a class, a reference to a class, an 15385 // enumeration, or a reference to an enumeration. 15386 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15387 if (MethodDecl->isStatic()) 15388 return Diag(FnDecl->getLocation(), 15389 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15390 } else { 15391 bool ClassOrEnumParam = false; 15392 for (auto Param : FnDecl->parameters()) { 15393 QualType ParamType = Param->getType().getNonReferenceType(); 15394 if (ParamType->isDependentType() || ParamType->isRecordType() || 15395 ParamType->isEnumeralType()) { 15396 ClassOrEnumParam = true; 15397 break; 15398 } 15399 } 15400 15401 if (!ClassOrEnumParam) 15402 return Diag(FnDecl->getLocation(), 15403 diag::err_operator_overload_needs_class_or_enum) 15404 << FnDecl->getDeclName(); 15405 } 15406 15407 // C++ [over.oper]p8: 15408 // An operator function cannot have default arguments (8.3.6), 15409 // except where explicitly stated below. 15410 // 15411 // Only the function-call operator allows default arguments 15412 // (C++ [over.call]p1). 15413 if (Op != OO_Call) { 15414 for (auto Param : FnDecl->parameters()) { 15415 if (Param->hasDefaultArg()) 15416 return Diag(Param->getLocation(), 15417 diag::err_operator_overload_default_arg) 15418 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15419 } 15420 } 15421 15422 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15423 { false, false, false } 15424 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15425 , { Unary, Binary, MemberOnly } 15426 #include "clang/Basic/OperatorKinds.def" 15427 }; 15428 15429 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15430 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15431 bool MustBeMemberOperator = OperatorUses[Op][2]; 15432 15433 // C++ [over.oper]p8: 15434 // [...] Operator functions cannot have more or fewer parameters 15435 // than the number required for the corresponding operator, as 15436 // described in the rest of this subclause. 15437 unsigned NumParams = FnDecl->getNumParams() 15438 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15439 if (Op != OO_Call && 15440 ((NumParams == 1 && !CanBeUnaryOperator) || 15441 (NumParams == 2 && !CanBeBinaryOperator) || 15442 (NumParams < 1) || (NumParams > 2))) { 15443 // We have the wrong number of parameters. 15444 unsigned ErrorKind; 15445 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15446 ErrorKind = 2; // 2 -> unary or binary. 15447 } else if (CanBeUnaryOperator) { 15448 ErrorKind = 0; // 0 -> unary 15449 } else { 15450 assert(CanBeBinaryOperator && 15451 "All non-call overloaded operators are unary or binary!"); 15452 ErrorKind = 1; // 1 -> binary 15453 } 15454 15455 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15456 << FnDecl->getDeclName() << NumParams << ErrorKind; 15457 } 15458 15459 // Overloaded operators other than operator() cannot be variadic. 15460 if (Op != OO_Call && 15461 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15462 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15463 << FnDecl->getDeclName(); 15464 } 15465 15466 // Some operators must be non-static member functions. 15467 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15468 return Diag(FnDecl->getLocation(), 15469 diag::err_operator_overload_must_be_member) 15470 << FnDecl->getDeclName(); 15471 } 15472 15473 // C++ [over.inc]p1: 15474 // The user-defined function called operator++ implements the 15475 // prefix and postfix ++ operator. If this function is a member 15476 // function with no parameters, or a non-member function with one 15477 // parameter of class or enumeration type, it defines the prefix 15478 // increment operator ++ for objects of that type. If the function 15479 // is a member function with one parameter (which shall be of type 15480 // int) or a non-member function with two parameters (the second 15481 // of which shall be of type int), it defines the postfix 15482 // increment operator ++ for objects of that type. 15483 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15484 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15485 QualType ParamType = LastParam->getType(); 15486 15487 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15488 !ParamType->isDependentType()) 15489 return Diag(LastParam->getLocation(), 15490 diag::err_operator_overload_post_incdec_must_be_int) 15491 << LastParam->getType() << (Op == OO_MinusMinus); 15492 } 15493 15494 return false; 15495 } 15496 15497 static bool 15498 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15499 FunctionTemplateDecl *TpDecl) { 15500 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15501 15502 // Must have one or two template parameters. 15503 if (TemplateParams->size() == 1) { 15504 NonTypeTemplateParmDecl *PmDecl = 15505 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15506 15507 // The template parameter must be a char parameter pack. 15508 if (PmDecl && PmDecl->isTemplateParameterPack() && 15509 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15510 return false; 15511 15512 } else if (TemplateParams->size() == 2) { 15513 TemplateTypeParmDecl *PmType = 15514 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15515 NonTypeTemplateParmDecl *PmArgs = 15516 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15517 15518 // The second template parameter must be a parameter pack with the 15519 // first template parameter as its type. 15520 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15521 PmArgs->isTemplateParameterPack()) { 15522 const TemplateTypeParmType *TArgs = 15523 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15524 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15525 TArgs->getIndex() == PmType->getIndex()) { 15526 if (!SemaRef.inTemplateInstantiation()) 15527 SemaRef.Diag(TpDecl->getLocation(), 15528 diag::ext_string_literal_operator_template); 15529 return false; 15530 } 15531 } 15532 } 15533 15534 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15535 diag::err_literal_operator_template) 15536 << TpDecl->getTemplateParameters()->getSourceRange(); 15537 return true; 15538 } 15539 15540 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15541 /// of this literal operator function is well-formed. If so, returns 15542 /// false; otherwise, emits appropriate diagnostics and returns true. 15543 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15544 if (isa<CXXMethodDecl>(FnDecl)) { 15545 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15546 << FnDecl->getDeclName(); 15547 return true; 15548 } 15549 15550 if (FnDecl->isExternC()) { 15551 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15552 if (const LinkageSpecDecl *LSD = 15553 FnDecl->getDeclContext()->getExternCContext()) 15554 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15555 return true; 15556 } 15557 15558 // This might be the definition of a literal operator template. 15559 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15560 15561 // This might be a specialization of a literal operator template. 15562 if (!TpDecl) 15563 TpDecl = FnDecl->getPrimaryTemplate(); 15564 15565 // template <char...> type operator "" name() and 15566 // template <class T, T...> type operator "" name() are the only valid 15567 // template signatures, and the only valid signatures with no parameters. 15568 if (TpDecl) { 15569 if (FnDecl->param_size() != 0) { 15570 Diag(FnDecl->getLocation(), 15571 diag::err_literal_operator_template_with_params); 15572 return true; 15573 } 15574 15575 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15576 return true; 15577 15578 } else if (FnDecl->param_size() == 1) { 15579 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15580 15581 QualType ParamType = Param->getType().getUnqualifiedType(); 15582 15583 // Only unsigned long long int, long double, any character type, and const 15584 // char * are allowed as the only parameters. 15585 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15586 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15587 Context.hasSameType(ParamType, Context.CharTy) || 15588 Context.hasSameType(ParamType, Context.WideCharTy) || 15589 Context.hasSameType(ParamType, Context.Char8Ty) || 15590 Context.hasSameType(ParamType, Context.Char16Ty) || 15591 Context.hasSameType(ParamType, Context.Char32Ty)) { 15592 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15593 QualType InnerType = Ptr->getPointeeType(); 15594 15595 // Pointer parameter must be a const char *. 15596 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15597 Context.CharTy) && 15598 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15599 Diag(Param->getSourceRange().getBegin(), 15600 diag::err_literal_operator_param) 15601 << ParamType << "'const char *'" << Param->getSourceRange(); 15602 return true; 15603 } 15604 15605 } else if (ParamType->isRealFloatingType()) { 15606 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15607 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15608 return true; 15609 15610 } else if (ParamType->isIntegerType()) { 15611 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15612 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15613 return true; 15614 15615 } else { 15616 Diag(Param->getSourceRange().getBegin(), 15617 diag::err_literal_operator_invalid_param) 15618 << ParamType << Param->getSourceRange(); 15619 return true; 15620 } 15621 15622 } else if (FnDecl->param_size() == 2) { 15623 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15624 15625 // First, verify that the first parameter is correct. 15626 15627 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15628 15629 // Two parameter function must have a pointer to const as a 15630 // first parameter; let's strip those qualifiers. 15631 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15632 15633 if (!PT) { 15634 Diag((*Param)->getSourceRange().getBegin(), 15635 diag::err_literal_operator_param) 15636 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15637 return true; 15638 } 15639 15640 QualType PointeeType = PT->getPointeeType(); 15641 // First parameter must be const 15642 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15643 Diag((*Param)->getSourceRange().getBegin(), 15644 diag::err_literal_operator_param) 15645 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15646 return true; 15647 } 15648 15649 QualType InnerType = PointeeType.getUnqualifiedType(); 15650 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15651 // const char32_t* are allowed as the first parameter to a two-parameter 15652 // function 15653 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15654 Context.hasSameType(InnerType, Context.WideCharTy) || 15655 Context.hasSameType(InnerType, Context.Char8Ty) || 15656 Context.hasSameType(InnerType, Context.Char16Ty) || 15657 Context.hasSameType(InnerType, Context.Char32Ty))) { 15658 Diag((*Param)->getSourceRange().getBegin(), 15659 diag::err_literal_operator_param) 15660 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15661 return true; 15662 } 15663 15664 // Move on to the second and final parameter. 15665 ++Param; 15666 15667 // The second parameter must be a std::size_t. 15668 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15669 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15670 Diag((*Param)->getSourceRange().getBegin(), 15671 diag::err_literal_operator_param) 15672 << SecondParamType << Context.getSizeType() 15673 << (*Param)->getSourceRange(); 15674 return true; 15675 } 15676 } else { 15677 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15678 return true; 15679 } 15680 15681 // Parameters are good. 15682 15683 // A parameter-declaration-clause containing a default argument is not 15684 // equivalent to any of the permitted forms. 15685 for (auto Param : FnDecl->parameters()) { 15686 if (Param->hasDefaultArg()) { 15687 Diag(Param->getDefaultArgRange().getBegin(), 15688 diag::err_literal_operator_default_argument) 15689 << Param->getDefaultArgRange(); 15690 break; 15691 } 15692 } 15693 15694 StringRef LiteralName 15695 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15696 if (LiteralName[0] != '_' && 15697 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15698 // C++11 [usrlit.suffix]p1: 15699 // Literal suffix identifiers that do not start with an underscore 15700 // are reserved for future standardization. 15701 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15702 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15703 } 15704 15705 return false; 15706 } 15707 15708 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15709 /// linkage specification, including the language and (if present) 15710 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15711 /// language string literal. LBraceLoc, if valid, provides the location of 15712 /// the '{' brace. Otherwise, this linkage specification does not 15713 /// have any braces. 15714 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15715 Expr *LangStr, 15716 SourceLocation LBraceLoc) { 15717 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15718 if (!Lit->isAscii()) { 15719 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15720 << LangStr->getSourceRange(); 15721 return nullptr; 15722 } 15723 15724 StringRef Lang = Lit->getString(); 15725 LinkageSpecDecl::LanguageIDs Language; 15726 if (Lang == "C") 15727 Language = LinkageSpecDecl::lang_c; 15728 else if (Lang == "C++") 15729 Language = LinkageSpecDecl::lang_cxx; 15730 else { 15731 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15732 << LangStr->getSourceRange(); 15733 return nullptr; 15734 } 15735 15736 // FIXME: Add all the various semantics of linkage specifications 15737 15738 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15739 LangStr->getExprLoc(), Language, 15740 LBraceLoc.isValid()); 15741 CurContext->addDecl(D); 15742 PushDeclContext(S, D); 15743 return D; 15744 } 15745 15746 /// ActOnFinishLinkageSpecification - Complete the definition of 15747 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15748 /// valid, it's the position of the closing '}' brace in a linkage 15749 /// specification that uses braces. 15750 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15751 Decl *LinkageSpec, 15752 SourceLocation RBraceLoc) { 15753 if (RBraceLoc.isValid()) { 15754 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15755 LSDecl->setRBraceLoc(RBraceLoc); 15756 } 15757 PopDeclContext(); 15758 return LinkageSpec; 15759 } 15760 15761 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15762 const ParsedAttributesView &AttrList, 15763 SourceLocation SemiLoc) { 15764 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15765 // Attribute declarations appertain to empty declaration so we handle 15766 // them here. 15767 ProcessDeclAttributeList(S, ED, AttrList); 15768 15769 CurContext->addDecl(ED); 15770 return ED; 15771 } 15772 15773 /// Perform semantic analysis for the variable declaration that 15774 /// occurs within a C++ catch clause, returning the newly-created 15775 /// variable. 15776 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15777 TypeSourceInfo *TInfo, 15778 SourceLocation StartLoc, 15779 SourceLocation Loc, 15780 IdentifierInfo *Name) { 15781 bool Invalid = false; 15782 QualType ExDeclType = TInfo->getType(); 15783 15784 // Arrays and functions decay. 15785 if (ExDeclType->isArrayType()) 15786 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15787 else if (ExDeclType->isFunctionType()) 15788 ExDeclType = Context.getPointerType(ExDeclType); 15789 15790 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15791 // The exception-declaration shall not denote a pointer or reference to an 15792 // incomplete type, other than [cv] void*. 15793 // N2844 forbids rvalue references. 15794 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15795 Diag(Loc, diag::err_catch_rvalue_ref); 15796 Invalid = true; 15797 } 15798 15799 if (ExDeclType->isVariablyModifiedType()) { 15800 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15801 Invalid = true; 15802 } 15803 15804 QualType BaseType = ExDeclType; 15805 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15806 unsigned DK = diag::err_catch_incomplete; 15807 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15808 BaseType = Ptr->getPointeeType(); 15809 Mode = 1; 15810 DK = diag::err_catch_incomplete_ptr; 15811 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15812 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15813 BaseType = Ref->getPointeeType(); 15814 Mode = 2; 15815 DK = diag::err_catch_incomplete_ref; 15816 } 15817 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15818 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15819 Invalid = true; 15820 15821 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15822 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15823 Invalid = true; 15824 } 15825 15826 if (!Invalid && !ExDeclType->isDependentType() && 15827 RequireNonAbstractType(Loc, ExDeclType, 15828 diag::err_abstract_type_in_decl, 15829 AbstractVariableType)) 15830 Invalid = true; 15831 15832 // Only the non-fragile NeXT runtime currently supports C++ catches 15833 // of ObjC types, and no runtime supports catching ObjC types by value. 15834 if (!Invalid && getLangOpts().ObjC) { 15835 QualType T = ExDeclType; 15836 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15837 T = RT->getPointeeType(); 15838 15839 if (T->isObjCObjectType()) { 15840 Diag(Loc, diag::err_objc_object_catch); 15841 Invalid = true; 15842 } else if (T->isObjCObjectPointerType()) { 15843 // FIXME: should this be a test for macosx-fragile specifically? 15844 if (getLangOpts().ObjCRuntime.isFragile()) 15845 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15846 } 15847 } 15848 15849 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15850 ExDeclType, TInfo, SC_None); 15851 ExDecl->setExceptionVariable(true); 15852 15853 // In ARC, infer 'retaining' for variables of retainable type. 15854 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15855 Invalid = true; 15856 15857 if (!Invalid && !ExDeclType->isDependentType()) { 15858 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15859 // Insulate this from anything else we might currently be parsing. 15860 EnterExpressionEvaluationContext scope( 15861 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15862 15863 // C++ [except.handle]p16: 15864 // The object declared in an exception-declaration or, if the 15865 // exception-declaration does not specify a name, a temporary (12.2) is 15866 // copy-initialized (8.5) from the exception object. [...] 15867 // The object is destroyed when the handler exits, after the destruction 15868 // of any automatic objects initialized within the handler. 15869 // 15870 // We just pretend to initialize the object with itself, then make sure 15871 // it can be destroyed later. 15872 QualType initType = Context.getExceptionObjectType(ExDeclType); 15873 15874 InitializedEntity entity = 15875 InitializedEntity::InitializeVariable(ExDecl); 15876 InitializationKind initKind = 15877 InitializationKind::CreateCopy(Loc, SourceLocation()); 15878 15879 Expr *opaqueValue = 15880 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15881 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15882 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15883 if (result.isInvalid()) 15884 Invalid = true; 15885 else { 15886 // If the constructor used was non-trivial, set this as the 15887 // "initializer". 15888 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15889 if (!construct->getConstructor()->isTrivial()) { 15890 Expr *init = MaybeCreateExprWithCleanups(construct); 15891 ExDecl->setInit(init); 15892 } 15893 15894 // And make sure it's destructable. 15895 FinalizeVarWithDestructor(ExDecl, recordType); 15896 } 15897 } 15898 } 15899 15900 if (Invalid) 15901 ExDecl->setInvalidDecl(); 15902 15903 return ExDecl; 15904 } 15905 15906 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15907 /// handler. 15908 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15909 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15910 bool Invalid = D.isInvalidType(); 15911 15912 // Check for unexpanded parameter packs. 15913 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15914 UPPC_ExceptionType)) { 15915 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15916 D.getIdentifierLoc()); 15917 Invalid = true; 15918 } 15919 15920 IdentifierInfo *II = D.getIdentifier(); 15921 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15922 LookupOrdinaryName, 15923 ForVisibleRedeclaration)) { 15924 // The scope should be freshly made just for us. There is just no way 15925 // it contains any previous declaration, except for function parameters in 15926 // a function-try-block's catch statement. 15927 assert(!S->isDeclScope(PrevDecl)); 15928 if (isDeclInScope(PrevDecl, CurContext, S)) { 15929 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15930 << D.getIdentifier(); 15931 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15932 Invalid = true; 15933 } else if (PrevDecl->isTemplateParameter()) 15934 // Maybe we will complain about the shadowed template parameter. 15935 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15936 } 15937 15938 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15939 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15940 << D.getCXXScopeSpec().getRange(); 15941 Invalid = true; 15942 } 15943 15944 VarDecl *ExDecl = BuildExceptionDeclaration( 15945 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15946 if (Invalid) 15947 ExDecl->setInvalidDecl(); 15948 15949 // Add the exception declaration into this scope. 15950 if (II) 15951 PushOnScopeChains(ExDecl, S); 15952 else 15953 CurContext->addDecl(ExDecl); 15954 15955 ProcessDeclAttributes(S, ExDecl, D); 15956 return ExDecl; 15957 } 15958 15959 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15960 Expr *AssertExpr, 15961 Expr *AssertMessageExpr, 15962 SourceLocation RParenLoc) { 15963 StringLiteral *AssertMessage = 15964 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15965 15966 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15967 return nullptr; 15968 15969 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15970 AssertMessage, RParenLoc, false); 15971 } 15972 15973 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15974 Expr *AssertExpr, 15975 StringLiteral *AssertMessage, 15976 SourceLocation RParenLoc, 15977 bool Failed) { 15978 assert(AssertExpr != nullptr && "Expected non-null condition"); 15979 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15980 !Failed) { 15981 // In a static_assert-declaration, the constant-expression shall be a 15982 // constant expression that can be contextually converted to bool. 15983 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15984 if (Converted.isInvalid()) 15985 Failed = true; 15986 15987 ExprResult FullAssertExpr = 15988 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15989 /*DiscardedValue*/ false, 15990 /*IsConstexpr*/ true); 15991 if (FullAssertExpr.isInvalid()) 15992 Failed = true; 15993 else 15994 AssertExpr = FullAssertExpr.get(); 15995 15996 llvm::APSInt Cond; 15997 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 15998 diag::err_static_assert_expression_is_not_constant, 15999 /*AllowFold=*/false).isInvalid()) 16000 Failed = true; 16001 16002 if (!Failed && !Cond) { 16003 SmallString<256> MsgBuffer; 16004 llvm::raw_svector_ostream Msg(MsgBuffer); 16005 if (AssertMessage) 16006 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16007 16008 Expr *InnerCond = nullptr; 16009 std::string InnerCondDescription; 16010 std::tie(InnerCond, InnerCondDescription) = 16011 findFailedBooleanCondition(Converted.get()); 16012 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16013 // Drill down into concept specialization expressions to see why they 16014 // weren't satisfied. 16015 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16016 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16017 ConstraintSatisfaction Satisfaction; 16018 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16019 DiagnoseUnsatisfiedConstraint(Satisfaction); 16020 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16021 && !isa<IntegerLiteral>(InnerCond)) { 16022 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16023 << InnerCondDescription << !AssertMessage 16024 << Msg.str() << InnerCond->getSourceRange(); 16025 } else { 16026 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16027 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16028 } 16029 Failed = true; 16030 } 16031 } else { 16032 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16033 /*DiscardedValue*/false, 16034 /*IsConstexpr*/true); 16035 if (FullAssertExpr.isInvalid()) 16036 Failed = true; 16037 else 16038 AssertExpr = FullAssertExpr.get(); 16039 } 16040 16041 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16042 AssertExpr, AssertMessage, RParenLoc, 16043 Failed); 16044 16045 CurContext->addDecl(Decl); 16046 return Decl; 16047 } 16048 16049 /// Perform semantic analysis of the given friend type declaration. 16050 /// 16051 /// \returns A friend declaration that. 16052 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16053 SourceLocation FriendLoc, 16054 TypeSourceInfo *TSInfo) { 16055 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16056 16057 QualType T = TSInfo->getType(); 16058 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16059 16060 // C++03 [class.friend]p2: 16061 // An elaborated-type-specifier shall be used in a friend declaration 16062 // for a class.* 16063 // 16064 // * The class-key of the elaborated-type-specifier is required. 16065 if (!CodeSynthesisContexts.empty()) { 16066 // Do not complain about the form of friend template types during any kind 16067 // of code synthesis. For template instantiation, we will have complained 16068 // when the template was defined. 16069 } else { 16070 if (!T->isElaboratedTypeSpecifier()) { 16071 // If we evaluated the type to a record type, suggest putting 16072 // a tag in front. 16073 if (const RecordType *RT = T->getAs<RecordType>()) { 16074 RecordDecl *RD = RT->getDecl(); 16075 16076 SmallString<16> InsertionText(" "); 16077 InsertionText += RD->getKindName(); 16078 16079 Diag(TypeRange.getBegin(), 16080 getLangOpts().CPlusPlus11 ? 16081 diag::warn_cxx98_compat_unelaborated_friend_type : 16082 diag::ext_unelaborated_friend_type) 16083 << (unsigned) RD->getTagKind() 16084 << T 16085 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16086 InsertionText); 16087 } else { 16088 Diag(FriendLoc, 16089 getLangOpts().CPlusPlus11 ? 16090 diag::warn_cxx98_compat_nonclass_type_friend : 16091 diag::ext_nonclass_type_friend) 16092 << T 16093 << TypeRange; 16094 } 16095 } else if (T->getAs<EnumType>()) { 16096 Diag(FriendLoc, 16097 getLangOpts().CPlusPlus11 ? 16098 diag::warn_cxx98_compat_enum_friend : 16099 diag::ext_enum_friend) 16100 << T 16101 << TypeRange; 16102 } 16103 16104 // C++11 [class.friend]p3: 16105 // A friend declaration that does not declare a function shall have one 16106 // of the following forms: 16107 // friend elaborated-type-specifier ; 16108 // friend simple-type-specifier ; 16109 // friend typename-specifier ; 16110 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16111 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16112 } 16113 16114 // If the type specifier in a friend declaration designates a (possibly 16115 // cv-qualified) class type, that class is declared as a friend; otherwise, 16116 // the friend declaration is ignored. 16117 return FriendDecl::Create(Context, CurContext, 16118 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16119 FriendLoc); 16120 } 16121 16122 /// Handle a friend tag declaration where the scope specifier was 16123 /// templated. 16124 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16125 unsigned TagSpec, SourceLocation TagLoc, 16126 CXXScopeSpec &SS, IdentifierInfo *Name, 16127 SourceLocation NameLoc, 16128 const ParsedAttributesView &Attr, 16129 MultiTemplateParamsArg TempParamLists) { 16130 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16131 16132 bool IsMemberSpecialization = false; 16133 bool Invalid = false; 16134 16135 if (TemplateParameterList *TemplateParams = 16136 MatchTemplateParametersToScopeSpecifier( 16137 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16138 IsMemberSpecialization, Invalid)) { 16139 if (TemplateParams->size() > 0) { 16140 // This is a declaration of a class template. 16141 if (Invalid) 16142 return nullptr; 16143 16144 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16145 NameLoc, Attr, TemplateParams, AS_public, 16146 /*ModulePrivateLoc=*/SourceLocation(), 16147 FriendLoc, TempParamLists.size() - 1, 16148 TempParamLists.data()).get(); 16149 } else { 16150 // The "template<>" header is extraneous. 16151 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16152 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16153 IsMemberSpecialization = true; 16154 } 16155 } 16156 16157 if (Invalid) return nullptr; 16158 16159 bool isAllExplicitSpecializations = true; 16160 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16161 if (TempParamLists[I]->size()) { 16162 isAllExplicitSpecializations = false; 16163 break; 16164 } 16165 } 16166 16167 // FIXME: don't ignore attributes. 16168 16169 // If it's explicit specializations all the way down, just forget 16170 // about the template header and build an appropriate non-templated 16171 // friend. TODO: for source fidelity, remember the headers. 16172 if (isAllExplicitSpecializations) { 16173 if (SS.isEmpty()) { 16174 bool Owned = false; 16175 bool IsDependent = false; 16176 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16177 Attr, AS_public, 16178 /*ModulePrivateLoc=*/SourceLocation(), 16179 MultiTemplateParamsArg(), Owned, IsDependent, 16180 /*ScopedEnumKWLoc=*/SourceLocation(), 16181 /*ScopedEnumUsesClassTag=*/false, 16182 /*UnderlyingType=*/TypeResult(), 16183 /*IsTypeSpecifier=*/false, 16184 /*IsTemplateParamOrArg=*/false); 16185 } 16186 16187 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16188 ElaboratedTypeKeyword Keyword 16189 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16190 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16191 *Name, NameLoc); 16192 if (T.isNull()) 16193 return nullptr; 16194 16195 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16196 if (isa<DependentNameType>(T)) { 16197 DependentNameTypeLoc TL = 16198 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16199 TL.setElaboratedKeywordLoc(TagLoc); 16200 TL.setQualifierLoc(QualifierLoc); 16201 TL.setNameLoc(NameLoc); 16202 } else { 16203 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16204 TL.setElaboratedKeywordLoc(TagLoc); 16205 TL.setQualifierLoc(QualifierLoc); 16206 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16207 } 16208 16209 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16210 TSI, FriendLoc, TempParamLists); 16211 Friend->setAccess(AS_public); 16212 CurContext->addDecl(Friend); 16213 return Friend; 16214 } 16215 16216 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16217 16218 16219 16220 // Handle the case of a templated-scope friend class. e.g. 16221 // template <class T> class A<T>::B; 16222 // FIXME: we don't support these right now. 16223 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16224 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16225 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16226 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16227 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16228 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16229 TL.setElaboratedKeywordLoc(TagLoc); 16230 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16231 TL.setNameLoc(NameLoc); 16232 16233 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16234 TSI, FriendLoc, TempParamLists); 16235 Friend->setAccess(AS_public); 16236 Friend->setUnsupportedFriend(true); 16237 CurContext->addDecl(Friend); 16238 return Friend; 16239 } 16240 16241 /// Handle a friend type declaration. This works in tandem with 16242 /// ActOnTag. 16243 /// 16244 /// Notes on friend class templates: 16245 /// 16246 /// We generally treat friend class declarations as if they were 16247 /// declaring a class. So, for example, the elaborated type specifier 16248 /// in a friend declaration is required to obey the restrictions of a 16249 /// class-head (i.e. no typedefs in the scope chain), template 16250 /// parameters are required to match up with simple template-ids, &c. 16251 /// However, unlike when declaring a template specialization, it's 16252 /// okay to refer to a template specialization without an empty 16253 /// template parameter declaration, e.g. 16254 /// friend class A<T>::B<unsigned>; 16255 /// We permit this as a special case; if there are any template 16256 /// parameters present at all, require proper matching, i.e. 16257 /// template <> template \<class T> friend class A<int>::B; 16258 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16259 MultiTemplateParamsArg TempParams) { 16260 SourceLocation Loc = DS.getBeginLoc(); 16261 16262 assert(DS.isFriendSpecified()); 16263 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16264 16265 // C++ [class.friend]p3: 16266 // A friend declaration that does not declare a function shall have one of 16267 // the following forms: 16268 // friend elaborated-type-specifier ; 16269 // friend simple-type-specifier ; 16270 // friend typename-specifier ; 16271 // 16272 // Any declaration with a type qualifier does not have that form. (It's 16273 // legal to specify a qualified type as a friend, you just can't write the 16274 // keywords.) 16275 if (DS.getTypeQualifiers()) { 16276 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16277 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16278 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16279 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16280 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16281 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16282 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16283 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16284 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16285 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16286 } 16287 16288 // Try to convert the decl specifier to a type. This works for 16289 // friend templates because ActOnTag never produces a ClassTemplateDecl 16290 // for a TUK_Friend. 16291 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 16292 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16293 QualType T = TSI->getType(); 16294 if (TheDeclarator.isInvalidType()) 16295 return nullptr; 16296 16297 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16298 return nullptr; 16299 16300 // This is definitely an error in C++98. It's probably meant to 16301 // be forbidden in C++0x, too, but the specification is just 16302 // poorly written. 16303 // 16304 // The problem is with declarations like the following: 16305 // template <T> friend A<T>::foo; 16306 // where deciding whether a class C is a friend or not now hinges 16307 // on whether there exists an instantiation of A that causes 16308 // 'foo' to equal C. There are restrictions on class-heads 16309 // (which we declare (by fiat) elaborated friend declarations to 16310 // be) that makes this tractable. 16311 // 16312 // FIXME: handle "template <> friend class A<T>;", which 16313 // is possibly well-formed? Who even knows? 16314 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16315 Diag(Loc, diag::err_tagless_friend_type_template) 16316 << DS.getSourceRange(); 16317 return nullptr; 16318 } 16319 16320 // C++98 [class.friend]p1: A friend of a class is a function 16321 // or class that is not a member of the class . . . 16322 // This is fixed in DR77, which just barely didn't make the C++03 16323 // deadline. It's also a very silly restriction that seriously 16324 // affects inner classes and which nobody else seems to implement; 16325 // thus we never diagnose it, not even in -pedantic. 16326 // 16327 // But note that we could warn about it: it's always useless to 16328 // friend one of your own members (it's not, however, worthless to 16329 // friend a member of an arbitrary specialization of your template). 16330 16331 Decl *D; 16332 if (!TempParams.empty()) 16333 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16334 TempParams, 16335 TSI, 16336 DS.getFriendSpecLoc()); 16337 else 16338 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16339 16340 if (!D) 16341 return nullptr; 16342 16343 D->setAccess(AS_public); 16344 CurContext->addDecl(D); 16345 16346 return D; 16347 } 16348 16349 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16350 MultiTemplateParamsArg TemplateParams) { 16351 const DeclSpec &DS = D.getDeclSpec(); 16352 16353 assert(DS.isFriendSpecified()); 16354 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16355 16356 SourceLocation Loc = D.getIdentifierLoc(); 16357 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16358 16359 // C++ [class.friend]p1 16360 // A friend of a class is a function or class.... 16361 // Note that this sees through typedefs, which is intended. 16362 // It *doesn't* see through dependent types, which is correct 16363 // according to [temp.arg.type]p3: 16364 // If a declaration acquires a function type through a 16365 // type dependent on a template-parameter and this causes 16366 // a declaration that does not use the syntactic form of a 16367 // function declarator to have a function type, the program 16368 // is ill-formed. 16369 if (!TInfo->getType()->isFunctionType()) { 16370 Diag(Loc, diag::err_unexpected_friend); 16371 16372 // It might be worthwhile to try to recover by creating an 16373 // appropriate declaration. 16374 return nullptr; 16375 } 16376 16377 // C++ [namespace.memdef]p3 16378 // - If a friend declaration in a non-local class first declares a 16379 // class or function, the friend class or function is a member 16380 // of the innermost enclosing namespace. 16381 // - The name of the friend is not found by simple name lookup 16382 // until a matching declaration is provided in that namespace 16383 // scope (either before or after the class declaration granting 16384 // friendship). 16385 // - If a friend function is called, its name may be found by the 16386 // name lookup that considers functions from namespaces and 16387 // classes associated with the types of the function arguments. 16388 // - When looking for a prior declaration of a class or a function 16389 // declared as a friend, scopes outside the innermost enclosing 16390 // namespace scope are not considered. 16391 16392 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16393 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16394 assert(NameInfo.getName()); 16395 16396 // Check for unexpanded parameter packs. 16397 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16398 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16399 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16400 return nullptr; 16401 16402 // The context we found the declaration in, or in which we should 16403 // create the declaration. 16404 DeclContext *DC; 16405 Scope *DCScope = S; 16406 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16407 ForExternalRedeclaration); 16408 16409 // There are five cases here. 16410 // - There's no scope specifier and we're in a local class. Only look 16411 // for functions declared in the immediately-enclosing block scope. 16412 // We recover from invalid scope qualifiers as if they just weren't there. 16413 FunctionDecl *FunctionContainingLocalClass = nullptr; 16414 if ((SS.isInvalid() || !SS.isSet()) && 16415 (FunctionContainingLocalClass = 16416 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16417 // C++11 [class.friend]p11: 16418 // If a friend declaration appears in a local class and the name 16419 // specified is an unqualified name, a prior declaration is 16420 // looked up without considering scopes that are outside the 16421 // innermost enclosing non-class scope. For a friend function 16422 // declaration, if there is no prior declaration, the program is 16423 // ill-formed. 16424 16425 // Find the innermost enclosing non-class scope. This is the block 16426 // scope containing the local class definition (or for a nested class, 16427 // the outer local class). 16428 DCScope = S->getFnParent(); 16429 16430 // Look up the function name in the scope. 16431 Previous.clear(LookupLocalFriendName); 16432 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16433 16434 if (!Previous.empty()) { 16435 // All possible previous declarations must have the same context: 16436 // either they were declared at block scope or they are members of 16437 // one of the enclosing local classes. 16438 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16439 } else { 16440 // This is ill-formed, but provide the context that we would have 16441 // declared the function in, if we were permitted to, for error recovery. 16442 DC = FunctionContainingLocalClass; 16443 } 16444 adjustContextForLocalExternDecl(DC); 16445 16446 // C++ [class.friend]p6: 16447 // A function can be defined in a friend declaration of a class if and 16448 // only if the class is a non-local class (9.8), the function name is 16449 // unqualified, and the function has namespace scope. 16450 if (D.isFunctionDefinition()) { 16451 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16452 } 16453 16454 // - There's no scope specifier, in which case we just go to the 16455 // appropriate scope and look for a function or function template 16456 // there as appropriate. 16457 } else if (SS.isInvalid() || !SS.isSet()) { 16458 // C++11 [namespace.memdef]p3: 16459 // If the name in a friend declaration is neither qualified nor 16460 // a template-id and the declaration is a function or an 16461 // elaborated-type-specifier, the lookup to determine whether 16462 // the entity has been previously declared shall not consider 16463 // any scopes outside the innermost enclosing namespace. 16464 bool isTemplateId = 16465 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16466 16467 // Find the appropriate context according to the above. 16468 DC = CurContext; 16469 16470 // Skip class contexts. If someone can cite chapter and verse 16471 // for this behavior, that would be nice --- it's what GCC and 16472 // EDG do, and it seems like a reasonable intent, but the spec 16473 // really only says that checks for unqualified existing 16474 // declarations should stop at the nearest enclosing namespace, 16475 // not that they should only consider the nearest enclosing 16476 // namespace. 16477 while (DC->isRecord()) 16478 DC = DC->getParent(); 16479 16480 DeclContext *LookupDC = DC; 16481 while (LookupDC->isTransparentContext()) 16482 LookupDC = LookupDC->getParent(); 16483 16484 while (true) { 16485 LookupQualifiedName(Previous, LookupDC); 16486 16487 if (!Previous.empty()) { 16488 DC = LookupDC; 16489 break; 16490 } 16491 16492 if (isTemplateId) { 16493 if (isa<TranslationUnitDecl>(LookupDC)) break; 16494 } else { 16495 if (LookupDC->isFileContext()) break; 16496 } 16497 LookupDC = LookupDC->getParent(); 16498 } 16499 16500 DCScope = getScopeForDeclContext(S, DC); 16501 16502 // - There's a non-dependent scope specifier, in which case we 16503 // compute it and do a previous lookup there for a function 16504 // or function template. 16505 } else if (!SS.getScopeRep()->isDependent()) { 16506 DC = computeDeclContext(SS); 16507 if (!DC) return nullptr; 16508 16509 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16510 16511 LookupQualifiedName(Previous, DC); 16512 16513 // C++ [class.friend]p1: A friend of a class is a function or 16514 // class that is not a member of the class . . . 16515 if (DC->Equals(CurContext)) 16516 Diag(DS.getFriendSpecLoc(), 16517 getLangOpts().CPlusPlus11 ? 16518 diag::warn_cxx98_compat_friend_is_member : 16519 diag::err_friend_is_member); 16520 16521 if (D.isFunctionDefinition()) { 16522 // C++ [class.friend]p6: 16523 // A function can be defined in a friend declaration of a class if and 16524 // only if the class is a non-local class (9.8), the function name is 16525 // unqualified, and the function has namespace scope. 16526 // 16527 // FIXME: We should only do this if the scope specifier names the 16528 // innermost enclosing namespace; otherwise the fixit changes the 16529 // meaning of the code. 16530 SemaDiagnosticBuilder DB 16531 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16532 16533 DB << SS.getScopeRep(); 16534 if (DC->isFileContext()) 16535 DB << FixItHint::CreateRemoval(SS.getRange()); 16536 SS.clear(); 16537 } 16538 16539 // - There's a scope specifier that does not match any template 16540 // parameter lists, in which case we use some arbitrary context, 16541 // create a method or method template, and wait for instantiation. 16542 // - There's a scope specifier that does match some template 16543 // parameter lists, which we don't handle right now. 16544 } else { 16545 if (D.isFunctionDefinition()) { 16546 // C++ [class.friend]p6: 16547 // A function can be defined in a friend declaration of a class if and 16548 // only if the class is a non-local class (9.8), the function name is 16549 // unqualified, and the function has namespace scope. 16550 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16551 << SS.getScopeRep(); 16552 } 16553 16554 DC = CurContext; 16555 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16556 } 16557 16558 if (!DC->isRecord()) { 16559 int DiagArg = -1; 16560 switch (D.getName().getKind()) { 16561 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16562 case UnqualifiedIdKind::IK_ConstructorName: 16563 DiagArg = 0; 16564 break; 16565 case UnqualifiedIdKind::IK_DestructorName: 16566 DiagArg = 1; 16567 break; 16568 case UnqualifiedIdKind::IK_ConversionFunctionId: 16569 DiagArg = 2; 16570 break; 16571 case UnqualifiedIdKind::IK_DeductionGuideName: 16572 DiagArg = 3; 16573 break; 16574 case UnqualifiedIdKind::IK_Identifier: 16575 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16576 case UnqualifiedIdKind::IK_LiteralOperatorId: 16577 case UnqualifiedIdKind::IK_OperatorFunctionId: 16578 case UnqualifiedIdKind::IK_TemplateId: 16579 break; 16580 } 16581 // This implies that it has to be an operator or function. 16582 if (DiagArg >= 0) { 16583 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16584 return nullptr; 16585 } 16586 } 16587 16588 // FIXME: This is an egregious hack to cope with cases where the scope stack 16589 // does not contain the declaration context, i.e., in an out-of-line 16590 // definition of a class. 16591 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16592 if (!DCScope) { 16593 FakeDCScope.setEntity(DC); 16594 DCScope = &FakeDCScope; 16595 } 16596 16597 bool AddToScope = true; 16598 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16599 TemplateParams, AddToScope); 16600 if (!ND) return nullptr; 16601 16602 assert(ND->getLexicalDeclContext() == CurContext); 16603 16604 // If we performed typo correction, we might have added a scope specifier 16605 // and changed the decl context. 16606 DC = ND->getDeclContext(); 16607 16608 // Add the function declaration to the appropriate lookup tables, 16609 // adjusting the redeclarations list as necessary. We don't 16610 // want to do this yet if the friending class is dependent. 16611 // 16612 // Also update the scope-based lookup if the target context's 16613 // lookup context is in lexical scope. 16614 if (!CurContext->isDependentContext()) { 16615 DC = DC->getRedeclContext(); 16616 DC->makeDeclVisibleInContext(ND); 16617 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16618 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16619 } 16620 16621 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16622 D.getIdentifierLoc(), ND, 16623 DS.getFriendSpecLoc()); 16624 FrD->setAccess(AS_public); 16625 CurContext->addDecl(FrD); 16626 16627 if (ND->isInvalidDecl()) { 16628 FrD->setInvalidDecl(); 16629 } else { 16630 if (DC->isRecord()) CheckFriendAccess(ND); 16631 16632 FunctionDecl *FD; 16633 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16634 FD = FTD->getTemplatedDecl(); 16635 else 16636 FD = cast<FunctionDecl>(ND); 16637 16638 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16639 // default argument expression, that declaration shall be a definition 16640 // and shall be the only declaration of the function or function 16641 // template in the translation unit. 16642 if (functionDeclHasDefaultArgument(FD)) { 16643 // We can't look at FD->getPreviousDecl() because it may not have been set 16644 // if we're in a dependent context. If the function is known to be a 16645 // redeclaration, we will have narrowed Previous down to the right decl. 16646 if (D.isRedeclaration()) { 16647 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16648 Diag(Previous.getRepresentativeDecl()->getLocation(), 16649 diag::note_previous_declaration); 16650 } else if (!D.isFunctionDefinition()) 16651 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16652 } 16653 16654 // Mark templated-scope function declarations as unsupported. 16655 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16656 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16657 << SS.getScopeRep() << SS.getRange() 16658 << cast<CXXRecordDecl>(CurContext); 16659 FrD->setUnsupportedFriend(true); 16660 } 16661 } 16662 16663 return ND; 16664 } 16665 16666 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16667 AdjustDeclIfTemplate(Dcl); 16668 16669 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16670 if (!Fn) { 16671 Diag(DelLoc, diag::err_deleted_non_function); 16672 return; 16673 } 16674 16675 // Deleted function does not have a body. 16676 Fn->setWillHaveBody(false); 16677 16678 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16679 // Don't consider the implicit declaration we generate for explicit 16680 // specializations. FIXME: Do not generate these implicit declarations. 16681 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16682 Prev->getPreviousDecl()) && 16683 !Prev->isDefined()) { 16684 Diag(DelLoc, diag::err_deleted_decl_not_first); 16685 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16686 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16687 : diag::note_previous_declaration); 16688 // We can't recover from this; the declaration might have already 16689 // been used. 16690 Fn->setInvalidDecl(); 16691 return; 16692 } 16693 16694 // To maintain the invariant that functions are only deleted on their first 16695 // declaration, mark the implicitly-instantiated declaration of the 16696 // explicitly-specialized function as deleted instead of marking the 16697 // instantiated redeclaration. 16698 Fn = Fn->getCanonicalDecl(); 16699 } 16700 16701 // dllimport/dllexport cannot be deleted. 16702 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16703 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16704 Fn->setInvalidDecl(); 16705 } 16706 16707 // C++11 [basic.start.main]p3: 16708 // A program that defines main as deleted [...] is ill-formed. 16709 if (Fn->isMain()) 16710 Diag(DelLoc, diag::err_deleted_main); 16711 16712 // C++11 [dcl.fct.def.delete]p4: 16713 // A deleted function is implicitly inline. 16714 Fn->setImplicitlyInline(); 16715 Fn->setDeletedAsWritten(); 16716 } 16717 16718 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16719 if (!Dcl || Dcl->isInvalidDecl()) 16720 return; 16721 16722 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16723 if (!FD) { 16724 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16725 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16726 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16727 return; 16728 } 16729 } 16730 16731 Diag(DefaultLoc, diag::err_default_special_members) 16732 << getLangOpts().CPlusPlus20; 16733 return; 16734 } 16735 16736 // Reject if this can't possibly be a defaultable function. 16737 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16738 if (!DefKind && 16739 // A dependent function that doesn't locally look defaultable can 16740 // still instantiate to a defaultable function if it's a constructor 16741 // or assignment operator. 16742 (!FD->isDependentContext() || 16743 (!isa<CXXConstructorDecl>(FD) && 16744 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16745 Diag(DefaultLoc, diag::err_default_special_members) 16746 << getLangOpts().CPlusPlus20; 16747 return; 16748 } 16749 16750 if (DefKind.isComparison() && 16751 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16752 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16753 << (int)DefKind.asComparison(); 16754 return; 16755 } 16756 16757 // Issue compatibility warning. We already warned if the operator is 16758 // 'operator<=>' when parsing the '<=>' token. 16759 if (DefKind.isComparison() && 16760 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16761 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16762 ? diag::warn_cxx17_compat_defaulted_comparison 16763 : diag::ext_defaulted_comparison); 16764 } 16765 16766 FD->setDefaulted(); 16767 FD->setExplicitlyDefaulted(); 16768 16769 // Defer checking functions that are defaulted in a dependent context. 16770 if (FD->isDependentContext()) 16771 return; 16772 16773 // Unset that we will have a body for this function. We might not, 16774 // if it turns out to be trivial, and we don't need this marking now 16775 // that we've marked it as defaulted. 16776 FD->setWillHaveBody(false); 16777 16778 // If this definition appears within the record, do the checking when 16779 // the record is complete. This is always the case for a defaulted 16780 // comparison. 16781 if (DefKind.isComparison()) 16782 return; 16783 auto *MD = cast<CXXMethodDecl>(FD); 16784 16785 const FunctionDecl *Primary = FD; 16786 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16787 // Ask the template instantiation pattern that actually had the 16788 // '= default' on it. 16789 Primary = Pattern; 16790 16791 // If the method was defaulted on its first declaration, we will have 16792 // already performed the checking in CheckCompletedCXXClass. Such a 16793 // declaration doesn't trigger an implicit definition. 16794 if (Primary->getCanonicalDecl()->isDefaulted()) 16795 return; 16796 16797 // FIXME: Once we support defining comparisons out of class, check for a 16798 // defaulted comparison here. 16799 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16800 MD->setInvalidDecl(); 16801 else 16802 DefineDefaultedFunction(*this, MD, DefaultLoc); 16803 } 16804 16805 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16806 for (Stmt *SubStmt : S->children()) { 16807 if (!SubStmt) 16808 continue; 16809 if (isa<ReturnStmt>(SubStmt)) 16810 Self.Diag(SubStmt->getBeginLoc(), 16811 diag::err_return_in_constructor_handler); 16812 if (!isa<Expr>(SubStmt)) 16813 SearchForReturnInStmt(Self, SubStmt); 16814 } 16815 } 16816 16817 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16818 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16819 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16820 SearchForReturnInStmt(*this, Handler); 16821 } 16822 } 16823 16824 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16825 const CXXMethodDecl *Old) { 16826 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16827 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16828 16829 if (OldFT->hasExtParameterInfos()) { 16830 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16831 // A parameter of the overriding method should be annotated with noescape 16832 // if the corresponding parameter of the overridden method is annotated. 16833 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16834 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16835 Diag(New->getParamDecl(I)->getLocation(), 16836 diag::warn_overriding_method_missing_noescape); 16837 Diag(Old->getParamDecl(I)->getLocation(), 16838 diag::note_overridden_marked_noescape); 16839 } 16840 } 16841 16842 // Virtual overrides must have the same code_seg. 16843 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16844 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16845 if ((NewCSA || OldCSA) && 16846 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16847 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16848 Diag(Old->getLocation(), diag::note_previous_declaration); 16849 return true; 16850 } 16851 16852 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16853 16854 // If the calling conventions match, everything is fine 16855 if (NewCC == OldCC) 16856 return false; 16857 16858 // If the calling conventions mismatch because the new function is static, 16859 // suppress the calling convention mismatch error; the error about static 16860 // function override (err_static_overrides_virtual from 16861 // Sema::CheckFunctionDeclaration) is more clear. 16862 if (New->getStorageClass() == SC_Static) 16863 return false; 16864 16865 Diag(New->getLocation(), 16866 diag::err_conflicting_overriding_cc_attributes) 16867 << New->getDeclName() << New->getType() << Old->getType(); 16868 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16869 return true; 16870 } 16871 16872 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16873 const CXXMethodDecl *Old) { 16874 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16875 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16876 16877 if (Context.hasSameType(NewTy, OldTy) || 16878 NewTy->isDependentType() || OldTy->isDependentType()) 16879 return false; 16880 16881 // Check if the return types are covariant 16882 QualType NewClassTy, OldClassTy; 16883 16884 /// Both types must be pointers or references to classes. 16885 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16886 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16887 NewClassTy = NewPT->getPointeeType(); 16888 OldClassTy = OldPT->getPointeeType(); 16889 } 16890 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16891 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16892 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16893 NewClassTy = NewRT->getPointeeType(); 16894 OldClassTy = OldRT->getPointeeType(); 16895 } 16896 } 16897 } 16898 16899 // The return types aren't either both pointers or references to a class type. 16900 if (NewClassTy.isNull()) { 16901 Diag(New->getLocation(), 16902 diag::err_different_return_type_for_overriding_virtual_function) 16903 << New->getDeclName() << NewTy << OldTy 16904 << New->getReturnTypeSourceRange(); 16905 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16906 << Old->getReturnTypeSourceRange(); 16907 16908 return true; 16909 } 16910 16911 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16912 // C++14 [class.virtual]p8: 16913 // If the class type in the covariant return type of D::f differs from 16914 // that of B::f, the class type in the return type of D::f shall be 16915 // complete at the point of declaration of D::f or shall be the class 16916 // type D. 16917 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16918 if (!RT->isBeingDefined() && 16919 RequireCompleteType(New->getLocation(), NewClassTy, 16920 diag::err_covariant_return_incomplete, 16921 New->getDeclName())) 16922 return true; 16923 } 16924 16925 // Check if the new class derives from the old class. 16926 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16927 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16928 << New->getDeclName() << NewTy << OldTy 16929 << New->getReturnTypeSourceRange(); 16930 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16931 << Old->getReturnTypeSourceRange(); 16932 return true; 16933 } 16934 16935 // Check if we the conversion from derived to base is valid. 16936 if (CheckDerivedToBaseConversion( 16937 NewClassTy, OldClassTy, 16938 diag::err_covariant_return_inaccessible_base, 16939 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16940 New->getLocation(), New->getReturnTypeSourceRange(), 16941 New->getDeclName(), nullptr)) { 16942 // FIXME: this note won't trigger for delayed access control 16943 // diagnostics, and it's impossible to get an undelayed error 16944 // here from access control during the original parse because 16945 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16946 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16947 << Old->getReturnTypeSourceRange(); 16948 return true; 16949 } 16950 } 16951 16952 // The qualifiers of the return types must be the same. 16953 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16954 Diag(New->getLocation(), 16955 diag::err_covariant_return_type_different_qualifications) 16956 << New->getDeclName() << NewTy << OldTy 16957 << New->getReturnTypeSourceRange(); 16958 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16959 << Old->getReturnTypeSourceRange(); 16960 return true; 16961 } 16962 16963 16964 // The new class type must have the same or less qualifiers as the old type. 16965 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16966 Diag(New->getLocation(), 16967 diag::err_covariant_return_type_class_type_more_qualified) 16968 << New->getDeclName() << NewTy << OldTy 16969 << New->getReturnTypeSourceRange(); 16970 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16971 << Old->getReturnTypeSourceRange(); 16972 return true; 16973 } 16974 16975 return false; 16976 } 16977 16978 /// Mark the given method pure. 16979 /// 16980 /// \param Method the method to be marked pure. 16981 /// 16982 /// \param InitRange the source range that covers the "0" initializer. 16983 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16984 SourceLocation EndLoc = InitRange.getEnd(); 16985 if (EndLoc.isValid()) 16986 Method->setRangeEnd(EndLoc); 16987 16988 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16989 Method->setPure(); 16990 return false; 16991 } 16992 16993 if (!Method->isInvalidDecl()) 16994 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16995 << Method->getDeclName() << InitRange; 16996 return true; 16997 } 16998 16999 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17000 if (D->getFriendObjectKind()) 17001 Diag(D->getLocation(), diag::err_pure_friend); 17002 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17003 CheckPureMethod(M, ZeroLoc); 17004 else 17005 Diag(D->getLocation(), diag::err_illegal_initializer); 17006 } 17007 17008 /// Determine whether the given declaration is a global variable or 17009 /// static data member. 17010 static bool isNonlocalVariable(const Decl *D) { 17011 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17012 return Var->hasGlobalStorage(); 17013 17014 return false; 17015 } 17016 17017 /// Invoked when we are about to parse an initializer for the declaration 17018 /// 'Dcl'. 17019 /// 17020 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17021 /// static data member of class X, names should be looked up in the scope of 17022 /// class X. If the declaration had a scope specifier, a scope will have 17023 /// been created and passed in for this purpose. Otherwise, S will be null. 17024 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17025 // If there is no declaration, there was an error parsing it. 17026 if (!D || D->isInvalidDecl()) 17027 return; 17028 17029 // We will always have a nested name specifier here, but this declaration 17030 // might not be out of line if the specifier names the current namespace: 17031 // extern int n; 17032 // int ::n = 0; 17033 if (S && D->isOutOfLine()) 17034 EnterDeclaratorContext(S, D->getDeclContext()); 17035 17036 // If we are parsing the initializer for a static data member, push a 17037 // new expression evaluation context that is associated with this static 17038 // data member. 17039 if (isNonlocalVariable(D)) 17040 PushExpressionEvaluationContext( 17041 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17042 } 17043 17044 /// Invoked after we are finished parsing an initializer for the declaration D. 17045 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17046 // If there is no declaration, there was an error parsing it. 17047 if (!D || D->isInvalidDecl()) 17048 return; 17049 17050 if (isNonlocalVariable(D)) 17051 PopExpressionEvaluationContext(); 17052 17053 if (S && D->isOutOfLine()) 17054 ExitDeclaratorContext(S); 17055 } 17056 17057 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17058 /// C++ if/switch/while/for statement. 17059 /// e.g: "if (int x = f()) {...}" 17060 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17061 // C++ 6.4p2: 17062 // The declarator shall not specify a function or an array. 17063 // The type-specifier-seq shall not contain typedef and shall not declare a 17064 // new class or enumeration. 17065 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17066 "Parser allowed 'typedef' as storage class of condition decl."); 17067 17068 Decl *Dcl = ActOnDeclarator(S, D); 17069 if (!Dcl) 17070 return true; 17071 17072 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17073 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17074 << D.getSourceRange(); 17075 return true; 17076 } 17077 17078 return Dcl; 17079 } 17080 17081 void Sema::LoadExternalVTableUses() { 17082 if (!ExternalSource) 17083 return; 17084 17085 SmallVector<ExternalVTableUse, 4> VTables; 17086 ExternalSource->ReadUsedVTables(VTables); 17087 SmallVector<VTableUse, 4> NewUses; 17088 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17089 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17090 = VTablesUsed.find(VTables[I].Record); 17091 // Even if a definition wasn't required before, it may be required now. 17092 if (Pos != VTablesUsed.end()) { 17093 if (!Pos->second && VTables[I].DefinitionRequired) 17094 Pos->second = true; 17095 continue; 17096 } 17097 17098 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17099 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17100 } 17101 17102 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17103 } 17104 17105 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17106 bool DefinitionRequired) { 17107 // Ignore any vtable uses in unevaluated operands or for classes that do 17108 // not have a vtable. 17109 if (!Class->isDynamicClass() || Class->isDependentContext() || 17110 CurContext->isDependentContext() || isUnevaluatedContext()) 17111 return; 17112 // Do not mark as used if compiling for the device outside of the target 17113 // region. 17114 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17115 !isInOpenMPDeclareTargetContext() && 17116 !isInOpenMPTargetExecutionDirective()) { 17117 if (!DefinitionRequired) 17118 MarkVirtualMembersReferenced(Loc, Class); 17119 return; 17120 } 17121 17122 // Try to insert this class into the map. 17123 LoadExternalVTableUses(); 17124 Class = Class->getCanonicalDecl(); 17125 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17126 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17127 if (!Pos.second) { 17128 // If we already had an entry, check to see if we are promoting this vtable 17129 // to require a definition. If so, we need to reappend to the VTableUses 17130 // list, since we may have already processed the first entry. 17131 if (DefinitionRequired && !Pos.first->second) { 17132 Pos.first->second = true; 17133 } else { 17134 // Otherwise, we can early exit. 17135 return; 17136 } 17137 } else { 17138 // The Microsoft ABI requires that we perform the destructor body 17139 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17140 // the deleting destructor is emitted with the vtable, not with the 17141 // destructor definition as in the Itanium ABI. 17142 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17143 CXXDestructorDecl *DD = Class->getDestructor(); 17144 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17145 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17146 // If this is an out-of-line declaration, marking it referenced will 17147 // not do anything. Manually call CheckDestructor to look up operator 17148 // delete(). 17149 ContextRAII SavedContext(*this, DD); 17150 CheckDestructor(DD); 17151 } else { 17152 MarkFunctionReferenced(Loc, Class->getDestructor()); 17153 } 17154 } 17155 } 17156 } 17157 17158 // Local classes need to have their virtual members marked 17159 // immediately. For all other classes, we mark their virtual members 17160 // at the end of the translation unit. 17161 if (Class->isLocalClass()) 17162 MarkVirtualMembersReferenced(Loc, Class); 17163 else 17164 VTableUses.push_back(std::make_pair(Class, Loc)); 17165 } 17166 17167 bool Sema::DefineUsedVTables() { 17168 LoadExternalVTableUses(); 17169 if (VTableUses.empty()) 17170 return false; 17171 17172 // Note: The VTableUses vector could grow as a result of marking 17173 // the members of a class as "used", so we check the size each 17174 // time through the loop and prefer indices (which are stable) to 17175 // iterators (which are not). 17176 bool DefinedAnything = false; 17177 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17178 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17179 if (!Class) 17180 continue; 17181 TemplateSpecializationKind ClassTSK = 17182 Class->getTemplateSpecializationKind(); 17183 17184 SourceLocation Loc = VTableUses[I].second; 17185 17186 bool DefineVTable = true; 17187 17188 // If this class has a key function, but that key function is 17189 // defined in another translation unit, we don't need to emit the 17190 // vtable even though we're using it. 17191 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17192 if (KeyFunction && !KeyFunction->hasBody()) { 17193 // The key function is in another translation unit. 17194 DefineVTable = false; 17195 TemplateSpecializationKind TSK = 17196 KeyFunction->getTemplateSpecializationKind(); 17197 assert(TSK != TSK_ExplicitInstantiationDefinition && 17198 TSK != TSK_ImplicitInstantiation && 17199 "Instantiations don't have key functions"); 17200 (void)TSK; 17201 } else if (!KeyFunction) { 17202 // If we have a class with no key function that is the subject 17203 // of an explicit instantiation declaration, suppress the 17204 // vtable; it will live with the explicit instantiation 17205 // definition. 17206 bool IsExplicitInstantiationDeclaration = 17207 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17208 for (auto R : Class->redecls()) { 17209 TemplateSpecializationKind TSK 17210 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17211 if (TSK == TSK_ExplicitInstantiationDeclaration) 17212 IsExplicitInstantiationDeclaration = true; 17213 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17214 IsExplicitInstantiationDeclaration = false; 17215 break; 17216 } 17217 } 17218 17219 if (IsExplicitInstantiationDeclaration) 17220 DefineVTable = false; 17221 } 17222 17223 // The exception specifications for all virtual members may be needed even 17224 // if we are not providing an authoritative form of the vtable in this TU. 17225 // We may choose to emit it available_externally anyway. 17226 if (!DefineVTable) { 17227 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17228 continue; 17229 } 17230 17231 // Mark all of the virtual members of this class as referenced, so 17232 // that we can build a vtable. Then, tell the AST consumer that a 17233 // vtable for this class is required. 17234 DefinedAnything = true; 17235 MarkVirtualMembersReferenced(Loc, Class); 17236 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17237 if (VTablesUsed[Canonical]) 17238 Consumer.HandleVTable(Class); 17239 17240 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17241 // no key function or the key function is inlined. Don't warn in C++ ABIs 17242 // that lack key functions, since the user won't be able to make one. 17243 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17244 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17245 const FunctionDecl *KeyFunctionDef = nullptr; 17246 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17247 KeyFunctionDef->isInlined())) { 17248 Diag(Class->getLocation(), 17249 ClassTSK == TSK_ExplicitInstantiationDefinition 17250 ? diag::warn_weak_template_vtable 17251 : diag::warn_weak_vtable) 17252 << Class; 17253 } 17254 } 17255 } 17256 VTableUses.clear(); 17257 17258 return DefinedAnything; 17259 } 17260 17261 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17262 const CXXRecordDecl *RD) { 17263 for (const auto *I : RD->methods()) 17264 if (I->isVirtual() && !I->isPure()) 17265 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17266 } 17267 17268 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17269 const CXXRecordDecl *RD, 17270 bool ConstexprOnly) { 17271 // Mark all functions which will appear in RD's vtable as used. 17272 CXXFinalOverriderMap FinalOverriders; 17273 RD->getFinalOverriders(FinalOverriders); 17274 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17275 E = FinalOverriders.end(); 17276 I != E; ++I) { 17277 for (OverridingMethods::const_iterator OI = I->second.begin(), 17278 OE = I->second.end(); 17279 OI != OE; ++OI) { 17280 assert(OI->second.size() > 0 && "no final overrider"); 17281 CXXMethodDecl *Overrider = OI->second.front().Method; 17282 17283 // C++ [basic.def.odr]p2: 17284 // [...] A virtual member function is used if it is not pure. [...] 17285 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17286 MarkFunctionReferenced(Loc, Overrider); 17287 } 17288 } 17289 17290 // Only classes that have virtual bases need a VTT. 17291 if (RD->getNumVBases() == 0) 17292 return; 17293 17294 for (const auto &I : RD->bases()) { 17295 const auto *Base = 17296 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17297 if (Base->getNumVBases() == 0) 17298 continue; 17299 MarkVirtualMembersReferenced(Loc, Base); 17300 } 17301 } 17302 17303 /// SetIvarInitializers - This routine builds initialization ASTs for the 17304 /// Objective-C implementation whose ivars need be initialized. 17305 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17306 if (!getLangOpts().CPlusPlus) 17307 return; 17308 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17309 SmallVector<ObjCIvarDecl*, 8> ivars; 17310 CollectIvarsToConstructOrDestruct(OID, ivars); 17311 if (ivars.empty()) 17312 return; 17313 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17314 for (unsigned i = 0; i < ivars.size(); i++) { 17315 FieldDecl *Field = ivars[i]; 17316 if (Field->isInvalidDecl()) 17317 continue; 17318 17319 CXXCtorInitializer *Member; 17320 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17321 InitializationKind InitKind = 17322 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17323 17324 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17325 ExprResult MemberInit = 17326 InitSeq.Perform(*this, InitEntity, InitKind, None); 17327 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17328 // Note, MemberInit could actually come back empty if no initialization 17329 // is required (e.g., because it would call a trivial default constructor) 17330 if (!MemberInit.get() || MemberInit.isInvalid()) 17331 continue; 17332 17333 Member = 17334 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17335 SourceLocation(), 17336 MemberInit.getAs<Expr>(), 17337 SourceLocation()); 17338 AllToInit.push_back(Member); 17339 17340 // Be sure that the destructor is accessible and is marked as referenced. 17341 if (const RecordType *RecordTy = 17342 Context.getBaseElementType(Field->getType()) 17343 ->getAs<RecordType>()) { 17344 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17345 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17346 MarkFunctionReferenced(Field->getLocation(), Destructor); 17347 CheckDestructorAccess(Field->getLocation(), Destructor, 17348 PDiag(diag::err_access_dtor_ivar) 17349 << Context.getBaseElementType(Field->getType())); 17350 } 17351 } 17352 } 17353 ObjCImplementation->setIvarInitializers(Context, 17354 AllToInit.data(), AllToInit.size()); 17355 } 17356 } 17357 17358 static 17359 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17360 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17361 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17362 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17363 Sema &S) { 17364 if (Ctor->isInvalidDecl()) 17365 return; 17366 17367 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17368 17369 // Target may not be determinable yet, for instance if this is a dependent 17370 // call in an uninstantiated template. 17371 if (Target) { 17372 const FunctionDecl *FNTarget = nullptr; 17373 (void)Target->hasBody(FNTarget); 17374 Target = const_cast<CXXConstructorDecl*>( 17375 cast_or_null<CXXConstructorDecl>(FNTarget)); 17376 } 17377 17378 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17379 // Avoid dereferencing a null pointer here. 17380 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17381 17382 if (!Current.insert(Canonical).second) 17383 return; 17384 17385 // We know that beyond here, we aren't chaining into a cycle. 17386 if (!Target || !Target->isDelegatingConstructor() || 17387 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17388 Valid.insert(Current.begin(), Current.end()); 17389 Current.clear(); 17390 // We've hit a cycle. 17391 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17392 Current.count(TCanonical)) { 17393 // If we haven't diagnosed this cycle yet, do so now. 17394 if (!Invalid.count(TCanonical)) { 17395 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17396 diag::warn_delegating_ctor_cycle) 17397 << Ctor; 17398 17399 // Don't add a note for a function delegating directly to itself. 17400 if (TCanonical != Canonical) 17401 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17402 17403 CXXConstructorDecl *C = Target; 17404 while (C->getCanonicalDecl() != Canonical) { 17405 const FunctionDecl *FNTarget = nullptr; 17406 (void)C->getTargetConstructor()->hasBody(FNTarget); 17407 assert(FNTarget && "Ctor cycle through bodiless function"); 17408 17409 C = const_cast<CXXConstructorDecl*>( 17410 cast<CXXConstructorDecl>(FNTarget)); 17411 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17412 } 17413 } 17414 17415 Invalid.insert(Current.begin(), Current.end()); 17416 Current.clear(); 17417 } else { 17418 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17419 } 17420 } 17421 17422 17423 void Sema::CheckDelegatingCtorCycles() { 17424 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17425 17426 for (DelegatingCtorDeclsType::iterator 17427 I = DelegatingCtorDecls.begin(ExternalSource), 17428 E = DelegatingCtorDecls.end(); 17429 I != E; ++I) 17430 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17431 17432 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17433 (*CI)->setInvalidDecl(); 17434 } 17435 17436 namespace { 17437 /// AST visitor that finds references to the 'this' expression. 17438 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17439 Sema &S; 17440 17441 public: 17442 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17443 17444 bool VisitCXXThisExpr(CXXThisExpr *E) { 17445 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17446 << E->isImplicit(); 17447 return false; 17448 } 17449 }; 17450 } 17451 17452 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17453 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17454 if (!TSInfo) 17455 return false; 17456 17457 TypeLoc TL = TSInfo->getTypeLoc(); 17458 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17459 if (!ProtoTL) 17460 return false; 17461 17462 // C++11 [expr.prim.general]p3: 17463 // [The expression this] shall not appear before the optional 17464 // cv-qualifier-seq and it shall not appear within the declaration of a 17465 // static member function (although its type and value category are defined 17466 // within a static member function as they are within a non-static member 17467 // function). [ Note: this is because declaration matching does not occur 17468 // until the complete declarator is known. - end note ] 17469 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17470 FindCXXThisExpr Finder(*this); 17471 17472 // If the return type came after the cv-qualifier-seq, check it now. 17473 if (Proto->hasTrailingReturn() && 17474 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17475 return true; 17476 17477 // Check the exception specification. 17478 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17479 return true; 17480 17481 // Check the trailing requires clause 17482 if (Expr *E = Method->getTrailingRequiresClause()) 17483 if (!Finder.TraverseStmt(E)) 17484 return true; 17485 17486 return checkThisInStaticMemberFunctionAttributes(Method); 17487 } 17488 17489 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17490 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17491 if (!TSInfo) 17492 return false; 17493 17494 TypeLoc TL = TSInfo->getTypeLoc(); 17495 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17496 if (!ProtoTL) 17497 return false; 17498 17499 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17500 FindCXXThisExpr Finder(*this); 17501 17502 switch (Proto->getExceptionSpecType()) { 17503 case EST_Unparsed: 17504 case EST_Uninstantiated: 17505 case EST_Unevaluated: 17506 case EST_BasicNoexcept: 17507 case EST_NoThrow: 17508 case EST_DynamicNone: 17509 case EST_MSAny: 17510 case EST_None: 17511 break; 17512 17513 case EST_DependentNoexcept: 17514 case EST_NoexceptFalse: 17515 case EST_NoexceptTrue: 17516 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17517 return true; 17518 LLVM_FALLTHROUGH; 17519 17520 case EST_Dynamic: 17521 for (const auto &E : Proto->exceptions()) { 17522 if (!Finder.TraverseType(E)) 17523 return true; 17524 } 17525 break; 17526 } 17527 17528 return false; 17529 } 17530 17531 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17532 FindCXXThisExpr Finder(*this); 17533 17534 // Check attributes. 17535 for (const auto *A : Method->attrs()) { 17536 // FIXME: This should be emitted by tblgen. 17537 Expr *Arg = nullptr; 17538 ArrayRef<Expr *> Args; 17539 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17540 Arg = G->getArg(); 17541 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17542 Arg = G->getArg(); 17543 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17544 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17545 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17546 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17547 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17548 Arg = ETLF->getSuccessValue(); 17549 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17550 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17551 Arg = STLF->getSuccessValue(); 17552 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17553 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17554 Arg = LR->getArg(); 17555 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17556 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17557 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17558 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17559 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17560 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17561 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17562 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17563 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17564 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17565 17566 if (Arg && !Finder.TraverseStmt(Arg)) 17567 return true; 17568 17569 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17570 if (!Finder.TraverseStmt(Args[I])) 17571 return true; 17572 } 17573 } 17574 17575 return false; 17576 } 17577 17578 void Sema::checkExceptionSpecification( 17579 bool IsTopLevel, ExceptionSpecificationType EST, 17580 ArrayRef<ParsedType> DynamicExceptions, 17581 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17582 SmallVectorImpl<QualType> &Exceptions, 17583 FunctionProtoType::ExceptionSpecInfo &ESI) { 17584 Exceptions.clear(); 17585 ESI.Type = EST; 17586 if (EST == EST_Dynamic) { 17587 Exceptions.reserve(DynamicExceptions.size()); 17588 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17589 // FIXME: Preserve type source info. 17590 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17591 17592 if (IsTopLevel) { 17593 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17594 collectUnexpandedParameterPacks(ET, Unexpanded); 17595 if (!Unexpanded.empty()) { 17596 DiagnoseUnexpandedParameterPacks( 17597 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17598 Unexpanded); 17599 continue; 17600 } 17601 } 17602 17603 // Check that the type is valid for an exception spec, and 17604 // drop it if not. 17605 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17606 Exceptions.push_back(ET); 17607 } 17608 ESI.Exceptions = Exceptions; 17609 return; 17610 } 17611 17612 if (isComputedNoexcept(EST)) { 17613 assert((NoexceptExpr->isTypeDependent() || 17614 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17615 Context.BoolTy) && 17616 "Parser should have made sure that the expression is boolean"); 17617 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17618 ESI.Type = EST_BasicNoexcept; 17619 return; 17620 } 17621 17622 ESI.NoexceptExpr = NoexceptExpr; 17623 return; 17624 } 17625 } 17626 17627 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17628 ExceptionSpecificationType EST, 17629 SourceRange SpecificationRange, 17630 ArrayRef<ParsedType> DynamicExceptions, 17631 ArrayRef<SourceRange> DynamicExceptionRanges, 17632 Expr *NoexceptExpr) { 17633 if (!MethodD) 17634 return; 17635 17636 // Dig out the method we're referring to. 17637 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17638 MethodD = FunTmpl->getTemplatedDecl(); 17639 17640 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17641 if (!Method) 17642 return; 17643 17644 // Check the exception specification. 17645 llvm::SmallVector<QualType, 4> Exceptions; 17646 FunctionProtoType::ExceptionSpecInfo ESI; 17647 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17648 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17649 ESI); 17650 17651 // Update the exception specification on the function type. 17652 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17653 17654 if (Method->isStatic()) 17655 checkThisInStaticMemberFunctionExceptionSpec(Method); 17656 17657 if (Method->isVirtual()) { 17658 // Check overrides, which we previously had to delay. 17659 for (const CXXMethodDecl *O : Method->overridden_methods()) 17660 CheckOverridingFunctionExceptionSpec(Method, O); 17661 } 17662 } 17663 17664 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17665 /// 17666 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17667 SourceLocation DeclStart, Declarator &D, 17668 Expr *BitWidth, 17669 InClassInitStyle InitStyle, 17670 AccessSpecifier AS, 17671 const ParsedAttr &MSPropertyAttr) { 17672 IdentifierInfo *II = D.getIdentifier(); 17673 if (!II) { 17674 Diag(DeclStart, diag::err_anonymous_property); 17675 return nullptr; 17676 } 17677 SourceLocation Loc = D.getIdentifierLoc(); 17678 17679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17680 QualType T = TInfo->getType(); 17681 if (getLangOpts().CPlusPlus) { 17682 CheckExtraCXXDefaultArguments(D); 17683 17684 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17685 UPPC_DataMemberType)) { 17686 D.setInvalidType(); 17687 T = Context.IntTy; 17688 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17689 } 17690 } 17691 17692 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17693 17694 if (D.getDeclSpec().isInlineSpecified()) 17695 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17696 << getLangOpts().CPlusPlus17; 17697 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17698 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17699 diag::err_invalid_thread) 17700 << DeclSpec::getSpecifierName(TSCS); 17701 17702 // Check to see if this name was declared as a member previously 17703 NamedDecl *PrevDecl = nullptr; 17704 LookupResult Previous(*this, II, Loc, LookupMemberName, 17705 ForVisibleRedeclaration); 17706 LookupName(Previous, S); 17707 switch (Previous.getResultKind()) { 17708 case LookupResult::Found: 17709 case LookupResult::FoundUnresolvedValue: 17710 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17711 break; 17712 17713 case LookupResult::FoundOverloaded: 17714 PrevDecl = Previous.getRepresentativeDecl(); 17715 break; 17716 17717 case LookupResult::NotFound: 17718 case LookupResult::NotFoundInCurrentInstantiation: 17719 case LookupResult::Ambiguous: 17720 break; 17721 } 17722 17723 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17724 // Maybe we will complain about the shadowed template parameter. 17725 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17726 // Just pretend that we didn't see the previous declaration. 17727 PrevDecl = nullptr; 17728 } 17729 17730 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17731 PrevDecl = nullptr; 17732 17733 SourceLocation TSSL = D.getBeginLoc(); 17734 MSPropertyDecl *NewPD = 17735 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17736 MSPropertyAttr.getPropertyDataGetter(), 17737 MSPropertyAttr.getPropertyDataSetter()); 17738 ProcessDeclAttributes(TUScope, NewPD, D); 17739 NewPD->setAccess(AS); 17740 17741 if (NewPD->isInvalidDecl()) 17742 Record->setInvalidDecl(); 17743 17744 if (D.getDeclSpec().isModulePrivateSpecified()) 17745 NewPD->setModulePrivate(); 17746 17747 if (NewPD->isInvalidDecl() && PrevDecl) { 17748 // Don't introduce NewFD into scope; there's already something 17749 // with the same name in the same scope. 17750 } else if (II) { 17751 PushOnScopeChains(NewPD, S); 17752 } else 17753 Record->addDecl(NewPD); 17754 17755 return NewPD; 17756 } 17757 17758 void Sema::ActOnStartFunctionDeclarationDeclarator( 17759 Declarator &Declarator, unsigned TemplateParameterDepth) { 17760 auto &Info = InventedParameterInfos.emplace_back(); 17761 TemplateParameterList *ExplicitParams = nullptr; 17762 ArrayRef<TemplateParameterList *> ExplicitLists = 17763 Declarator.getTemplateParameterLists(); 17764 if (!ExplicitLists.empty()) { 17765 bool IsMemberSpecialization, IsInvalid; 17766 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17767 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17768 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17769 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17770 /*SuppressDiagnostic=*/true); 17771 } 17772 if (ExplicitParams) { 17773 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17774 for (NamedDecl *Param : *ExplicitParams) 17775 Info.TemplateParams.push_back(Param); 17776 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17777 } else { 17778 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17779 Info.NumExplicitTemplateParams = 0; 17780 } 17781 } 17782 17783 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17784 auto &FSI = InventedParameterInfos.back(); 17785 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17786 if (FSI.NumExplicitTemplateParams != 0) { 17787 TemplateParameterList *ExplicitParams = 17788 Declarator.getTemplateParameterLists().back(); 17789 Declarator.setInventedTemplateParameterList( 17790 TemplateParameterList::Create( 17791 Context, ExplicitParams->getTemplateLoc(), 17792 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17793 ExplicitParams->getRAngleLoc(), 17794 ExplicitParams->getRequiresClause())); 17795 } else { 17796 Declarator.setInventedTemplateParameterList( 17797 TemplateParameterList::Create( 17798 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17799 SourceLocation(), /*RequiresClause=*/nullptr)); 17800 } 17801 } 17802 InventedParameterInfos.pop_back(); 17803 } 17804