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(ParmVarDecl *Param, Expr *Arg, 258 SourceLocation EqualLoc) { 259 if (RequireCompleteType(Param->getLocation(), Param->getType(), 260 diag::err_typecheck_decl_incomplete_type)) 261 return true; 262 263 // C++ [dcl.fct.default]p5 264 // A default argument expression is implicitly converted (clause 265 // 4) to the parameter type. The default argument expression has 266 // the same semantic constraints as the initializer expression in 267 // a declaration of a variable of the parameter type, using the 268 // copy-initialization semantics (8.5). 269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 270 Param); 271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 272 EqualLoc); 273 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 275 if (Result.isInvalid()) 276 return true; 277 Arg = Result.getAs<Expr>(); 278 279 CheckCompletedExpr(Arg, EqualLoc); 280 Arg = MaybeCreateExprWithCleanups(Arg); 281 282 return Arg; 283 } 284 285 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 286 SourceLocation EqualLoc) { 287 // Add the default argument to the parameter 288 Param->setDefaultArg(Arg); 289 290 // We have already instantiated this parameter; provide each of the 291 // instantiations with the uninstantiated default argument. 292 UnparsedDefaultArgInstantiationsMap::iterator InstPos 293 = UnparsedDefaultArgInstantiations.find(Param); 294 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 297 298 // We're done tracking this parameter's instantiations. 299 UnparsedDefaultArgInstantiations.erase(InstPos); 300 } 301 } 302 303 /// ActOnParamDefaultArgument - Check whether the default argument 304 /// provided for a function parameter is well-formed. If so, attach it 305 /// to the parameter declaration. 306 void 307 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 308 Expr *DefaultArg) { 309 if (!param || !DefaultArg) 310 return; 311 312 ParmVarDecl *Param = cast<ParmVarDecl>(param); 313 UnparsedDefaultArgLocs.erase(Param); 314 315 auto Fail = [&] { 316 Param->setInvalidDecl(); 317 Param->setDefaultArg(new (Context) OpaqueValueExpr( 318 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 319 }; 320 321 // Default arguments are only permitted in C++ 322 if (!getLangOpts().CPlusPlus) { 323 Diag(EqualLoc, diag::err_param_default_argument) 324 << DefaultArg->getSourceRange(); 325 return Fail(); 326 } 327 328 // Check for unexpanded parameter packs. 329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 330 return Fail(); 331 } 332 333 // C++11 [dcl.fct.default]p3 334 // A default argument expression [...] shall not be specified for a 335 // parameter pack. 336 if (Param->isParameterPack()) { 337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 338 << DefaultArg->getSourceRange(); 339 // Recover by discarding the default argument. 340 Param->setDefaultArg(nullptr); 341 return; 342 } 343 344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 345 if (Result.isInvalid()) 346 return Fail(); 347 348 DefaultArg = Result.getAs<Expr>(); 349 350 // Check that the default argument is well-formed 351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 352 if (DefaultArgChecker.Visit(DefaultArg)) 353 return Fail(); 354 355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 356 } 357 358 /// ActOnParamUnparsedDefaultArgument - We've seen a default 359 /// argument for a function parameter, but we can't parse it yet 360 /// because we're inside a class definition. Note that this default 361 /// argument will be parsed later. 362 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 363 SourceLocation EqualLoc, 364 SourceLocation ArgLoc) { 365 if (!param) 366 return; 367 368 ParmVarDecl *Param = cast<ParmVarDecl>(param); 369 Param->setUnparsedDefaultArg(); 370 UnparsedDefaultArgLocs[Param] = ArgLoc; 371 } 372 373 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 374 /// the default argument for the parameter param failed. 375 void Sema::ActOnParamDefaultArgumentError(Decl *param, 376 SourceLocation EqualLoc) { 377 if (!param) 378 return; 379 380 ParmVarDecl *Param = cast<ParmVarDecl>(param); 381 Param->setInvalidDecl(); 382 UnparsedDefaultArgLocs.erase(Param); 383 Param->setDefaultArg(new(Context) 384 OpaqueValueExpr(EqualLoc, 385 Param->getType().getNonReferenceType(), 386 VK_RValue)); 387 } 388 389 /// CheckExtraCXXDefaultArguments - Check for any extra default 390 /// arguments in the declarator, which is not a function declaration 391 /// or definition and therefore is not permitted to have default 392 /// arguments. This routine should be invoked for every declarator 393 /// that is not a function declaration or definition. 394 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 395 // C++ [dcl.fct.default]p3 396 // A default argument expression shall be specified only in the 397 // parameter-declaration-clause of a function declaration or in a 398 // template-parameter (14.1). It shall not be specified for a 399 // parameter pack. If it is specified in a 400 // parameter-declaration-clause, it shall not occur within a 401 // declarator or abstract-declarator of a parameter-declaration. 402 bool MightBeFunction = D.isFunctionDeclarationContext(); 403 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 404 DeclaratorChunk &chunk = D.getTypeObject(i); 405 if (chunk.Kind == DeclaratorChunk::Function) { 406 if (MightBeFunction) { 407 // This is a function declaration. It can have default arguments, but 408 // keep looking in case its return type is a function type with default 409 // arguments. 410 MightBeFunction = false; 411 continue; 412 } 413 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 414 ++argIdx) { 415 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 416 if (Param->hasUnparsedDefaultArg()) { 417 std::unique_ptr<CachedTokens> Toks = 418 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 419 SourceRange SR; 420 if (Toks->size() > 1) 421 SR = SourceRange((*Toks)[1].getLocation(), 422 Toks->back().getLocation()); 423 else 424 SR = UnparsedDefaultArgLocs[Param]; 425 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 426 << SR; 427 } else if (Param->getDefaultArg()) { 428 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 429 << Param->getDefaultArg()->getSourceRange(); 430 Param->setDefaultArg(nullptr); 431 } 432 } 433 } else if (chunk.Kind != DeclaratorChunk::Paren) { 434 MightBeFunction = false; 435 } 436 } 437 } 438 439 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 440 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 441 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 442 }); 443 } 444 445 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 446 /// function, once we already know that they have the same 447 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 448 /// error, false otherwise. 449 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 450 Scope *S) { 451 bool Invalid = false; 452 453 // The declaration context corresponding to the scope is the semantic 454 // parent, unless this is a local function declaration, in which case 455 // it is that surrounding function. 456 DeclContext *ScopeDC = New->isLocalExternDecl() 457 ? New->getLexicalDeclContext() 458 : New->getDeclContext(); 459 460 // Find the previous declaration for the purpose of default arguments. 461 FunctionDecl *PrevForDefaultArgs = Old; 462 for (/**/; PrevForDefaultArgs; 463 // Don't bother looking back past the latest decl if this is a local 464 // extern declaration; nothing else could work. 465 PrevForDefaultArgs = New->isLocalExternDecl() 466 ? nullptr 467 : PrevForDefaultArgs->getPreviousDecl()) { 468 // Ignore hidden declarations. 469 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 470 continue; 471 472 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 473 !New->isCXXClassMember()) { 474 // Ignore default arguments of old decl if they are not in 475 // the same scope and this is not an out-of-line definition of 476 // a member function. 477 continue; 478 } 479 480 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 481 // If only one of these is a local function declaration, then they are 482 // declared in different scopes, even though isDeclInScope may think 483 // they're in the same scope. (If both are local, the scope check is 484 // sufficient, and if neither is local, then they are in the same scope.) 485 continue; 486 } 487 488 // We found the right previous declaration. 489 break; 490 } 491 492 // C++ [dcl.fct.default]p4: 493 // For non-template functions, default arguments can be added in 494 // later declarations of a function in the same 495 // scope. Declarations in different scopes have completely 496 // distinct sets of default arguments. That is, declarations in 497 // inner scopes do not acquire default arguments from 498 // declarations in outer scopes, and vice versa. In a given 499 // function declaration, all parameters subsequent to a 500 // parameter with a default argument shall have default 501 // arguments supplied in this or previous declarations. A 502 // default argument shall not be redefined by a later 503 // declaration (not even to the same value). 504 // 505 // C++ [dcl.fct.default]p6: 506 // Except for member functions of class templates, the default arguments 507 // in a member function definition that appears outside of the class 508 // definition are added to the set of default arguments provided by the 509 // member function declaration in the class definition. 510 for (unsigned p = 0, NumParams = PrevForDefaultArgs 511 ? PrevForDefaultArgs->getNumParams() 512 : 0; 513 p < NumParams; ++p) { 514 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 515 ParmVarDecl *NewParam = New->getParamDecl(p); 516 517 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 518 bool NewParamHasDfl = NewParam->hasDefaultArg(); 519 520 if (OldParamHasDfl && NewParamHasDfl) { 521 unsigned DiagDefaultParamID = 522 diag::err_param_default_argument_redefinition; 523 524 // MSVC accepts that default parameters be redefined for member functions 525 // of template class. The new default parameter's value is ignored. 526 Invalid = true; 527 if (getLangOpts().MicrosoftExt) { 528 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 529 if (MD && MD->getParent()->getDescribedClassTemplate()) { 530 // Merge the old default argument into the new parameter. 531 NewParam->setHasInheritedDefaultArg(); 532 if (OldParam->hasUninstantiatedDefaultArg()) 533 NewParam->setUninstantiatedDefaultArg( 534 OldParam->getUninstantiatedDefaultArg()); 535 else 536 NewParam->setDefaultArg(OldParam->getInit()); 537 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 538 Invalid = false; 539 } 540 } 541 542 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 543 // hint here. Alternatively, we could walk the type-source information 544 // for NewParam to find the last source location in the type... but it 545 // isn't worth the effort right now. This is the kind of test case that 546 // is hard to get right: 547 // int f(int); 548 // void g(int (*fp)(int) = f); 549 // void g(int (*fp)(int) = &f); 550 Diag(NewParam->getLocation(), DiagDefaultParamID) 551 << NewParam->getDefaultArgRange(); 552 553 // Look for the function declaration where the default argument was 554 // actually written, which may be a declaration prior to Old. 555 for (auto Older = PrevForDefaultArgs; 556 OldParam->hasInheritedDefaultArg(); /**/) { 557 Older = Older->getPreviousDecl(); 558 OldParam = Older->getParamDecl(p); 559 } 560 561 Diag(OldParam->getLocation(), diag::note_previous_definition) 562 << OldParam->getDefaultArgRange(); 563 } else if (OldParamHasDfl) { 564 // Merge the old default argument into the new parameter unless the new 565 // function is a friend declaration in a template class. In the latter 566 // case the default arguments will be inherited when the friend 567 // declaration will be instantiated. 568 if (New->getFriendObjectKind() == Decl::FOK_None || 569 !New->getLexicalDeclContext()->isDependentContext()) { 570 // It's important to use getInit() here; getDefaultArg() 571 // strips off any top-level ExprWithCleanups. 572 NewParam->setHasInheritedDefaultArg(); 573 if (OldParam->hasUnparsedDefaultArg()) 574 NewParam->setUnparsedDefaultArg(); 575 else if (OldParam->hasUninstantiatedDefaultArg()) 576 NewParam->setUninstantiatedDefaultArg( 577 OldParam->getUninstantiatedDefaultArg()); 578 else 579 NewParam->setDefaultArg(OldParam->getInit()); 580 } 581 } else if (NewParamHasDfl) { 582 if (New->getDescribedFunctionTemplate()) { 583 // Paragraph 4, quoted above, only applies to non-template functions. 584 Diag(NewParam->getLocation(), 585 diag::err_param_default_argument_template_redecl) 586 << NewParam->getDefaultArgRange(); 587 Diag(PrevForDefaultArgs->getLocation(), 588 diag::note_template_prev_declaration) 589 << false; 590 } else if (New->getTemplateSpecializationKind() 591 != TSK_ImplicitInstantiation && 592 New->getTemplateSpecializationKind() != TSK_Undeclared) { 593 // C++ [temp.expr.spec]p21: 594 // Default function arguments shall not be specified in a declaration 595 // or a definition for one of the following explicit specializations: 596 // - the explicit specialization of a function template; 597 // - the explicit specialization of a member function template; 598 // - the explicit specialization of a member function of a class 599 // template where the class template specialization to which the 600 // member function specialization belongs is implicitly 601 // instantiated. 602 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 603 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 604 << New->getDeclName() 605 << NewParam->getDefaultArgRange(); 606 } else if (New->getDeclContext()->isDependentContext()) { 607 // C++ [dcl.fct.default]p6 (DR217): 608 // Default arguments for a member function of a class template shall 609 // be specified on the initial declaration of the member function 610 // within the class template. 611 // 612 // Reading the tea leaves a bit in DR217 and its reference to DR205 613 // leads me to the conclusion that one cannot add default function 614 // arguments for an out-of-line definition of a member function of a 615 // dependent type. 616 int WhichKind = 2; 617 if (CXXRecordDecl *Record 618 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 619 if (Record->getDescribedClassTemplate()) 620 WhichKind = 0; 621 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 622 WhichKind = 1; 623 else 624 WhichKind = 2; 625 } 626 627 Diag(NewParam->getLocation(), 628 diag::err_param_default_argument_member_template_redecl) 629 << WhichKind 630 << NewParam->getDefaultArgRange(); 631 } 632 } 633 } 634 635 // DR1344: If a default argument is added outside a class definition and that 636 // default argument makes the function a special member function, the program 637 // is ill-formed. This can only happen for constructors. 638 if (isa<CXXConstructorDecl>(New) && 639 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 640 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 641 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 642 if (NewSM != OldSM) { 643 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 644 assert(NewParam->hasDefaultArg()); 645 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 646 << NewParam->getDefaultArgRange() << NewSM; 647 Diag(Old->getLocation(), diag::note_previous_declaration); 648 } 649 } 650 651 const FunctionDecl *Def; 652 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 653 // template has a constexpr specifier then all its declarations shall 654 // contain the constexpr specifier. 655 if (New->getConstexprKind() != Old->getConstexprKind()) { 656 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 657 << New << static_cast<int>(New->getConstexprKind()) 658 << static_cast<int>(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 // C++11 [temp.friend]p4 (DR329): 698 // When a function is defined in a friend function declaration in a class 699 // template, the function is instantiated when the function is odr-used. 700 // The same restrictions on multiple declarations and definitions that 701 // apply to non-template function declarations and definitions also apply 702 // to these implicit definitions. 703 const FunctionDecl *OldDefinition = nullptr; 704 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 705 Old->isDefined(OldDefinition, true)) 706 CheckForFunctionRedefinition(New, OldDefinition); 707 708 return Invalid; 709 } 710 711 NamedDecl * 712 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 713 MultiTemplateParamsArg TemplateParamLists) { 714 assert(D.isDecompositionDeclarator()); 715 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 716 717 // The syntax only allows a decomposition declarator as a simple-declaration, 718 // a for-range-declaration, or a condition in Clang, but we parse it in more 719 // cases than that. 720 if (!D.mayHaveDecompositionDeclarator()) { 721 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 722 << Decomp.getSourceRange(); 723 return nullptr; 724 } 725 726 if (!TemplateParamLists.empty()) { 727 // FIXME: There's no rule against this, but there are also no rules that 728 // would actually make it usable, so we reject it for now. 729 Diag(TemplateParamLists.front()->getTemplateLoc(), 730 diag::err_decomp_decl_template); 731 return nullptr; 732 } 733 734 Diag(Decomp.getLSquareLoc(), 735 !getLangOpts().CPlusPlus17 736 ? diag::ext_decomp_decl 737 : D.getContext() == DeclaratorContext::Condition 738 ? diag::ext_decomp_decl_cond 739 : diag::warn_cxx14_compat_decomp_decl) 740 << Decomp.getSourceRange(); 741 742 // The semantic context is always just the current context. 743 DeclContext *const DC = CurContext; 744 745 // C++17 [dcl.dcl]/8: 746 // The decl-specifier-seq shall contain only the type-specifier auto 747 // and cv-qualifiers. 748 // C++2a [dcl.dcl]/8: 749 // If decl-specifier-seq contains any decl-specifier other than static, 750 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 751 auto &DS = D.getDeclSpec(); 752 { 753 SmallVector<StringRef, 8> BadSpecifiers; 754 SmallVector<SourceLocation, 8> BadSpecifierLocs; 755 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 756 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 757 if (auto SCS = DS.getStorageClassSpec()) { 758 if (SCS == DeclSpec::SCS_static) { 759 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 760 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 761 } else { 762 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 763 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 764 } 765 } 766 if (auto TSCS = DS.getThreadStorageClassSpec()) { 767 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 768 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 769 } 770 if (DS.hasConstexprSpecifier()) { 771 BadSpecifiers.push_back( 772 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 773 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 774 } 775 if (DS.isInlineSpecified()) { 776 BadSpecifiers.push_back("inline"); 777 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 778 } 779 if (!BadSpecifiers.empty()) { 780 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 781 Err << (int)BadSpecifiers.size() 782 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 783 // Don't add FixItHints to remove the specifiers; we do still respect 784 // them when building the underlying variable. 785 for (auto Loc : BadSpecifierLocs) 786 Err << SourceRange(Loc, Loc); 787 } else if (!CPlusPlus20Specifiers.empty()) { 788 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 789 getLangOpts().CPlusPlus20 790 ? diag::warn_cxx17_compat_decomp_decl_spec 791 : diag::ext_decomp_decl_spec); 792 Warn << (int)CPlusPlus20Specifiers.size() 793 << llvm::join(CPlusPlus20Specifiers.begin(), 794 CPlusPlus20Specifiers.end(), " "); 795 for (auto Loc : CPlusPlus20SpecifierLocs) 796 Warn << SourceRange(Loc, Loc); 797 } 798 // We can't recover from it being declared as a typedef. 799 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 800 return nullptr; 801 } 802 803 // C++2a [dcl.struct.bind]p1: 804 // A cv that includes volatile is deprecated 805 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 806 getLangOpts().CPlusPlus20) 807 Diag(DS.getVolatileSpecLoc(), 808 diag::warn_deprecated_volatile_structured_binding); 809 810 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 811 QualType R = TInfo->getType(); 812 813 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 814 UPPC_DeclarationType)) 815 D.setInvalidType(); 816 817 // The syntax only allows a single ref-qualifier prior to the decomposition 818 // declarator. No other declarator chunks are permitted. Also check the type 819 // specifier here. 820 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 821 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 822 (D.getNumTypeObjects() == 1 && 823 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 824 Diag(Decomp.getLSquareLoc(), 825 (D.hasGroupingParens() || 826 (D.getNumTypeObjects() && 827 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 828 ? diag::err_decomp_decl_parens 829 : diag::err_decomp_decl_type) 830 << R; 831 832 // In most cases, there's no actual problem with an explicitly-specified 833 // type, but a function type won't work here, and ActOnVariableDeclarator 834 // shouldn't be called for such a type. 835 if (R->isFunctionType()) 836 D.setInvalidType(); 837 } 838 839 // Build the BindingDecls. 840 SmallVector<BindingDecl*, 8> Bindings; 841 842 // Build the BindingDecls. 843 for (auto &B : D.getDecompositionDeclarator().bindings()) { 844 // Check for name conflicts. 845 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 847 ForVisibleRedeclaration); 848 LookupName(Previous, S, 849 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 850 851 // It's not permitted to shadow a template parameter name. 852 if (Previous.isSingleResult() && 853 Previous.getFoundDecl()->isTemplateParameter()) { 854 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 855 Previous.getFoundDecl()); 856 Previous.clear(); 857 } 858 859 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 860 861 // Find the shadowed declaration before filtering for scope. 862 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 863 ? getShadowedDeclaration(BD, Previous) 864 : nullptr; 865 866 bool ConsiderLinkage = DC->isFunctionOrMethod() && 867 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 868 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 869 /*AllowInlineNamespace*/false); 870 871 if (!Previous.empty()) { 872 auto *Old = Previous.getRepresentativeDecl(); 873 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 874 Diag(Old->getLocation(), diag::note_previous_definition); 875 } else if (ShadowedDecl && !D.isRedeclaration()) { 876 CheckShadow(BD, ShadowedDecl, Previous); 877 } 878 PushOnScopeChains(BD, S, true); 879 Bindings.push_back(BD); 880 ParsingInitForAutoVars.insert(BD); 881 } 882 883 // There are no prior lookup results for the variable itself, because it 884 // is unnamed. 885 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 886 Decomp.getLSquareLoc()); 887 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 888 ForVisibleRedeclaration); 889 890 // Build the variable that holds the non-decomposed object. 891 bool AddToScope = true; 892 NamedDecl *New = 893 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 894 MultiTemplateParamsArg(), AddToScope, Bindings); 895 if (AddToScope) { 896 S->AddDecl(New); 897 CurContext->addHiddenDecl(New); 898 } 899 900 if (isInOpenMPDeclareTargetContext()) 901 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 902 903 return New; 904 } 905 906 static bool checkSimpleDecomposition( 907 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 908 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 909 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 910 if ((int64_t)Bindings.size() != NumElems) { 911 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 912 << DecompType << (unsigned)Bindings.size() 913 << (unsigned)NumElems.getLimitedValue(UINT_MAX) << NumElems.toString(10) 914 << (NumElems < Bindings.size()); 915 return true; 916 } 917 918 unsigned I = 0; 919 for (auto *B : Bindings) { 920 SourceLocation Loc = B->getLocation(); 921 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 922 if (E.isInvalid()) 923 return true; 924 E = GetInit(Loc, E.get(), I++); 925 if (E.isInvalid()) 926 return true; 927 B->setBinding(ElemType, E.get()); 928 } 929 930 return false; 931 } 932 933 static bool checkArrayLikeDecomposition(Sema &S, 934 ArrayRef<BindingDecl *> Bindings, 935 ValueDecl *Src, QualType DecompType, 936 const llvm::APSInt &NumElems, 937 QualType ElemType) { 938 return checkSimpleDecomposition( 939 S, Bindings, Src, DecompType, NumElems, ElemType, 940 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 941 ExprResult E = S.ActOnIntegerConstant(Loc, I); 942 if (E.isInvalid()) 943 return ExprError(); 944 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 945 }); 946 } 947 948 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 949 ValueDecl *Src, QualType DecompType, 950 const ConstantArrayType *CAT) { 951 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 952 llvm::APSInt(CAT->getSize()), 953 CAT->getElementType()); 954 } 955 956 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 957 ValueDecl *Src, QualType DecompType, 958 const VectorType *VT) { 959 return checkArrayLikeDecomposition( 960 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 961 S.Context.getQualifiedType(VT->getElementType(), 962 DecompType.getQualifiers())); 963 } 964 965 static bool checkComplexDecomposition(Sema &S, 966 ArrayRef<BindingDecl *> Bindings, 967 ValueDecl *Src, QualType DecompType, 968 const ComplexType *CT) { 969 return checkSimpleDecomposition( 970 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 971 S.Context.getQualifiedType(CT->getElementType(), 972 DecompType.getQualifiers()), 973 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 974 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 975 }); 976 } 977 978 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 979 TemplateArgumentListInfo &Args) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 for (auto &Arg : Args.arguments()) { 984 if (!First) 985 OS << ", "; 986 Arg.getArgument().print(PrintingPolicy, OS); 987 First = false; 988 } 989 return std::string(OS.str()); 990 } 991 992 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 993 SourceLocation Loc, StringRef Trait, 994 TemplateArgumentListInfo &Args, 995 unsigned DiagID) { 996 auto DiagnoseMissing = [&] { 997 if (DiagID) 998 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 999 Args); 1000 return true; 1001 }; 1002 1003 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1004 NamespaceDecl *Std = S.getStdNamespace(); 1005 if (!Std) 1006 return DiagnoseMissing(); 1007 1008 // Look up the trait itself, within namespace std. We can diagnose various 1009 // problems with this lookup even if we've been asked to not diagnose a 1010 // missing specialization, because this can only fail if the user has been 1011 // declaring their own names in namespace std or we don't support the 1012 // standard library implementation in use. 1013 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1014 Loc, Sema::LookupOrdinaryName); 1015 if (!S.LookupQualifiedName(Result, Std)) 1016 return DiagnoseMissing(); 1017 if (Result.isAmbiguous()) 1018 return true; 1019 1020 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1021 if (!TraitTD) { 1022 Result.suppressDiagnostics(); 1023 NamedDecl *Found = *Result.begin(); 1024 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1025 S.Diag(Found->getLocation(), diag::note_declared_at); 1026 return true; 1027 } 1028 1029 // Build the template-id. 1030 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1031 if (TraitTy.isNull()) 1032 return true; 1033 if (!S.isCompleteType(Loc, TraitTy)) { 1034 if (DiagID) 1035 S.RequireCompleteType( 1036 Loc, TraitTy, DiagID, 1037 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1038 return true; 1039 } 1040 1041 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1042 assert(RD && "specialization of class template is not a class?"); 1043 1044 // Look up the member of the trait type. 1045 S.LookupQualifiedName(TraitMemberLookup, RD); 1046 return TraitMemberLookup.isAmbiguous(); 1047 } 1048 1049 static TemplateArgumentLoc 1050 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1051 uint64_t I) { 1052 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1053 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1054 } 1055 1056 static TemplateArgumentLoc 1057 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1058 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1059 } 1060 1061 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1062 1063 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1064 llvm::APSInt &Size) { 1065 EnterExpressionEvaluationContext ContextRAII( 1066 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1067 1068 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1069 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1070 1071 // Form template argument list for tuple_size<T>. 1072 TemplateArgumentListInfo Args(Loc, Loc); 1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1074 1075 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1076 // it's not tuple-like. 1077 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1078 R.empty()) 1079 return IsTupleLike::NotTupleLike; 1080 1081 // If we get this far, we've committed to the tuple interpretation, but 1082 // we can still fail if there actually isn't a usable ::value. 1083 1084 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1085 LookupResult &R; 1086 TemplateArgumentListInfo &Args; 1087 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1088 : R(R), Args(Args) {} 1089 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1090 SourceLocation Loc) override { 1091 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1092 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1093 } 1094 } Diagnoser(R, Args); 1095 1096 ExprResult E = 1097 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1098 if (E.isInvalid()) 1099 return IsTupleLike::Error; 1100 1101 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1102 if (E.isInvalid()) 1103 return IsTupleLike::Error; 1104 1105 return IsTupleLike::TupleLike; 1106 } 1107 1108 /// \return std::tuple_element<I, T>::type. 1109 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1110 unsigned I, QualType T) { 1111 // Form template argument list for tuple_element<I, T>. 1112 TemplateArgumentListInfo Args(Loc, Loc); 1113 Args.addArgument( 1114 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1115 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1116 1117 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1118 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1119 if (lookupStdTypeTraitMember( 1120 S, R, Loc, "tuple_element", Args, 1121 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1122 return QualType(); 1123 1124 auto *TD = R.getAsSingle<TypeDecl>(); 1125 if (!TD) { 1126 R.suppressDiagnostics(); 1127 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1128 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1129 if (!R.empty()) 1130 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1131 return QualType(); 1132 } 1133 1134 return S.Context.getTypeDeclType(TD); 1135 } 1136 1137 namespace { 1138 struct InitializingBinding { 1139 Sema &S; 1140 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1141 Sema::CodeSynthesisContext Ctx; 1142 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1143 Ctx.PointOfInstantiation = BD->getLocation(); 1144 Ctx.Entity = BD; 1145 S.pushCodeSynthesisContext(Ctx); 1146 } 1147 ~InitializingBinding() { 1148 S.popCodeSynthesisContext(); 1149 } 1150 }; 1151 } 1152 1153 static bool checkTupleLikeDecomposition(Sema &S, 1154 ArrayRef<BindingDecl *> Bindings, 1155 VarDecl *Src, QualType DecompType, 1156 const llvm::APSInt &TupleSize) { 1157 if ((int64_t)Bindings.size() != TupleSize) { 1158 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1159 << DecompType << (unsigned)Bindings.size() 1160 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1161 << TupleSize.toString(10) << (TupleSize < Bindings.size()); 1162 return true; 1163 } 1164 1165 if (Bindings.empty()) 1166 return false; 1167 1168 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1169 1170 // [dcl.decomp]p3: 1171 // The unqualified-id get is looked up in the scope of E by class member 1172 // access lookup ... 1173 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1174 bool UseMemberGet = false; 1175 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1176 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1177 S.LookupQualifiedName(MemberGet, RD); 1178 if (MemberGet.isAmbiguous()) 1179 return true; 1180 // ... and if that finds at least one declaration that is a function 1181 // template whose first template parameter is a non-type parameter ... 1182 for (NamedDecl *D : MemberGet) { 1183 if (FunctionTemplateDecl *FTD = 1184 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1185 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1186 if (TPL->size() != 0 && 1187 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1188 // ... the initializer is e.get<i>(). 1189 UseMemberGet = true; 1190 break; 1191 } 1192 } 1193 } 1194 } 1195 1196 unsigned I = 0; 1197 for (auto *B : Bindings) { 1198 InitializingBinding InitContext(S, B); 1199 SourceLocation Loc = B->getLocation(); 1200 1201 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1202 if (E.isInvalid()) 1203 return true; 1204 1205 // e is an lvalue if the type of the entity is an lvalue reference and 1206 // an xvalue otherwise 1207 if (!Src->getType()->isLValueReferenceType()) 1208 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1209 E.get(), nullptr, VK_XValue, 1210 FPOptionsOverride()); 1211 1212 TemplateArgumentListInfo Args(Loc, Loc); 1213 Args.addArgument( 1214 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1215 1216 if (UseMemberGet) { 1217 // if [lookup of member get] finds at least one declaration, the 1218 // initializer is e.get<i-1>(). 1219 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1220 CXXScopeSpec(), SourceLocation(), nullptr, 1221 MemberGet, &Args, nullptr); 1222 if (E.isInvalid()) 1223 return true; 1224 1225 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1226 } else { 1227 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1228 // in the associated namespaces. 1229 Expr *Get = UnresolvedLookupExpr::Create( 1230 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1231 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1232 UnresolvedSetIterator(), UnresolvedSetIterator()); 1233 1234 Expr *Arg = E.get(); 1235 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1236 } 1237 if (E.isInvalid()) 1238 return true; 1239 Expr *Init = E.get(); 1240 1241 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1242 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1243 if (T.isNull()) 1244 return true; 1245 1246 // each vi is a variable of type "reference to T" initialized with the 1247 // initializer, where the reference is an lvalue reference if the 1248 // initializer is an lvalue and an rvalue reference otherwise 1249 QualType RefType = 1250 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1251 if (RefType.isNull()) 1252 return true; 1253 auto *RefVD = VarDecl::Create( 1254 S.Context, Src->getDeclContext(), Loc, Loc, 1255 B->getDeclName().getAsIdentifierInfo(), RefType, 1256 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1257 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1258 RefVD->setTSCSpec(Src->getTSCSpec()); 1259 RefVD->setImplicit(); 1260 if (Src->isInlineSpecified()) 1261 RefVD->setInlineSpecified(); 1262 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1263 1264 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1265 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1266 InitializationSequence Seq(S, Entity, Kind, Init); 1267 E = Seq.Perform(S, Entity, Kind, Init); 1268 if (E.isInvalid()) 1269 return true; 1270 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1271 if (E.isInvalid()) 1272 return true; 1273 RefVD->setInit(E.get()); 1274 S.CheckCompleteVariableDeclaration(RefVD); 1275 1276 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1277 DeclarationNameInfo(B->getDeclName(), Loc), 1278 RefVD); 1279 if (E.isInvalid()) 1280 return true; 1281 1282 B->setBinding(T, E.get()); 1283 I++; 1284 } 1285 1286 return false; 1287 } 1288 1289 /// Find the base class to decompose in a built-in decomposition of a class type. 1290 /// This base class search is, unfortunately, not quite like any other that we 1291 /// perform anywhere else in C++. 1292 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1293 const CXXRecordDecl *RD, 1294 CXXCastPath &BasePath) { 1295 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1296 CXXBasePath &Path) { 1297 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1298 }; 1299 1300 const CXXRecordDecl *ClassWithFields = nullptr; 1301 AccessSpecifier AS = AS_public; 1302 if (RD->hasDirectFields()) 1303 // [dcl.decomp]p4: 1304 // Otherwise, all of E's non-static data members shall be public direct 1305 // members of E ... 1306 ClassWithFields = RD; 1307 else { 1308 // ... or of ... 1309 CXXBasePaths Paths; 1310 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1311 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1312 // If no classes have fields, just decompose RD itself. (This will work 1313 // if and only if zero bindings were provided.) 1314 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1315 } 1316 1317 CXXBasePath *BestPath = nullptr; 1318 for (auto &P : Paths) { 1319 if (!BestPath) 1320 BestPath = &P; 1321 else if (!S.Context.hasSameType(P.back().Base->getType(), 1322 BestPath->back().Base->getType())) { 1323 // ... the same ... 1324 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1325 << false << RD << BestPath->back().Base->getType() 1326 << P.back().Base->getType(); 1327 return DeclAccessPair(); 1328 } else if (P.Access < BestPath->Access) { 1329 BestPath = &P; 1330 } 1331 } 1332 1333 // ... unambiguous ... 1334 QualType BaseType = BestPath->back().Base->getType(); 1335 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1336 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1337 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1338 return DeclAccessPair(); 1339 } 1340 1341 // ... [accessible, implied by other rules] base class of E. 1342 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1343 *BestPath, diag::err_decomp_decl_inaccessible_base); 1344 AS = BestPath->Access; 1345 1346 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1347 S.BuildBasePathArray(Paths, BasePath); 1348 } 1349 1350 // The above search did not check whether the selected class itself has base 1351 // classes with fields, so check that now. 1352 CXXBasePaths Paths; 1353 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1354 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1355 << (ClassWithFields == RD) << RD << ClassWithFields 1356 << Paths.front().back().Base->getType(); 1357 return DeclAccessPair(); 1358 } 1359 1360 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1361 } 1362 1363 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1364 ValueDecl *Src, QualType DecompType, 1365 const CXXRecordDecl *OrigRD) { 1366 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1367 diag::err_incomplete_type)) 1368 return true; 1369 1370 CXXCastPath BasePath; 1371 DeclAccessPair BasePair = 1372 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1373 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1374 if (!RD) 1375 return true; 1376 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1377 DecompType.getQualifiers()); 1378 1379 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1380 unsigned NumFields = 1381 std::count_if(RD->field_begin(), RD->field_end(), 1382 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1383 assert(Bindings.size() != NumFields); 1384 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1385 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1386 << (NumFields < Bindings.size()); 1387 return true; 1388 }; 1389 1390 // all of E's non-static data members shall be [...] well-formed 1391 // when named as e.name in the context of the structured binding, 1392 // E shall not have an anonymous union member, ... 1393 unsigned I = 0; 1394 for (auto *FD : RD->fields()) { 1395 if (FD->isUnnamedBitfield()) 1396 continue; 1397 1398 // All the non-static data members are required to be nameable, so they 1399 // must all have names. 1400 if (!FD->getDeclName()) { 1401 if (RD->isLambda()) { 1402 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1403 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1404 return true; 1405 } 1406 1407 if (FD->isAnonymousStructOrUnion()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1409 << DecompType << FD->getType()->isUnionType(); 1410 S.Diag(FD->getLocation(), diag::note_declared_at); 1411 return true; 1412 } 1413 1414 // FIXME: Are there any other ways we could have an anonymous member? 1415 } 1416 1417 // We have a real field to bind. 1418 if (I >= Bindings.size()) 1419 return DiagnoseBadNumberOfBindings(); 1420 auto *B = Bindings[I++]; 1421 SourceLocation Loc = B->getLocation(); 1422 1423 // The field must be accessible in the context of the structured binding. 1424 // We already checked that the base class is accessible. 1425 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1426 // const_cast here. 1427 S.CheckStructuredBindingMemberAccess( 1428 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1429 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1430 BasePair.getAccess(), FD->getAccess()))); 1431 1432 // Initialize the binding to Src.FD. 1433 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1434 if (E.isInvalid()) 1435 return true; 1436 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1437 VK_LValue, &BasePath); 1438 if (E.isInvalid()) 1439 return true; 1440 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1441 CXXScopeSpec(), FD, 1442 DeclAccessPair::make(FD, FD->getAccess()), 1443 DeclarationNameInfo(FD->getDeclName(), Loc)); 1444 if (E.isInvalid()) 1445 return true; 1446 1447 // If the type of the member is T, the referenced type is cv T, where cv is 1448 // the cv-qualification of the decomposition expression. 1449 // 1450 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1451 // 'const' to the type of the field. 1452 Qualifiers Q = DecompType.getQualifiers(); 1453 if (FD->isMutable()) 1454 Q.removeConst(); 1455 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1456 } 1457 1458 if (I != Bindings.size()) 1459 return DiagnoseBadNumberOfBindings(); 1460 1461 return false; 1462 } 1463 1464 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1465 QualType DecompType = DD->getType(); 1466 1467 // If the type of the decomposition is dependent, then so is the type of 1468 // each binding. 1469 if (DecompType->isDependentType()) { 1470 for (auto *B : DD->bindings()) 1471 B->setType(Context.DependentTy); 1472 return; 1473 } 1474 1475 DecompType = DecompType.getNonReferenceType(); 1476 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1477 1478 // C++1z [dcl.decomp]/2: 1479 // If E is an array type [...] 1480 // As an extension, we also support decomposition of built-in complex and 1481 // vector types. 1482 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1483 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1484 DD->setInvalidDecl(); 1485 return; 1486 } 1487 if (auto *VT = DecompType->getAs<VectorType>()) { 1488 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1489 DD->setInvalidDecl(); 1490 return; 1491 } 1492 if (auto *CT = DecompType->getAs<ComplexType>()) { 1493 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1494 DD->setInvalidDecl(); 1495 return; 1496 } 1497 1498 // C++1z [dcl.decomp]/3: 1499 // if the expression std::tuple_size<E>::value is a well-formed integral 1500 // constant expression, [...] 1501 llvm::APSInt TupleSize(32); 1502 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1503 case IsTupleLike::Error: 1504 DD->setInvalidDecl(); 1505 return; 1506 1507 case IsTupleLike::TupleLike: 1508 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1509 DD->setInvalidDecl(); 1510 return; 1511 1512 case IsTupleLike::NotTupleLike: 1513 break; 1514 } 1515 1516 // C++1z [dcl.dcl]/8: 1517 // [E shall be of array or non-union class type] 1518 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1519 if (!RD || RD->isUnion()) { 1520 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1521 << DD << !RD << DecompType; 1522 DD->setInvalidDecl(); 1523 return; 1524 } 1525 1526 // C++1z [dcl.decomp]/4: 1527 // all of E's non-static data members shall be [...] direct members of 1528 // E or of the same unambiguous public base class of E, ... 1529 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1530 DD->setInvalidDecl(); 1531 } 1532 1533 /// Merge the exception specifications of two variable declarations. 1534 /// 1535 /// This is called when there's a redeclaration of a VarDecl. The function 1536 /// checks if the redeclaration might have an exception specification and 1537 /// validates compatibility and merges the specs if necessary. 1538 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1539 // Shortcut if exceptions are disabled. 1540 if (!getLangOpts().CXXExceptions) 1541 return; 1542 1543 assert(Context.hasSameType(New->getType(), Old->getType()) && 1544 "Should only be called if types are otherwise the same."); 1545 1546 QualType NewType = New->getType(); 1547 QualType OldType = Old->getType(); 1548 1549 // We're only interested in pointers and references to functions, as well 1550 // as pointers to member functions. 1551 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1552 NewType = R->getPointeeType(); 1553 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1554 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1555 NewType = P->getPointeeType(); 1556 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1557 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1558 NewType = M->getPointeeType(); 1559 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1560 } 1561 1562 if (!NewType->isFunctionProtoType()) 1563 return; 1564 1565 // There's lots of special cases for functions. For function pointers, system 1566 // libraries are hopefully not as broken so that we don't need these 1567 // workarounds. 1568 if (CheckEquivalentExceptionSpec( 1569 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1570 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1571 New->setInvalidDecl(); 1572 } 1573 } 1574 1575 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1576 /// function declaration are well-formed according to C++ 1577 /// [dcl.fct.default]. 1578 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1579 unsigned NumParams = FD->getNumParams(); 1580 unsigned ParamIdx = 0; 1581 1582 // This checking doesn't make sense for explicit specializations; their 1583 // default arguments are determined by the declaration we're specializing, 1584 // not by FD. 1585 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1586 return; 1587 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1588 if (FTD->isMemberSpecialization()) 1589 return; 1590 1591 // Find first parameter with a default argument 1592 for (; ParamIdx < NumParams; ++ParamIdx) { 1593 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1594 if (Param->hasDefaultArg()) 1595 break; 1596 } 1597 1598 // C++20 [dcl.fct.default]p4: 1599 // In a given function declaration, each parameter subsequent to a parameter 1600 // with a default argument shall have a default argument supplied in this or 1601 // a previous declaration, unless the parameter was expanded from a 1602 // parameter pack, or shall be a function parameter pack. 1603 for (; ParamIdx < NumParams; ++ParamIdx) { 1604 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1605 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1606 !(CurrentInstantiationScope && 1607 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1608 if (Param->isInvalidDecl()) 1609 /* We already complained about this parameter. */; 1610 else if (Param->getIdentifier()) 1611 Diag(Param->getLocation(), 1612 diag::err_param_default_argument_missing_name) 1613 << Param->getIdentifier(); 1614 else 1615 Diag(Param->getLocation(), 1616 diag::err_param_default_argument_missing); 1617 } 1618 } 1619 } 1620 1621 /// Check that the given type is a literal type. Issue a diagnostic if not, 1622 /// if Kind is Diagnose. 1623 /// \return \c true if a problem has been found (and optionally diagnosed). 1624 template <typename... Ts> 1625 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1626 SourceLocation Loc, QualType T, unsigned DiagID, 1627 Ts &&...DiagArgs) { 1628 if (T->isDependentType()) 1629 return false; 1630 1631 switch (Kind) { 1632 case Sema::CheckConstexprKind::Diagnose: 1633 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1634 std::forward<Ts>(DiagArgs)...); 1635 1636 case Sema::CheckConstexprKind::CheckValid: 1637 return !T->isLiteralType(SemaRef.Context); 1638 } 1639 1640 llvm_unreachable("unknown CheckConstexprKind"); 1641 } 1642 1643 /// Determine whether a destructor cannot be constexpr due to 1644 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1645 const CXXDestructorDecl *DD, 1646 Sema::CheckConstexprKind Kind) { 1647 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1648 const CXXRecordDecl *RD = 1649 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1650 if (!RD || RD->hasConstexprDestructor()) 1651 return true; 1652 1653 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1654 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1655 << static_cast<int>(DD->getConstexprKind()) << !FD 1656 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1657 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1658 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1659 } 1660 return false; 1661 }; 1662 1663 const CXXRecordDecl *RD = DD->getParent(); 1664 for (const CXXBaseSpecifier &B : RD->bases()) 1665 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1666 return false; 1667 for (const FieldDecl *FD : RD->fields()) 1668 if (!Check(FD->getLocation(), FD->getType(), FD)) 1669 return false; 1670 return true; 1671 } 1672 1673 /// Check whether a function's parameter types are all literal types. If so, 1674 /// return true. If not, produce a suitable diagnostic and return false. 1675 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1676 const FunctionDecl *FD, 1677 Sema::CheckConstexprKind Kind) { 1678 unsigned ArgIndex = 0; 1679 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1680 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1681 e = FT->param_type_end(); 1682 i != e; ++i, ++ArgIndex) { 1683 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1684 SourceLocation ParamLoc = PD->getLocation(); 1685 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1686 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1687 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1688 FD->isConsteval())) 1689 return false; 1690 } 1691 return true; 1692 } 1693 1694 /// Check whether a function's return type is a literal type. If so, return 1695 /// true. If not, produce a suitable diagnostic and return false. 1696 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1697 Sema::CheckConstexprKind Kind) { 1698 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1699 diag::err_constexpr_non_literal_return, 1700 FD->isConsteval())) 1701 return false; 1702 return true; 1703 } 1704 1705 /// Get diagnostic %select index for tag kind for 1706 /// record diagnostic message. 1707 /// WARNING: Indexes apply to particular diagnostics only! 1708 /// 1709 /// \returns diagnostic %select index. 1710 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1711 switch (Tag) { 1712 case TTK_Struct: return 0; 1713 case TTK_Interface: return 1; 1714 case TTK_Class: return 2; 1715 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1716 } 1717 } 1718 1719 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1720 Stmt *Body, 1721 Sema::CheckConstexprKind Kind); 1722 1723 // Check whether a function declaration satisfies the requirements of a 1724 // constexpr function definition or a constexpr constructor definition. If so, 1725 // return true. If not, produce appropriate diagnostics (unless asked not to by 1726 // Kind) and return false. 1727 // 1728 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1729 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1730 CheckConstexprKind Kind) { 1731 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1732 if (MD && MD->isInstance()) { 1733 // C++11 [dcl.constexpr]p4: 1734 // The definition of a constexpr constructor shall satisfy the following 1735 // constraints: 1736 // - the class shall not have any virtual base classes; 1737 // 1738 // FIXME: This only applies to constructors and destructors, not arbitrary 1739 // member functions. 1740 const CXXRecordDecl *RD = MD->getParent(); 1741 if (RD->getNumVBases()) { 1742 if (Kind == CheckConstexprKind::CheckValid) 1743 return false; 1744 1745 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1746 << isa<CXXConstructorDecl>(NewFD) 1747 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1748 for (const auto &I : RD->vbases()) 1749 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1750 << I.getSourceRange(); 1751 return false; 1752 } 1753 } 1754 1755 if (!isa<CXXConstructorDecl>(NewFD)) { 1756 // C++11 [dcl.constexpr]p3: 1757 // The definition of a constexpr function shall satisfy the following 1758 // constraints: 1759 // - it shall not be virtual; (removed in C++20) 1760 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1761 if (Method && Method->isVirtual()) { 1762 if (getLangOpts().CPlusPlus20) { 1763 if (Kind == CheckConstexprKind::Diagnose) 1764 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1765 } else { 1766 if (Kind == CheckConstexprKind::CheckValid) 1767 return false; 1768 1769 Method = Method->getCanonicalDecl(); 1770 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1771 1772 // If it's not obvious why this function is virtual, find an overridden 1773 // function which uses the 'virtual' keyword. 1774 const CXXMethodDecl *WrittenVirtual = Method; 1775 while (!WrittenVirtual->isVirtualAsWritten()) 1776 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1777 if (WrittenVirtual != Method) 1778 Diag(WrittenVirtual->getLocation(), 1779 diag::note_overridden_virtual_function); 1780 return false; 1781 } 1782 } 1783 1784 // - its return type shall be a literal type; 1785 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1786 return false; 1787 } 1788 1789 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1790 // A destructor can be constexpr only if the defaulted destructor could be; 1791 // we don't need to check the members and bases if we already know they all 1792 // have constexpr destructors. 1793 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1794 if (Kind == CheckConstexprKind::CheckValid) 1795 return false; 1796 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1797 return false; 1798 } 1799 } 1800 1801 // - each of its parameter types shall be a literal type; 1802 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1803 return false; 1804 1805 Stmt *Body = NewFD->getBody(); 1806 assert(Body && 1807 "CheckConstexprFunctionDefinition called on function with no body"); 1808 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1809 } 1810 1811 /// Check the given declaration statement is legal within a constexpr function 1812 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1813 /// 1814 /// \return true if the body is OK (maybe only as an extension), false if we 1815 /// have diagnosed a problem. 1816 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1817 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1818 Sema::CheckConstexprKind Kind) { 1819 // C++11 [dcl.constexpr]p3 and p4: 1820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1821 // contain only 1822 for (const auto *DclIt : DS->decls()) { 1823 switch (DclIt->getKind()) { 1824 case Decl::StaticAssert: 1825 case Decl::Using: 1826 case Decl::UsingShadow: 1827 case Decl::UsingDirective: 1828 case Decl::UnresolvedUsingTypename: 1829 case Decl::UnresolvedUsingValue: 1830 // - static_assert-declarations 1831 // - using-declarations, 1832 // - using-directives, 1833 continue; 1834 1835 case Decl::Typedef: 1836 case Decl::TypeAlias: { 1837 // - typedef declarations and alias-declarations that do not define 1838 // classes or enumerations, 1839 const auto *TN = cast<TypedefNameDecl>(DclIt); 1840 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1841 // Don't allow variably-modified types in constexpr functions. 1842 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1843 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1844 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1845 << TL.getSourceRange() << TL.getType() 1846 << isa<CXXConstructorDecl>(Dcl); 1847 } 1848 return false; 1849 } 1850 continue; 1851 } 1852 1853 case Decl::Enum: 1854 case Decl::CXXRecord: 1855 // C++1y allows types to be defined, not just declared. 1856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1857 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1858 SemaRef.Diag(DS->getBeginLoc(), 1859 SemaRef.getLangOpts().CPlusPlus14 1860 ? diag::warn_cxx11_compat_constexpr_type_definition 1861 : diag::ext_constexpr_type_definition) 1862 << isa<CXXConstructorDecl>(Dcl); 1863 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1864 return false; 1865 } 1866 } 1867 continue; 1868 1869 case Decl::EnumConstant: 1870 case Decl::IndirectField: 1871 case Decl::ParmVar: 1872 // These can only appear with other declarations which are banned in 1873 // C++11 and permitted in C++1y, so ignore them. 1874 continue; 1875 1876 case Decl::Var: 1877 case Decl::Decomposition: { 1878 // C++1y [dcl.constexpr]p3 allows anything except: 1879 // a definition of a variable of non-literal type or of static or 1880 // thread storage duration or [before C++2a] for which no 1881 // initialization is performed. 1882 const auto *VD = cast<VarDecl>(DclIt); 1883 if (VD->isThisDeclarationADefinition()) { 1884 if (VD->isStaticLocal()) { 1885 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1886 SemaRef.Diag(VD->getLocation(), 1887 diag::err_constexpr_local_var_static) 1888 << isa<CXXConstructorDecl>(Dcl) 1889 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1890 } 1891 return false; 1892 } 1893 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1894 diag::err_constexpr_local_var_non_literal_type, 1895 isa<CXXConstructorDecl>(Dcl))) 1896 return false; 1897 if (!VD->getType()->isDependentType() && 1898 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1899 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1900 SemaRef.Diag( 1901 VD->getLocation(), 1902 SemaRef.getLangOpts().CPlusPlus20 1903 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1904 : diag::ext_constexpr_local_var_no_init) 1905 << isa<CXXConstructorDecl>(Dcl); 1906 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1907 return false; 1908 } 1909 continue; 1910 } 1911 } 1912 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1913 SemaRef.Diag(VD->getLocation(), 1914 SemaRef.getLangOpts().CPlusPlus14 1915 ? diag::warn_cxx11_compat_constexpr_local_var 1916 : diag::ext_constexpr_local_var) 1917 << isa<CXXConstructorDecl>(Dcl); 1918 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1919 return false; 1920 } 1921 continue; 1922 } 1923 1924 case Decl::NamespaceAlias: 1925 case Decl::Function: 1926 // These are disallowed in C++11 and permitted in C++1y. Allow them 1927 // everywhere as an extension. 1928 if (!Cxx1yLoc.isValid()) 1929 Cxx1yLoc = DS->getBeginLoc(); 1930 continue; 1931 1932 default: 1933 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1934 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1935 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1936 } 1937 return false; 1938 } 1939 } 1940 1941 return true; 1942 } 1943 1944 /// Check that the given field is initialized within a constexpr constructor. 1945 /// 1946 /// \param Dcl The constexpr constructor being checked. 1947 /// \param Field The field being checked. This may be a member of an anonymous 1948 /// struct or union nested within the class being checked. 1949 /// \param Inits All declarations, including anonymous struct/union members and 1950 /// indirect members, for which any initialization was provided. 1951 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1952 /// multiple notes for different members to the same error. 1953 /// \param Kind Whether we're diagnosing a constructor as written or determining 1954 /// whether the formal requirements are satisfied. 1955 /// \return \c false if we're checking for validity and the constructor does 1956 /// not satisfy the requirements on a constexpr constructor. 1957 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1958 const FunctionDecl *Dcl, 1959 FieldDecl *Field, 1960 llvm::SmallSet<Decl*, 16> &Inits, 1961 bool &Diagnosed, 1962 Sema::CheckConstexprKind Kind) { 1963 // In C++20 onwards, there's nothing to check for validity. 1964 if (Kind == Sema::CheckConstexprKind::CheckValid && 1965 SemaRef.getLangOpts().CPlusPlus20) 1966 return true; 1967 1968 if (Field->isInvalidDecl()) 1969 return true; 1970 1971 if (Field->isUnnamedBitfield()) 1972 return true; 1973 1974 // Anonymous unions with no variant members and empty anonymous structs do not 1975 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1976 // indirect fields don't need initializing. 1977 if (Field->isAnonymousStructOrUnion() && 1978 (Field->getType()->isUnionType() 1979 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1980 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1981 return true; 1982 1983 if (!Inits.count(Field)) { 1984 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1985 if (!Diagnosed) { 1986 SemaRef.Diag(Dcl->getLocation(), 1987 SemaRef.getLangOpts().CPlusPlus20 1988 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1989 : diag::ext_constexpr_ctor_missing_init); 1990 Diagnosed = true; 1991 } 1992 SemaRef.Diag(Field->getLocation(), 1993 diag::note_constexpr_ctor_missing_init); 1994 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1995 return false; 1996 } 1997 } else if (Field->isAnonymousStructOrUnion()) { 1998 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1999 for (auto *I : RD->fields()) 2000 // If an anonymous union contains an anonymous struct of which any member 2001 // is initialized, all members must be initialized. 2002 if (!RD->isUnion() || Inits.count(I)) 2003 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2004 Kind)) 2005 return false; 2006 } 2007 return true; 2008 } 2009 2010 /// Check the provided statement is allowed in a constexpr function 2011 /// definition. 2012 static bool 2013 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2014 SmallVectorImpl<SourceLocation> &ReturnStmts, 2015 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2016 Sema::CheckConstexprKind Kind) { 2017 // - its function-body shall be [...] a compound-statement that contains only 2018 switch (S->getStmtClass()) { 2019 case Stmt::NullStmtClass: 2020 // - null statements, 2021 return true; 2022 2023 case Stmt::DeclStmtClass: 2024 // - static_assert-declarations 2025 // - using-declarations, 2026 // - using-directives, 2027 // - typedef declarations and alias-declarations that do not define 2028 // classes or enumerations, 2029 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2030 return false; 2031 return true; 2032 2033 case Stmt::ReturnStmtClass: 2034 // - and exactly one return statement; 2035 if (isa<CXXConstructorDecl>(Dcl)) { 2036 // C++1y allows return statements in constexpr constructors. 2037 if (!Cxx1yLoc.isValid()) 2038 Cxx1yLoc = S->getBeginLoc(); 2039 return true; 2040 } 2041 2042 ReturnStmts.push_back(S->getBeginLoc()); 2043 return true; 2044 2045 case Stmt::CompoundStmtClass: { 2046 // C++1y allows compound-statements. 2047 if (!Cxx1yLoc.isValid()) 2048 Cxx1yLoc = S->getBeginLoc(); 2049 2050 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2051 for (auto *BodyIt : CompStmt->body()) { 2052 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2053 Cxx1yLoc, Cxx2aLoc, Kind)) 2054 return false; 2055 } 2056 return true; 2057 } 2058 2059 case Stmt::AttributedStmtClass: 2060 if (!Cxx1yLoc.isValid()) 2061 Cxx1yLoc = S->getBeginLoc(); 2062 return true; 2063 2064 case Stmt::IfStmtClass: { 2065 // C++1y allows if-statements. 2066 if (!Cxx1yLoc.isValid()) 2067 Cxx1yLoc = S->getBeginLoc(); 2068 2069 IfStmt *If = cast<IfStmt>(S); 2070 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2071 Cxx1yLoc, Cxx2aLoc, Kind)) 2072 return false; 2073 if (If->getElse() && 2074 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2075 Cxx1yLoc, Cxx2aLoc, Kind)) 2076 return false; 2077 return true; 2078 } 2079 2080 case Stmt::WhileStmtClass: 2081 case Stmt::DoStmtClass: 2082 case Stmt::ForStmtClass: 2083 case Stmt::CXXForRangeStmtClass: 2084 case Stmt::ContinueStmtClass: 2085 // C++1y allows all of these. We don't allow them as extensions in C++11, 2086 // because they don't make sense without variable mutation. 2087 if (!SemaRef.getLangOpts().CPlusPlus14) 2088 break; 2089 if (!Cxx1yLoc.isValid()) 2090 Cxx1yLoc = S->getBeginLoc(); 2091 for (Stmt *SubStmt : S->children()) 2092 if (SubStmt && 2093 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2094 Cxx1yLoc, Cxx2aLoc, Kind)) 2095 return false; 2096 return true; 2097 2098 case Stmt::SwitchStmtClass: 2099 case Stmt::CaseStmtClass: 2100 case Stmt::DefaultStmtClass: 2101 case Stmt::BreakStmtClass: 2102 // C++1y allows switch-statements, and since they don't need variable 2103 // mutation, we can reasonably allow them in C++11 as an extension. 2104 if (!Cxx1yLoc.isValid()) 2105 Cxx1yLoc = S->getBeginLoc(); 2106 for (Stmt *SubStmt : S->children()) 2107 if (SubStmt && 2108 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2109 Cxx1yLoc, Cxx2aLoc, Kind)) 2110 return false; 2111 return true; 2112 2113 case Stmt::GCCAsmStmtClass: 2114 case Stmt::MSAsmStmtClass: 2115 // C++2a allows inline assembly statements. 2116 case Stmt::CXXTryStmtClass: 2117 if (Cxx2aLoc.isInvalid()) 2118 Cxx2aLoc = S->getBeginLoc(); 2119 for (Stmt *SubStmt : S->children()) { 2120 if (SubStmt && 2121 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2122 Cxx1yLoc, Cxx2aLoc, Kind)) 2123 return false; 2124 } 2125 return true; 2126 2127 case Stmt::CXXCatchStmtClass: 2128 // Do not bother checking the language mode (already covered by the 2129 // try block check). 2130 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2131 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2132 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2133 return false; 2134 return true; 2135 2136 default: 2137 if (!isa<Expr>(S)) 2138 break; 2139 2140 // C++1y allows expression-statements. 2141 if (!Cxx1yLoc.isValid()) 2142 Cxx1yLoc = S->getBeginLoc(); 2143 return true; 2144 } 2145 2146 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2147 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2148 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2149 } 2150 return false; 2151 } 2152 2153 /// Check the body for the given constexpr function declaration only contains 2154 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2155 /// 2156 /// \return true if the body is OK, false if we have found or diagnosed a 2157 /// problem. 2158 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2159 Stmt *Body, 2160 Sema::CheckConstexprKind Kind) { 2161 SmallVector<SourceLocation, 4> ReturnStmts; 2162 2163 if (isa<CXXTryStmt>(Body)) { 2164 // C++11 [dcl.constexpr]p3: 2165 // The definition of a constexpr function shall satisfy the following 2166 // constraints: [...] 2167 // - its function-body shall be = delete, = default, or a 2168 // compound-statement 2169 // 2170 // C++11 [dcl.constexpr]p4: 2171 // In the definition of a constexpr constructor, [...] 2172 // - its function-body shall not be a function-try-block; 2173 // 2174 // This restriction is lifted in C++2a, as long as inner statements also 2175 // apply the general constexpr rules. 2176 switch (Kind) { 2177 case Sema::CheckConstexprKind::CheckValid: 2178 if (!SemaRef.getLangOpts().CPlusPlus20) 2179 return false; 2180 break; 2181 2182 case Sema::CheckConstexprKind::Diagnose: 2183 SemaRef.Diag(Body->getBeginLoc(), 2184 !SemaRef.getLangOpts().CPlusPlus20 2185 ? diag::ext_constexpr_function_try_block_cxx20 2186 : diag::warn_cxx17_compat_constexpr_function_try_block) 2187 << isa<CXXConstructorDecl>(Dcl); 2188 break; 2189 } 2190 } 2191 2192 // - its function-body shall be [...] a compound-statement that contains only 2193 // [... list of cases ...] 2194 // 2195 // Note that walking the children here is enough to properly check for 2196 // CompoundStmt and CXXTryStmt body. 2197 SourceLocation Cxx1yLoc, Cxx2aLoc; 2198 for (Stmt *SubStmt : Body->children()) { 2199 if (SubStmt && 2200 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2201 Cxx1yLoc, Cxx2aLoc, Kind)) 2202 return false; 2203 } 2204 2205 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2206 // If this is only valid as an extension, report that we don't satisfy the 2207 // constraints of the current language. 2208 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2209 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2210 return false; 2211 } else if (Cxx2aLoc.isValid()) { 2212 SemaRef.Diag(Cxx2aLoc, 2213 SemaRef.getLangOpts().CPlusPlus20 2214 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2215 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2216 << isa<CXXConstructorDecl>(Dcl); 2217 } else if (Cxx1yLoc.isValid()) { 2218 SemaRef.Diag(Cxx1yLoc, 2219 SemaRef.getLangOpts().CPlusPlus14 2220 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2221 : diag::ext_constexpr_body_invalid_stmt) 2222 << isa<CXXConstructorDecl>(Dcl); 2223 } 2224 2225 if (const CXXConstructorDecl *Constructor 2226 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2227 const CXXRecordDecl *RD = Constructor->getParent(); 2228 // DR1359: 2229 // - every non-variant non-static data member and base class sub-object 2230 // shall be initialized; 2231 // DR1460: 2232 // - if the class is a union having variant members, exactly one of them 2233 // shall be initialized; 2234 if (RD->isUnion()) { 2235 if (Constructor->getNumCtorInitializers() == 0 && 2236 RD->hasVariantMembers()) { 2237 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2238 SemaRef.Diag( 2239 Dcl->getLocation(), 2240 SemaRef.getLangOpts().CPlusPlus20 2241 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2242 : diag::ext_constexpr_union_ctor_no_init); 2243 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2244 return false; 2245 } 2246 } 2247 } else if (!Constructor->isDependentContext() && 2248 !Constructor->isDelegatingConstructor()) { 2249 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2250 2251 // Skip detailed checking if we have enough initializers, and we would 2252 // allow at most one initializer per member. 2253 bool AnyAnonStructUnionMembers = false; 2254 unsigned Fields = 0; 2255 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2256 E = RD->field_end(); I != E; ++I, ++Fields) { 2257 if (I->isAnonymousStructOrUnion()) { 2258 AnyAnonStructUnionMembers = true; 2259 break; 2260 } 2261 } 2262 // DR1460: 2263 // - if the class is a union-like class, but is not a union, for each of 2264 // its anonymous union members having variant members, exactly one of 2265 // them shall be initialized; 2266 if (AnyAnonStructUnionMembers || 2267 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2268 // Check initialization of non-static data members. Base classes are 2269 // always initialized so do not need to be checked. Dependent bases 2270 // might not have initializers in the member initializer list. 2271 llvm::SmallSet<Decl*, 16> Inits; 2272 for (const auto *I: Constructor->inits()) { 2273 if (FieldDecl *FD = I->getMember()) 2274 Inits.insert(FD); 2275 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2276 Inits.insert(ID->chain_begin(), ID->chain_end()); 2277 } 2278 2279 bool Diagnosed = false; 2280 for (auto *I : RD->fields()) 2281 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2282 Kind)) 2283 return false; 2284 } 2285 } 2286 } else { 2287 if (ReturnStmts.empty()) { 2288 // C++1y doesn't require constexpr functions to contain a 'return' 2289 // statement. We still do, unless the return type might be void, because 2290 // otherwise if there's no return statement, the function cannot 2291 // be used in a core constant expression. 2292 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2293 (Dcl->getReturnType()->isVoidType() || 2294 Dcl->getReturnType()->isDependentType()); 2295 switch (Kind) { 2296 case Sema::CheckConstexprKind::Diagnose: 2297 SemaRef.Diag(Dcl->getLocation(), 2298 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2299 : diag::err_constexpr_body_no_return) 2300 << Dcl->isConsteval(); 2301 if (!OK) 2302 return false; 2303 break; 2304 2305 case Sema::CheckConstexprKind::CheckValid: 2306 // The formal requirements don't include this rule in C++14, even 2307 // though the "must be able to produce a constant expression" rules 2308 // still imply it in some cases. 2309 if (!SemaRef.getLangOpts().CPlusPlus14) 2310 return false; 2311 break; 2312 } 2313 } else if (ReturnStmts.size() > 1) { 2314 switch (Kind) { 2315 case Sema::CheckConstexprKind::Diagnose: 2316 SemaRef.Diag( 2317 ReturnStmts.back(), 2318 SemaRef.getLangOpts().CPlusPlus14 2319 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2320 : diag::ext_constexpr_body_multiple_return); 2321 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2322 SemaRef.Diag(ReturnStmts[I], 2323 diag::note_constexpr_body_previous_return); 2324 break; 2325 2326 case Sema::CheckConstexprKind::CheckValid: 2327 if (!SemaRef.getLangOpts().CPlusPlus14) 2328 return false; 2329 break; 2330 } 2331 } 2332 } 2333 2334 // C++11 [dcl.constexpr]p5: 2335 // if no function argument values exist such that the function invocation 2336 // substitution would produce a constant expression, the program is 2337 // ill-formed; no diagnostic required. 2338 // C++11 [dcl.constexpr]p3: 2339 // - every constructor call and implicit conversion used in initializing the 2340 // return value shall be one of those allowed in a constant expression. 2341 // C++11 [dcl.constexpr]p4: 2342 // - every constructor involved in initializing non-static data members and 2343 // base class sub-objects shall be a constexpr constructor. 2344 // 2345 // Note that this rule is distinct from the "requirements for a constexpr 2346 // function", so is not checked in CheckValid mode. 2347 SmallVector<PartialDiagnosticAt, 8> Diags; 2348 if (Kind == Sema::CheckConstexprKind::Diagnose && 2349 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2350 SemaRef.Diag(Dcl->getLocation(), 2351 diag::ext_constexpr_function_never_constant_expr) 2352 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2353 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2354 SemaRef.Diag(Diags[I].first, Diags[I].second); 2355 // Don't return false here: we allow this for compatibility in 2356 // system headers. 2357 } 2358 2359 return true; 2360 } 2361 2362 /// Get the class that is directly named by the current context. This is the 2363 /// class for which an unqualified-id in this scope could name a constructor 2364 /// or destructor. 2365 /// 2366 /// If the scope specifier denotes a class, this will be that class. 2367 /// If the scope specifier is empty, this will be the class whose 2368 /// member-specification we are currently within. Otherwise, there 2369 /// is no such class. 2370 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2371 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2372 2373 if (SS && SS->isInvalid()) 2374 return nullptr; 2375 2376 if (SS && SS->isNotEmpty()) { 2377 DeclContext *DC = computeDeclContext(*SS, true); 2378 return dyn_cast_or_null<CXXRecordDecl>(DC); 2379 } 2380 2381 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2382 } 2383 2384 /// isCurrentClassName - Determine whether the identifier II is the 2385 /// name of the class type currently being defined. In the case of 2386 /// nested classes, this will only return true if II is the name of 2387 /// the innermost class. 2388 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2389 const CXXScopeSpec *SS) { 2390 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2391 return CurDecl && &II == CurDecl->getIdentifier(); 2392 } 2393 2394 /// Determine whether the identifier II is a typo for the name of 2395 /// the class type currently being defined. If so, update it to the identifier 2396 /// that should have been used. 2397 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2398 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2399 2400 if (!getLangOpts().SpellChecking) 2401 return false; 2402 2403 CXXRecordDecl *CurDecl; 2404 if (SS && SS->isSet() && !SS->isInvalid()) { 2405 DeclContext *DC = computeDeclContext(*SS, true); 2406 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2407 } else 2408 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2409 2410 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2411 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2412 < II->getLength()) { 2413 II = CurDecl->getIdentifier(); 2414 return true; 2415 } 2416 2417 return false; 2418 } 2419 2420 /// Determine whether the given class is a base class of the given 2421 /// class, including looking at dependent bases. 2422 static bool findCircularInheritance(const CXXRecordDecl *Class, 2423 const CXXRecordDecl *Current) { 2424 SmallVector<const CXXRecordDecl*, 8> Queue; 2425 2426 Class = Class->getCanonicalDecl(); 2427 while (true) { 2428 for (const auto &I : Current->bases()) { 2429 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2430 if (!Base) 2431 continue; 2432 2433 Base = Base->getDefinition(); 2434 if (!Base) 2435 continue; 2436 2437 if (Base->getCanonicalDecl() == Class) 2438 return true; 2439 2440 Queue.push_back(Base); 2441 } 2442 2443 if (Queue.empty()) 2444 return false; 2445 2446 Current = Queue.pop_back_val(); 2447 } 2448 2449 return false; 2450 } 2451 2452 /// Check the validity of a C++ base class specifier. 2453 /// 2454 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2455 /// and returns NULL otherwise. 2456 CXXBaseSpecifier * 2457 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2458 SourceRange SpecifierRange, 2459 bool Virtual, AccessSpecifier Access, 2460 TypeSourceInfo *TInfo, 2461 SourceLocation EllipsisLoc) { 2462 QualType BaseType = TInfo->getType(); 2463 if (BaseType->containsErrors()) { 2464 // Already emitted a diagnostic when parsing the error type. 2465 return nullptr; 2466 } 2467 // C++ [class.union]p1: 2468 // A union shall not have base classes. 2469 if (Class->isUnion()) { 2470 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2471 << SpecifierRange; 2472 return nullptr; 2473 } 2474 2475 if (EllipsisLoc.isValid() && 2476 !TInfo->getType()->containsUnexpandedParameterPack()) { 2477 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2478 << TInfo->getTypeLoc().getSourceRange(); 2479 EllipsisLoc = SourceLocation(); 2480 } 2481 2482 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2483 2484 if (BaseType->isDependentType()) { 2485 // Make sure that we don't have circular inheritance among our dependent 2486 // bases. For non-dependent bases, the check for completeness below handles 2487 // this. 2488 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2489 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2490 ((BaseDecl = BaseDecl->getDefinition()) && 2491 findCircularInheritance(Class, BaseDecl))) { 2492 Diag(BaseLoc, diag::err_circular_inheritance) 2493 << BaseType << Context.getTypeDeclType(Class); 2494 2495 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2496 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2497 << BaseType; 2498 2499 return nullptr; 2500 } 2501 } 2502 2503 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2504 Class->getTagKind() == TTK_Class, 2505 Access, TInfo, EllipsisLoc); 2506 } 2507 2508 // Base specifiers must be record types. 2509 if (!BaseType->isRecordType()) { 2510 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2511 return nullptr; 2512 } 2513 2514 // C++ [class.union]p1: 2515 // A union shall not be used as a base class. 2516 if (BaseType->isUnionType()) { 2517 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2518 return nullptr; 2519 } 2520 2521 // For the MS ABI, propagate DLL attributes to base class templates. 2522 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2523 if (Attr *ClassAttr = getDLLAttr(Class)) { 2524 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2525 BaseType->getAsCXXRecordDecl())) { 2526 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2527 BaseLoc); 2528 } 2529 } 2530 } 2531 2532 // C++ [class.derived]p2: 2533 // The class-name in a base-specifier shall not be an incompletely 2534 // defined class. 2535 if (RequireCompleteType(BaseLoc, BaseType, 2536 diag::err_incomplete_base_class, SpecifierRange)) { 2537 Class->setInvalidDecl(); 2538 return nullptr; 2539 } 2540 2541 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2542 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2543 assert(BaseDecl && "Record type has no declaration"); 2544 BaseDecl = BaseDecl->getDefinition(); 2545 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2546 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2547 assert(CXXBaseDecl && "Base type is not a C++ type"); 2548 2549 // Microsoft docs say: 2550 // "If a base-class has a code_seg attribute, derived classes must have the 2551 // same attribute." 2552 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2553 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2554 if ((DerivedCSA || BaseCSA) && 2555 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2556 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2557 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2558 << CXXBaseDecl; 2559 return nullptr; 2560 } 2561 2562 // A class which contains a flexible array member is not suitable for use as a 2563 // base class: 2564 // - If the layout determines that a base comes before another base, 2565 // the flexible array member would index into the subsequent base. 2566 // - If the layout determines that base comes before the derived class, 2567 // the flexible array member would index into the derived class. 2568 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2569 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2570 << CXXBaseDecl->getDeclName(); 2571 return nullptr; 2572 } 2573 2574 // C++ [class]p3: 2575 // If a class is marked final and it appears as a base-type-specifier in 2576 // base-clause, the program is ill-formed. 2577 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2578 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2579 << CXXBaseDecl->getDeclName() 2580 << FA->isSpelledAsSealed(); 2581 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2582 << CXXBaseDecl->getDeclName() << FA->getRange(); 2583 return nullptr; 2584 } 2585 2586 if (BaseDecl->isInvalidDecl()) 2587 Class->setInvalidDecl(); 2588 2589 // Create the base specifier. 2590 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2591 Class->getTagKind() == TTK_Class, 2592 Access, TInfo, EllipsisLoc); 2593 } 2594 2595 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2596 /// one entry in the base class list of a class specifier, for 2597 /// example: 2598 /// class foo : public bar, virtual private baz { 2599 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2600 BaseResult 2601 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2602 ParsedAttributes &Attributes, 2603 bool Virtual, AccessSpecifier Access, 2604 ParsedType basetype, SourceLocation BaseLoc, 2605 SourceLocation EllipsisLoc) { 2606 if (!classdecl) 2607 return true; 2608 2609 AdjustDeclIfTemplate(classdecl); 2610 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2611 if (!Class) 2612 return true; 2613 2614 // We haven't yet attached the base specifiers. 2615 Class->setIsParsingBaseSpecifiers(); 2616 2617 // We do not support any C++11 attributes on base-specifiers yet. 2618 // Diagnose any attributes we see. 2619 for (const ParsedAttr &AL : Attributes) { 2620 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2621 continue; 2622 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2623 ? (unsigned)diag::warn_unknown_attribute_ignored 2624 : (unsigned)diag::err_base_specifier_attribute) 2625 << AL << AL.getRange(); 2626 } 2627 2628 TypeSourceInfo *TInfo = nullptr; 2629 GetTypeFromParser(basetype, &TInfo); 2630 2631 if (EllipsisLoc.isInvalid() && 2632 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2633 UPPC_BaseType)) 2634 return true; 2635 2636 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2637 Virtual, Access, TInfo, 2638 EllipsisLoc)) 2639 return BaseSpec; 2640 else 2641 Class->setInvalidDecl(); 2642 2643 return true; 2644 } 2645 2646 /// Use small set to collect indirect bases. As this is only used 2647 /// locally, there's no need to abstract the small size parameter. 2648 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2649 2650 /// Recursively add the bases of Type. Don't add Type itself. 2651 static void 2652 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2653 const QualType &Type) 2654 { 2655 // Even though the incoming type is a base, it might not be 2656 // a class -- it could be a template parm, for instance. 2657 if (auto Rec = Type->getAs<RecordType>()) { 2658 auto Decl = Rec->getAsCXXRecordDecl(); 2659 2660 // Iterate over its bases. 2661 for (const auto &BaseSpec : Decl->bases()) { 2662 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2663 .getUnqualifiedType(); 2664 if (Set.insert(Base).second) 2665 // If we've not already seen it, recurse. 2666 NoteIndirectBases(Context, Set, Base); 2667 } 2668 } 2669 } 2670 2671 /// Performs the actual work of attaching the given base class 2672 /// specifiers to a C++ class. 2673 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2674 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2675 if (Bases.empty()) 2676 return false; 2677 2678 // Used to keep track of which base types we have already seen, so 2679 // that we can properly diagnose redundant direct base types. Note 2680 // that the key is always the unqualified canonical type of the base 2681 // class. 2682 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2683 2684 // Used to track indirect bases so we can see if a direct base is 2685 // ambiguous. 2686 IndirectBaseSet IndirectBaseTypes; 2687 2688 // Copy non-redundant base specifiers into permanent storage. 2689 unsigned NumGoodBases = 0; 2690 bool Invalid = false; 2691 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2692 QualType NewBaseType 2693 = Context.getCanonicalType(Bases[idx]->getType()); 2694 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2695 2696 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2697 if (KnownBase) { 2698 // C++ [class.mi]p3: 2699 // A class shall not be specified as a direct base class of a 2700 // derived class more than once. 2701 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2702 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2703 2704 // Delete the duplicate base class specifier; we're going to 2705 // overwrite its pointer later. 2706 Context.Deallocate(Bases[idx]); 2707 2708 Invalid = true; 2709 } else { 2710 // Okay, add this new base class. 2711 KnownBase = Bases[idx]; 2712 Bases[NumGoodBases++] = Bases[idx]; 2713 2714 // Note this base's direct & indirect bases, if there could be ambiguity. 2715 if (Bases.size() > 1) 2716 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2717 2718 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2719 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2720 if (Class->isInterface() && 2721 (!RD->isInterfaceLike() || 2722 KnownBase->getAccessSpecifier() != AS_public)) { 2723 // The Microsoft extension __interface does not permit bases that 2724 // are not themselves public interfaces. 2725 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2726 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2727 << RD->getSourceRange(); 2728 Invalid = true; 2729 } 2730 if (RD->hasAttr<WeakAttr>()) 2731 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2732 } 2733 } 2734 } 2735 2736 // Attach the remaining base class specifiers to the derived class. 2737 Class->setBases(Bases.data(), NumGoodBases); 2738 2739 // Check that the only base classes that are duplicate are virtual. 2740 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2741 // Check whether this direct base is inaccessible due to ambiguity. 2742 QualType BaseType = Bases[idx]->getType(); 2743 2744 // Skip all dependent types in templates being used as base specifiers. 2745 // Checks below assume that the base specifier is a CXXRecord. 2746 if (BaseType->isDependentType()) 2747 continue; 2748 2749 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2750 .getUnqualifiedType(); 2751 2752 if (IndirectBaseTypes.count(CanonicalBase)) { 2753 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2754 /*DetectVirtual=*/true); 2755 bool found 2756 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2757 assert(found); 2758 (void)found; 2759 2760 if (Paths.isAmbiguous(CanonicalBase)) 2761 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2762 << BaseType << getAmbiguousPathsDisplayString(Paths) 2763 << Bases[idx]->getSourceRange(); 2764 else 2765 assert(Bases[idx]->isVirtual()); 2766 } 2767 2768 // Delete the base class specifier, since its data has been copied 2769 // into the CXXRecordDecl. 2770 Context.Deallocate(Bases[idx]); 2771 } 2772 2773 return Invalid; 2774 } 2775 2776 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2777 /// class, after checking whether there are any duplicate base 2778 /// classes. 2779 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2780 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2781 if (!ClassDecl || Bases.empty()) 2782 return; 2783 2784 AdjustDeclIfTemplate(ClassDecl); 2785 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2786 } 2787 2788 /// Determine whether the type \p Derived is a C++ class that is 2789 /// derived from the type \p Base. 2790 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2791 if (!getLangOpts().CPlusPlus) 2792 return false; 2793 2794 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2795 if (!DerivedRD) 2796 return false; 2797 2798 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2799 if (!BaseRD) 2800 return false; 2801 2802 // If either the base or the derived type is invalid, don't try to 2803 // check whether one is derived from the other. 2804 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2805 return false; 2806 2807 // FIXME: In a modules build, do we need the entire path to be visible for us 2808 // to be able to use the inheritance relationship? 2809 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2810 return false; 2811 2812 return DerivedRD->isDerivedFrom(BaseRD); 2813 } 2814 2815 /// Determine whether the type \p Derived is a C++ class that is 2816 /// derived from the type \p Base. 2817 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2818 CXXBasePaths &Paths) { 2819 if (!getLangOpts().CPlusPlus) 2820 return false; 2821 2822 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2823 if (!DerivedRD) 2824 return false; 2825 2826 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2827 if (!BaseRD) 2828 return false; 2829 2830 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2831 return false; 2832 2833 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2834 } 2835 2836 static void BuildBasePathArray(const CXXBasePath &Path, 2837 CXXCastPath &BasePathArray) { 2838 // We first go backward and check if we have a virtual base. 2839 // FIXME: It would be better if CXXBasePath had the base specifier for 2840 // the nearest virtual base. 2841 unsigned Start = 0; 2842 for (unsigned I = Path.size(); I != 0; --I) { 2843 if (Path[I - 1].Base->isVirtual()) { 2844 Start = I - 1; 2845 break; 2846 } 2847 } 2848 2849 // Now add all bases. 2850 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2851 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2852 } 2853 2854 2855 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2856 CXXCastPath &BasePathArray) { 2857 assert(BasePathArray.empty() && "Base path array must be empty!"); 2858 assert(Paths.isRecordingPaths() && "Must record paths!"); 2859 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2860 } 2861 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2862 /// conversion (where Derived and Base are class types) is 2863 /// well-formed, meaning that the conversion is unambiguous (and 2864 /// that all of the base classes are accessible). Returns true 2865 /// and emits a diagnostic if the code is ill-formed, returns false 2866 /// otherwise. Loc is the location where this routine should point to 2867 /// if there is an error, and Range is the source range to highlight 2868 /// if there is an error. 2869 /// 2870 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2871 /// diagnostic for the respective type of error will be suppressed, but the 2872 /// check for ill-formed code will still be performed. 2873 bool 2874 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2875 unsigned InaccessibleBaseID, 2876 unsigned AmbiguousBaseConvID, 2877 SourceLocation Loc, SourceRange Range, 2878 DeclarationName Name, 2879 CXXCastPath *BasePath, 2880 bool IgnoreAccess) { 2881 // First, determine whether the path from Derived to Base is 2882 // ambiguous. This is slightly more expensive than checking whether 2883 // the Derived to Base conversion exists, because here we need to 2884 // explore multiple paths to determine if there is an ambiguity. 2885 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2886 /*DetectVirtual=*/false); 2887 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2888 if (!DerivationOkay) 2889 return true; 2890 2891 const CXXBasePath *Path = nullptr; 2892 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2893 Path = &Paths.front(); 2894 2895 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2896 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2897 // user to access such bases. 2898 if (!Path && getLangOpts().MSVCCompat) { 2899 for (const CXXBasePath &PossiblePath : Paths) { 2900 if (PossiblePath.size() == 1) { 2901 Path = &PossiblePath; 2902 if (AmbiguousBaseConvID) 2903 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2904 << Base << Derived << Range; 2905 break; 2906 } 2907 } 2908 } 2909 2910 if (Path) { 2911 if (!IgnoreAccess) { 2912 // Check that the base class can be accessed. 2913 switch ( 2914 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2915 case AR_inaccessible: 2916 return true; 2917 case AR_accessible: 2918 case AR_dependent: 2919 case AR_delayed: 2920 break; 2921 } 2922 } 2923 2924 // Build a base path if necessary. 2925 if (BasePath) 2926 ::BuildBasePathArray(*Path, *BasePath); 2927 return false; 2928 } 2929 2930 if (AmbiguousBaseConvID) { 2931 // We know that the derived-to-base conversion is ambiguous, and 2932 // we're going to produce a diagnostic. Perform the derived-to-base 2933 // search just one more time to compute all of the possible paths so 2934 // that we can print them out. This is more expensive than any of 2935 // the previous derived-to-base checks we've done, but at this point 2936 // performance isn't as much of an issue. 2937 Paths.clear(); 2938 Paths.setRecordingPaths(true); 2939 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2940 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2941 (void)StillOkay; 2942 2943 // Build up a textual representation of the ambiguous paths, e.g., 2944 // D -> B -> A, that will be used to illustrate the ambiguous 2945 // conversions in the diagnostic. We only print one of the paths 2946 // to each base class subobject. 2947 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2948 2949 Diag(Loc, AmbiguousBaseConvID) 2950 << Derived << Base << PathDisplayStr << Range << Name; 2951 } 2952 return true; 2953 } 2954 2955 bool 2956 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2957 SourceLocation Loc, SourceRange Range, 2958 CXXCastPath *BasePath, 2959 bool IgnoreAccess) { 2960 return CheckDerivedToBaseConversion( 2961 Derived, Base, diag::err_upcast_to_inaccessible_base, 2962 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2963 BasePath, IgnoreAccess); 2964 } 2965 2966 2967 /// Builds a string representing ambiguous paths from a 2968 /// specific derived class to different subobjects of the same base 2969 /// class. 2970 /// 2971 /// This function builds a string that can be used in error messages 2972 /// to show the different paths that one can take through the 2973 /// inheritance hierarchy to go from the derived class to different 2974 /// subobjects of a base class. The result looks something like this: 2975 /// @code 2976 /// struct D -> struct B -> struct A 2977 /// struct D -> struct C -> struct A 2978 /// @endcode 2979 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2980 std::string PathDisplayStr; 2981 std::set<unsigned> DisplayedPaths; 2982 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2983 Path != Paths.end(); ++Path) { 2984 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2985 // We haven't displayed a path to this particular base 2986 // class subobject yet. 2987 PathDisplayStr += "\n "; 2988 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2989 for (CXXBasePath::const_iterator Element = Path->begin(); 2990 Element != Path->end(); ++Element) 2991 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2992 } 2993 } 2994 2995 return PathDisplayStr; 2996 } 2997 2998 //===----------------------------------------------------------------------===// 2999 // C++ class member Handling 3000 //===----------------------------------------------------------------------===// 3001 3002 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3003 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3004 SourceLocation ColonLoc, 3005 const ParsedAttributesView &Attrs) { 3006 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3007 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3008 ASLoc, ColonLoc); 3009 CurContext->addHiddenDecl(ASDecl); 3010 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3011 } 3012 3013 /// CheckOverrideControl - Check C++11 override control semantics. 3014 void Sema::CheckOverrideControl(NamedDecl *D) { 3015 if (D->isInvalidDecl()) 3016 return; 3017 3018 // We only care about "override" and "final" declarations. 3019 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3020 return; 3021 3022 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3023 3024 // We can't check dependent instance methods. 3025 if (MD && MD->isInstance() && 3026 (MD->getParent()->hasAnyDependentBases() || 3027 MD->getType()->isDependentType())) 3028 return; 3029 3030 if (MD && !MD->isVirtual()) { 3031 // If we have a non-virtual method, check if if hides a virtual method. 3032 // (In that case, it's most likely the method has the wrong type.) 3033 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3034 FindHiddenVirtualMethods(MD, OverloadedMethods); 3035 3036 if (!OverloadedMethods.empty()) { 3037 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3038 Diag(OA->getLocation(), 3039 diag::override_keyword_hides_virtual_member_function) 3040 << "override" << (OverloadedMethods.size() > 1); 3041 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3042 Diag(FA->getLocation(), 3043 diag::override_keyword_hides_virtual_member_function) 3044 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3045 << (OverloadedMethods.size() > 1); 3046 } 3047 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3048 MD->setInvalidDecl(); 3049 return; 3050 } 3051 // Fall through into the general case diagnostic. 3052 // FIXME: We might want to attempt typo correction here. 3053 } 3054 3055 if (!MD || !MD->isVirtual()) { 3056 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3057 Diag(OA->getLocation(), 3058 diag::override_keyword_only_allowed_on_virtual_member_functions) 3059 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3060 D->dropAttr<OverrideAttr>(); 3061 } 3062 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3063 Diag(FA->getLocation(), 3064 diag::override_keyword_only_allowed_on_virtual_member_functions) 3065 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3066 << FixItHint::CreateRemoval(FA->getLocation()); 3067 D->dropAttr<FinalAttr>(); 3068 } 3069 return; 3070 } 3071 3072 // C++11 [class.virtual]p5: 3073 // If a function is marked with the virt-specifier override and 3074 // does not override a member function of a base class, the program is 3075 // ill-formed. 3076 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3077 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3078 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3079 << MD->getDeclName(); 3080 } 3081 3082 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3083 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3084 return; 3085 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3086 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3087 return; 3088 3089 SourceLocation Loc = MD->getLocation(); 3090 SourceLocation SpellingLoc = Loc; 3091 if (getSourceManager().isMacroArgExpansion(Loc)) 3092 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3093 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3094 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3095 return; 3096 3097 if (MD->size_overridden_methods() > 0) { 3098 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3099 unsigned DiagID = 3100 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3101 ? DiagInconsistent 3102 : DiagSuggest; 3103 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3104 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3105 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3106 }; 3107 if (isa<CXXDestructorDecl>(MD)) 3108 EmitDiag( 3109 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3110 diag::warn_suggest_destructor_marked_not_override_overriding); 3111 else 3112 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3113 diag::warn_suggest_function_marked_not_override_overriding); 3114 } 3115 } 3116 3117 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3118 /// function overrides a virtual member function marked 'final', according to 3119 /// C++11 [class.virtual]p4. 3120 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3121 const CXXMethodDecl *Old) { 3122 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3123 if (!FA) 3124 return false; 3125 3126 Diag(New->getLocation(), diag::err_final_function_overridden) 3127 << New->getDeclName() 3128 << FA->isSpelledAsSealed(); 3129 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3130 return true; 3131 } 3132 3133 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3134 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3135 // FIXME: Destruction of ObjC lifetime types has side-effects. 3136 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3137 return !RD->isCompleteDefinition() || 3138 !RD->hasTrivialDefaultConstructor() || 3139 !RD->hasTrivialDestructor(); 3140 return false; 3141 } 3142 3143 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3144 ParsedAttributesView::const_iterator Itr = 3145 llvm::find_if(list, [](const ParsedAttr &AL) { 3146 return AL.isDeclspecPropertyAttribute(); 3147 }); 3148 if (Itr != list.end()) 3149 return &*Itr; 3150 return nullptr; 3151 } 3152 3153 // Check if there is a field shadowing. 3154 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3155 DeclarationName FieldName, 3156 const CXXRecordDecl *RD, 3157 bool DeclIsField) { 3158 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3159 return; 3160 3161 // To record a shadowed field in a base 3162 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3163 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3164 CXXBasePath &Path) { 3165 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3166 // Record an ambiguous path directly 3167 if (Bases.find(Base) != Bases.end()) 3168 return true; 3169 for (const auto Field : Base->lookup(FieldName)) { 3170 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3171 Field->getAccess() != AS_private) { 3172 assert(Field->getAccess() != AS_none); 3173 assert(Bases.find(Base) == Bases.end()); 3174 Bases[Base] = Field; 3175 return true; 3176 } 3177 } 3178 return false; 3179 }; 3180 3181 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3182 /*DetectVirtual=*/true); 3183 if (!RD->lookupInBases(FieldShadowed, Paths)) 3184 return; 3185 3186 for (const auto &P : Paths) { 3187 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3188 auto It = Bases.find(Base); 3189 // Skip duplicated bases 3190 if (It == Bases.end()) 3191 continue; 3192 auto BaseField = It->second; 3193 assert(BaseField->getAccess() != AS_private); 3194 if (AS_none != 3195 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3196 Diag(Loc, diag::warn_shadow_field) 3197 << FieldName << RD << Base << DeclIsField; 3198 Diag(BaseField->getLocation(), diag::note_shadow_field); 3199 Bases.erase(It); 3200 } 3201 } 3202 } 3203 3204 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3205 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3206 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3207 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3208 /// present (but parsing it has been deferred). 3209 NamedDecl * 3210 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3211 MultiTemplateParamsArg TemplateParameterLists, 3212 Expr *BW, const VirtSpecifiers &VS, 3213 InClassInitStyle InitStyle) { 3214 const DeclSpec &DS = D.getDeclSpec(); 3215 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3216 DeclarationName Name = NameInfo.getName(); 3217 SourceLocation Loc = NameInfo.getLoc(); 3218 3219 // For anonymous bitfields, the location should point to the type. 3220 if (Loc.isInvalid()) 3221 Loc = D.getBeginLoc(); 3222 3223 Expr *BitWidth = static_cast<Expr*>(BW); 3224 3225 assert(isa<CXXRecordDecl>(CurContext)); 3226 assert(!DS.isFriendSpecified()); 3227 3228 bool isFunc = D.isDeclarationOfFunction(); 3229 const ParsedAttr *MSPropertyAttr = 3230 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3231 3232 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3233 // The Microsoft extension __interface only permits public member functions 3234 // and prohibits constructors, destructors, operators, non-public member 3235 // functions, static methods and data members. 3236 unsigned InvalidDecl; 3237 bool ShowDeclName = true; 3238 if (!isFunc && 3239 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3240 InvalidDecl = 0; 3241 else if (!isFunc) 3242 InvalidDecl = 1; 3243 else if (AS != AS_public) 3244 InvalidDecl = 2; 3245 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3246 InvalidDecl = 3; 3247 else switch (Name.getNameKind()) { 3248 case DeclarationName::CXXConstructorName: 3249 InvalidDecl = 4; 3250 ShowDeclName = false; 3251 break; 3252 3253 case DeclarationName::CXXDestructorName: 3254 InvalidDecl = 5; 3255 ShowDeclName = false; 3256 break; 3257 3258 case DeclarationName::CXXOperatorName: 3259 case DeclarationName::CXXConversionFunctionName: 3260 InvalidDecl = 6; 3261 break; 3262 3263 default: 3264 InvalidDecl = 0; 3265 break; 3266 } 3267 3268 if (InvalidDecl) { 3269 if (ShowDeclName) 3270 Diag(Loc, diag::err_invalid_member_in_interface) 3271 << (InvalidDecl-1) << Name; 3272 else 3273 Diag(Loc, diag::err_invalid_member_in_interface) 3274 << (InvalidDecl-1) << ""; 3275 return nullptr; 3276 } 3277 } 3278 3279 // C++ 9.2p6: A member shall not be declared to have automatic storage 3280 // duration (auto, register) or with the extern storage-class-specifier. 3281 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3282 // data members and cannot be applied to names declared const or static, 3283 // and cannot be applied to reference members. 3284 switch (DS.getStorageClassSpec()) { 3285 case DeclSpec::SCS_unspecified: 3286 case DeclSpec::SCS_typedef: 3287 case DeclSpec::SCS_static: 3288 break; 3289 case DeclSpec::SCS_mutable: 3290 if (isFunc) { 3291 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3292 3293 // FIXME: It would be nicer if the keyword was ignored only for this 3294 // declarator. Otherwise we could get follow-up errors. 3295 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3296 } 3297 break; 3298 default: 3299 Diag(DS.getStorageClassSpecLoc(), 3300 diag::err_storageclass_invalid_for_member); 3301 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3302 break; 3303 } 3304 3305 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3306 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3307 !isFunc); 3308 3309 if (DS.hasConstexprSpecifier() && isInstField) { 3310 SemaDiagnosticBuilder B = 3311 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3312 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3313 if (InitStyle == ICIS_NoInit) { 3314 B << 0 << 0; 3315 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3316 B << FixItHint::CreateRemoval(ConstexprLoc); 3317 else { 3318 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3319 D.getMutableDeclSpec().ClearConstexprSpec(); 3320 const char *PrevSpec; 3321 unsigned DiagID; 3322 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3323 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3324 (void)Failed; 3325 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3326 } 3327 } else { 3328 B << 1; 3329 const char *PrevSpec; 3330 unsigned DiagID; 3331 if (D.getMutableDeclSpec().SetStorageClassSpec( 3332 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3333 Context.getPrintingPolicy())) { 3334 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3335 "This is the only DeclSpec that should fail to be applied"); 3336 B << 1; 3337 } else { 3338 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3339 isInstField = false; 3340 } 3341 } 3342 } 3343 3344 NamedDecl *Member; 3345 if (isInstField) { 3346 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3347 3348 // Data members must have identifiers for names. 3349 if (!Name.isIdentifier()) { 3350 Diag(Loc, diag::err_bad_variable_name) 3351 << Name; 3352 return nullptr; 3353 } 3354 3355 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3356 3357 // Member field could not be with "template" keyword. 3358 // So TemplateParameterLists should be empty in this case. 3359 if (TemplateParameterLists.size()) { 3360 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3361 if (TemplateParams->size()) { 3362 // There is no such thing as a member field template. 3363 Diag(D.getIdentifierLoc(), diag::err_template_member) 3364 << II 3365 << SourceRange(TemplateParams->getTemplateLoc(), 3366 TemplateParams->getRAngleLoc()); 3367 } else { 3368 // There is an extraneous 'template<>' for this member. 3369 Diag(TemplateParams->getTemplateLoc(), 3370 diag::err_template_member_noparams) 3371 << II 3372 << SourceRange(TemplateParams->getTemplateLoc(), 3373 TemplateParams->getRAngleLoc()); 3374 } 3375 return nullptr; 3376 } 3377 3378 if (SS.isSet() && !SS.isInvalid()) { 3379 // The user provided a superfluous scope specifier inside a class 3380 // definition: 3381 // 3382 // class X { 3383 // int X::member; 3384 // }; 3385 if (DeclContext *DC = computeDeclContext(SS, false)) 3386 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3387 D.getName().getKind() == 3388 UnqualifiedIdKind::IK_TemplateId); 3389 else 3390 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3391 << Name << SS.getRange(); 3392 3393 SS.clear(); 3394 } 3395 3396 if (MSPropertyAttr) { 3397 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3398 BitWidth, InitStyle, AS, *MSPropertyAttr); 3399 if (!Member) 3400 return nullptr; 3401 isInstField = false; 3402 } else { 3403 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3404 BitWidth, InitStyle, AS); 3405 if (!Member) 3406 return nullptr; 3407 } 3408 3409 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3410 } else { 3411 Member = HandleDeclarator(S, D, TemplateParameterLists); 3412 if (!Member) 3413 return nullptr; 3414 3415 // Non-instance-fields can't have a bitfield. 3416 if (BitWidth) { 3417 if (Member->isInvalidDecl()) { 3418 // don't emit another diagnostic. 3419 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3420 // C++ 9.6p3: A bit-field shall not be a static member. 3421 // "static member 'A' cannot be a bit-field" 3422 Diag(Loc, diag::err_static_not_bitfield) 3423 << Name << BitWidth->getSourceRange(); 3424 } else if (isa<TypedefDecl>(Member)) { 3425 // "typedef member 'x' cannot be a bit-field" 3426 Diag(Loc, diag::err_typedef_not_bitfield) 3427 << Name << BitWidth->getSourceRange(); 3428 } else { 3429 // A function typedef ("typedef int f(); f a;"). 3430 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3431 Diag(Loc, diag::err_not_integral_type_bitfield) 3432 << Name << cast<ValueDecl>(Member)->getType() 3433 << BitWidth->getSourceRange(); 3434 } 3435 3436 BitWidth = nullptr; 3437 Member->setInvalidDecl(); 3438 } 3439 3440 NamedDecl *NonTemplateMember = Member; 3441 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3442 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3443 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3444 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3445 3446 Member->setAccess(AS); 3447 3448 // If we have declared a member function template or static data member 3449 // template, set the access of the templated declaration as well. 3450 if (NonTemplateMember != Member) 3451 NonTemplateMember->setAccess(AS); 3452 3453 // C++ [temp.deduct.guide]p3: 3454 // A deduction guide [...] for a member class template [shall be 3455 // declared] with the same access [as the template]. 3456 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3457 auto *TD = DG->getDeducedTemplate(); 3458 // Access specifiers are only meaningful if both the template and the 3459 // deduction guide are from the same scope. 3460 if (AS != TD->getAccess() && 3461 TD->getDeclContext()->getRedeclContext()->Equals( 3462 DG->getDeclContext()->getRedeclContext())) { 3463 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3464 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3465 << TD->getAccess(); 3466 const AccessSpecDecl *LastAccessSpec = nullptr; 3467 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3468 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3469 LastAccessSpec = AccessSpec; 3470 } 3471 assert(LastAccessSpec && "differing access with no access specifier"); 3472 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3473 << AS; 3474 } 3475 } 3476 } 3477 3478 if (VS.isOverrideSpecified()) 3479 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3480 AttributeCommonInfo::AS_Keyword)); 3481 if (VS.isFinalSpecified()) 3482 Member->addAttr(FinalAttr::Create( 3483 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3484 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3485 3486 if (VS.getLastLocation().isValid()) { 3487 // Update the end location of a method that has a virt-specifiers. 3488 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3489 MD->setRangeEnd(VS.getLastLocation()); 3490 } 3491 3492 CheckOverrideControl(Member); 3493 3494 assert((Name || isInstField) && "No identifier for non-field ?"); 3495 3496 if (isInstField) { 3497 FieldDecl *FD = cast<FieldDecl>(Member); 3498 FieldCollector->Add(FD); 3499 3500 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3501 // Remember all explicit private FieldDecls that have a name, no side 3502 // effects and are not part of a dependent type declaration. 3503 if (!FD->isImplicit() && FD->getDeclName() && 3504 FD->getAccess() == AS_private && 3505 !FD->hasAttr<UnusedAttr>() && 3506 !FD->getParent()->isDependentContext() && 3507 !InitializationHasSideEffects(*FD)) 3508 UnusedPrivateFields.insert(FD); 3509 } 3510 } 3511 3512 return Member; 3513 } 3514 3515 namespace { 3516 class UninitializedFieldVisitor 3517 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3518 Sema &S; 3519 // List of Decls to generate a warning on. Also remove Decls that become 3520 // initialized. 3521 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3522 // List of base classes of the record. Classes are removed after their 3523 // initializers. 3524 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3525 // Vector of decls to be removed from the Decl set prior to visiting the 3526 // nodes. These Decls may have been initialized in the prior initializer. 3527 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3528 // If non-null, add a note to the warning pointing back to the constructor. 3529 const CXXConstructorDecl *Constructor; 3530 // Variables to hold state when processing an initializer list. When 3531 // InitList is true, special case initialization of FieldDecls matching 3532 // InitListFieldDecl. 3533 bool InitList; 3534 FieldDecl *InitListFieldDecl; 3535 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3536 3537 public: 3538 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3539 UninitializedFieldVisitor(Sema &S, 3540 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3541 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3542 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3543 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3544 3545 // Returns true if the use of ME is not an uninitialized use. 3546 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3547 bool CheckReferenceOnly) { 3548 llvm::SmallVector<FieldDecl*, 4> Fields; 3549 bool ReferenceField = false; 3550 while (ME) { 3551 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3552 if (!FD) 3553 return false; 3554 Fields.push_back(FD); 3555 if (FD->getType()->isReferenceType()) 3556 ReferenceField = true; 3557 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3558 } 3559 3560 // Binding a reference to an uninitialized field is not an 3561 // uninitialized use. 3562 if (CheckReferenceOnly && !ReferenceField) 3563 return true; 3564 3565 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3566 // Discard the first field since it is the field decl that is being 3567 // initialized. 3568 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3569 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3570 } 3571 3572 for (auto UsedIter = UsedFieldIndex.begin(), 3573 UsedEnd = UsedFieldIndex.end(), 3574 OrigIter = InitFieldIndex.begin(), 3575 OrigEnd = InitFieldIndex.end(); 3576 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3577 if (*UsedIter < *OrigIter) 3578 return true; 3579 if (*UsedIter > *OrigIter) 3580 break; 3581 } 3582 3583 return false; 3584 } 3585 3586 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3587 bool AddressOf) { 3588 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3589 return; 3590 3591 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3592 // or union. 3593 MemberExpr *FieldME = ME; 3594 3595 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3596 3597 Expr *Base = ME; 3598 while (MemberExpr *SubME = 3599 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3600 3601 if (isa<VarDecl>(SubME->getMemberDecl())) 3602 return; 3603 3604 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3605 if (!FD->isAnonymousStructOrUnion()) 3606 FieldME = SubME; 3607 3608 if (!FieldME->getType().isPODType(S.Context)) 3609 AllPODFields = false; 3610 3611 Base = SubME->getBase(); 3612 } 3613 3614 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3615 Visit(Base); 3616 return; 3617 } 3618 3619 if (AddressOf && AllPODFields) 3620 return; 3621 3622 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3623 3624 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3625 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3626 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3627 } 3628 3629 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3630 QualType T = BaseCast->getType(); 3631 if (T->isPointerType() && 3632 BaseClasses.count(T->getPointeeType())) { 3633 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3634 << T->getPointeeType() << FoundVD; 3635 } 3636 } 3637 } 3638 3639 if (!Decls.count(FoundVD)) 3640 return; 3641 3642 const bool IsReference = FoundVD->getType()->isReferenceType(); 3643 3644 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3645 // Special checking for initializer lists. 3646 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3647 return; 3648 } 3649 } else { 3650 // Prevent double warnings on use of unbounded references. 3651 if (CheckReferenceOnly && !IsReference) 3652 return; 3653 } 3654 3655 unsigned diag = IsReference 3656 ? diag::warn_reference_field_is_uninit 3657 : diag::warn_field_is_uninit; 3658 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3659 if (Constructor) 3660 S.Diag(Constructor->getLocation(), 3661 diag::note_uninit_in_this_constructor) 3662 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3663 3664 } 3665 3666 void HandleValue(Expr *E, bool AddressOf) { 3667 E = E->IgnoreParens(); 3668 3669 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3670 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3671 AddressOf /*AddressOf*/); 3672 return; 3673 } 3674 3675 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3676 Visit(CO->getCond()); 3677 HandleValue(CO->getTrueExpr(), AddressOf); 3678 HandleValue(CO->getFalseExpr(), AddressOf); 3679 return; 3680 } 3681 3682 if (BinaryConditionalOperator *BCO = 3683 dyn_cast<BinaryConditionalOperator>(E)) { 3684 Visit(BCO->getCond()); 3685 HandleValue(BCO->getFalseExpr(), AddressOf); 3686 return; 3687 } 3688 3689 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3690 HandleValue(OVE->getSourceExpr(), AddressOf); 3691 return; 3692 } 3693 3694 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3695 switch (BO->getOpcode()) { 3696 default: 3697 break; 3698 case(BO_PtrMemD): 3699 case(BO_PtrMemI): 3700 HandleValue(BO->getLHS(), AddressOf); 3701 Visit(BO->getRHS()); 3702 return; 3703 case(BO_Comma): 3704 Visit(BO->getLHS()); 3705 HandleValue(BO->getRHS(), AddressOf); 3706 return; 3707 } 3708 } 3709 3710 Visit(E); 3711 } 3712 3713 void CheckInitListExpr(InitListExpr *ILE) { 3714 InitFieldIndex.push_back(0); 3715 for (auto Child : ILE->children()) { 3716 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3717 CheckInitListExpr(SubList); 3718 } else { 3719 Visit(Child); 3720 } 3721 ++InitFieldIndex.back(); 3722 } 3723 InitFieldIndex.pop_back(); 3724 } 3725 3726 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3727 FieldDecl *Field, const Type *BaseClass) { 3728 // Remove Decls that may have been initialized in the previous 3729 // initializer. 3730 for (ValueDecl* VD : DeclsToRemove) 3731 Decls.erase(VD); 3732 DeclsToRemove.clear(); 3733 3734 Constructor = FieldConstructor; 3735 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3736 3737 if (ILE && Field) { 3738 InitList = true; 3739 InitListFieldDecl = Field; 3740 InitFieldIndex.clear(); 3741 CheckInitListExpr(ILE); 3742 } else { 3743 InitList = false; 3744 Visit(E); 3745 } 3746 3747 if (Field) 3748 Decls.erase(Field); 3749 if (BaseClass) 3750 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3751 } 3752 3753 void VisitMemberExpr(MemberExpr *ME) { 3754 // All uses of unbounded reference fields will warn. 3755 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3756 } 3757 3758 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3759 if (E->getCastKind() == CK_LValueToRValue) { 3760 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3761 return; 3762 } 3763 3764 Inherited::VisitImplicitCastExpr(E); 3765 } 3766 3767 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3768 if (E->getConstructor()->isCopyConstructor()) { 3769 Expr *ArgExpr = E->getArg(0); 3770 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3771 if (ILE->getNumInits() == 1) 3772 ArgExpr = ILE->getInit(0); 3773 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3774 if (ICE->getCastKind() == CK_NoOp) 3775 ArgExpr = ICE->getSubExpr(); 3776 HandleValue(ArgExpr, false /*AddressOf*/); 3777 return; 3778 } 3779 Inherited::VisitCXXConstructExpr(E); 3780 } 3781 3782 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3783 Expr *Callee = E->getCallee(); 3784 if (isa<MemberExpr>(Callee)) { 3785 HandleValue(Callee, false /*AddressOf*/); 3786 for (auto Arg : E->arguments()) 3787 Visit(Arg); 3788 return; 3789 } 3790 3791 Inherited::VisitCXXMemberCallExpr(E); 3792 } 3793 3794 void VisitCallExpr(CallExpr *E) { 3795 // Treat std::move as a use. 3796 if (E->isCallToStdMove()) { 3797 HandleValue(E->getArg(0), /*AddressOf=*/false); 3798 return; 3799 } 3800 3801 Inherited::VisitCallExpr(E); 3802 } 3803 3804 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3805 Expr *Callee = E->getCallee(); 3806 3807 if (isa<UnresolvedLookupExpr>(Callee)) 3808 return Inherited::VisitCXXOperatorCallExpr(E); 3809 3810 Visit(Callee); 3811 for (auto Arg : E->arguments()) 3812 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3813 } 3814 3815 void VisitBinaryOperator(BinaryOperator *E) { 3816 // If a field assignment is detected, remove the field from the 3817 // uninitiailized field set. 3818 if (E->getOpcode() == BO_Assign) 3819 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3820 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3821 if (!FD->getType()->isReferenceType()) 3822 DeclsToRemove.push_back(FD); 3823 3824 if (E->isCompoundAssignmentOp()) { 3825 HandleValue(E->getLHS(), false /*AddressOf*/); 3826 Visit(E->getRHS()); 3827 return; 3828 } 3829 3830 Inherited::VisitBinaryOperator(E); 3831 } 3832 3833 void VisitUnaryOperator(UnaryOperator *E) { 3834 if (E->isIncrementDecrementOp()) { 3835 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3836 return; 3837 } 3838 if (E->getOpcode() == UO_AddrOf) { 3839 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3840 HandleValue(ME->getBase(), true /*AddressOf*/); 3841 return; 3842 } 3843 } 3844 3845 Inherited::VisitUnaryOperator(E); 3846 } 3847 }; 3848 3849 // Diagnose value-uses of fields to initialize themselves, e.g. 3850 // foo(foo) 3851 // where foo is not also a parameter to the constructor. 3852 // Also diagnose across field uninitialized use such as 3853 // x(y), y(x) 3854 // TODO: implement -Wuninitialized and fold this into that framework. 3855 static void DiagnoseUninitializedFields( 3856 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3857 3858 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3859 Constructor->getLocation())) { 3860 return; 3861 } 3862 3863 if (Constructor->isInvalidDecl()) 3864 return; 3865 3866 const CXXRecordDecl *RD = Constructor->getParent(); 3867 3868 if (RD->isDependentContext()) 3869 return; 3870 3871 // Holds fields that are uninitialized. 3872 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3873 3874 // At the beginning, all fields are uninitialized. 3875 for (auto *I : RD->decls()) { 3876 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3877 UninitializedFields.insert(FD); 3878 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3879 UninitializedFields.insert(IFD->getAnonField()); 3880 } 3881 } 3882 3883 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3884 for (auto I : RD->bases()) 3885 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3886 3887 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3888 return; 3889 3890 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3891 UninitializedFields, 3892 UninitializedBaseClasses); 3893 3894 for (const auto *FieldInit : Constructor->inits()) { 3895 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3896 break; 3897 3898 Expr *InitExpr = FieldInit->getInit(); 3899 if (!InitExpr) 3900 continue; 3901 3902 if (CXXDefaultInitExpr *Default = 3903 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3904 InitExpr = Default->getExpr(); 3905 if (!InitExpr) 3906 continue; 3907 // In class initializers will point to the constructor. 3908 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3909 FieldInit->getAnyMember(), 3910 FieldInit->getBaseClass()); 3911 } else { 3912 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3913 FieldInit->getAnyMember(), 3914 FieldInit->getBaseClass()); 3915 } 3916 } 3917 } 3918 } // namespace 3919 3920 /// Enter a new C++ default initializer scope. After calling this, the 3921 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3922 /// parsing or instantiating the initializer failed. 3923 void Sema::ActOnStartCXXInClassMemberInitializer() { 3924 // Create a synthetic function scope to represent the call to the constructor 3925 // that notionally surrounds a use of this initializer. 3926 PushFunctionScope(); 3927 } 3928 3929 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3930 if (!D.isFunctionDeclarator()) 3931 return; 3932 auto &FTI = D.getFunctionTypeInfo(); 3933 if (!FTI.Params) 3934 return; 3935 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3936 FTI.NumParams)) { 3937 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3938 if (ParamDecl->getDeclName()) 3939 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3940 } 3941 } 3942 3943 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3944 return ActOnRequiresClause(ConstraintExpr); 3945 } 3946 3947 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3948 if (ConstraintExpr.isInvalid()) 3949 return ExprError(); 3950 3951 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3952 if (ConstraintExpr.isInvalid()) 3953 return ExprError(); 3954 3955 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3956 UPPC_RequiresClause)) 3957 return ExprError(); 3958 3959 return ConstraintExpr; 3960 } 3961 3962 /// This is invoked after parsing an in-class initializer for a 3963 /// non-static C++ class member, and after instantiating an in-class initializer 3964 /// in a class template. Such actions are deferred until the class is complete. 3965 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3966 SourceLocation InitLoc, 3967 Expr *InitExpr) { 3968 // Pop the notional constructor scope we created earlier. 3969 PopFunctionScopeInfo(nullptr, D); 3970 3971 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3972 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3973 "must set init style when field is created"); 3974 3975 if (!InitExpr) { 3976 D->setInvalidDecl(); 3977 if (FD) 3978 FD->removeInClassInitializer(); 3979 return; 3980 } 3981 3982 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3983 FD->setInvalidDecl(); 3984 FD->removeInClassInitializer(); 3985 return; 3986 } 3987 3988 ExprResult Init = InitExpr; 3989 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3990 InitializedEntity Entity = 3991 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3992 InitializationKind Kind = 3993 FD->getInClassInitStyle() == ICIS_ListInit 3994 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3995 InitExpr->getBeginLoc(), 3996 InitExpr->getEndLoc()) 3997 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3998 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3999 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4000 if (Init.isInvalid()) { 4001 FD->setInvalidDecl(); 4002 return; 4003 } 4004 } 4005 4006 // C++11 [class.base.init]p7: 4007 // The initialization of each base and member constitutes a 4008 // full-expression. 4009 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4010 if (Init.isInvalid()) { 4011 FD->setInvalidDecl(); 4012 return; 4013 } 4014 4015 InitExpr = Init.get(); 4016 4017 FD->setInClassInitializer(InitExpr); 4018 } 4019 4020 /// Find the direct and/or virtual base specifiers that 4021 /// correspond to the given base type, for use in base initialization 4022 /// within a constructor. 4023 static bool FindBaseInitializer(Sema &SemaRef, 4024 CXXRecordDecl *ClassDecl, 4025 QualType BaseType, 4026 const CXXBaseSpecifier *&DirectBaseSpec, 4027 const CXXBaseSpecifier *&VirtualBaseSpec) { 4028 // First, check for a direct base class. 4029 DirectBaseSpec = nullptr; 4030 for (const auto &Base : ClassDecl->bases()) { 4031 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4032 // We found a direct base of this type. That's what we're 4033 // initializing. 4034 DirectBaseSpec = &Base; 4035 break; 4036 } 4037 } 4038 4039 // Check for a virtual base class. 4040 // FIXME: We might be able to short-circuit this if we know in advance that 4041 // there are no virtual bases. 4042 VirtualBaseSpec = nullptr; 4043 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4044 // We haven't found a base yet; search the class hierarchy for a 4045 // virtual base class. 4046 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4047 /*DetectVirtual=*/false); 4048 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4049 SemaRef.Context.getTypeDeclType(ClassDecl), 4050 BaseType, Paths)) { 4051 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4052 Path != Paths.end(); ++Path) { 4053 if (Path->back().Base->isVirtual()) { 4054 VirtualBaseSpec = Path->back().Base; 4055 break; 4056 } 4057 } 4058 } 4059 } 4060 4061 return DirectBaseSpec || VirtualBaseSpec; 4062 } 4063 4064 /// Handle a C++ member initializer using braced-init-list syntax. 4065 MemInitResult 4066 Sema::ActOnMemInitializer(Decl *ConstructorD, 4067 Scope *S, 4068 CXXScopeSpec &SS, 4069 IdentifierInfo *MemberOrBase, 4070 ParsedType TemplateTypeTy, 4071 const DeclSpec &DS, 4072 SourceLocation IdLoc, 4073 Expr *InitList, 4074 SourceLocation EllipsisLoc) { 4075 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4076 DS, IdLoc, InitList, 4077 EllipsisLoc); 4078 } 4079 4080 /// Handle a C++ member initializer using parentheses syntax. 4081 MemInitResult 4082 Sema::ActOnMemInitializer(Decl *ConstructorD, 4083 Scope *S, 4084 CXXScopeSpec &SS, 4085 IdentifierInfo *MemberOrBase, 4086 ParsedType TemplateTypeTy, 4087 const DeclSpec &DS, 4088 SourceLocation IdLoc, 4089 SourceLocation LParenLoc, 4090 ArrayRef<Expr *> Args, 4091 SourceLocation RParenLoc, 4092 SourceLocation EllipsisLoc) { 4093 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4094 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4095 DS, IdLoc, List, EllipsisLoc); 4096 } 4097 4098 namespace { 4099 4100 // Callback to only accept typo corrections that can be a valid C++ member 4101 // intializer: either a non-static field member or a base class. 4102 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4103 public: 4104 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4105 : ClassDecl(ClassDecl) {} 4106 4107 bool ValidateCandidate(const TypoCorrection &candidate) override { 4108 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4109 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4110 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4111 return isa<TypeDecl>(ND); 4112 } 4113 return false; 4114 } 4115 4116 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4117 return std::make_unique<MemInitializerValidatorCCC>(*this); 4118 } 4119 4120 private: 4121 CXXRecordDecl *ClassDecl; 4122 }; 4123 4124 } 4125 4126 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4127 CXXScopeSpec &SS, 4128 ParsedType TemplateTypeTy, 4129 IdentifierInfo *MemberOrBase) { 4130 if (SS.getScopeRep() || TemplateTypeTy) 4131 return nullptr; 4132 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4133 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4134 return cast<ValueDecl>(D); 4135 return nullptr; 4136 } 4137 4138 /// Handle a C++ member initializer. 4139 MemInitResult 4140 Sema::BuildMemInitializer(Decl *ConstructorD, 4141 Scope *S, 4142 CXXScopeSpec &SS, 4143 IdentifierInfo *MemberOrBase, 4144 ParsedType TemplateTypeTy, 4145 const DeclSpec &DS, 4146 SourceLocation IdLoc, 4147 Expr *Init, 4148 SourceLocation EllipsisLoc) { 4149 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4150 if (!Res.isUsable()) 4151 return true; 4152 Init = Res.get(); 4153 4154 if (!ConstructorD) 4155 return true; 4156 4157 AdjustDeclIfTemplate(ConstructorD); 4158 4159 CXXConstructorDecl *Constructor 4160 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4161 if (!Constructor) { 4162 // The user wrote a constructor initializer on a function that is 4163 // not a C++ constructor. Ignore the error for now, because we may 4164 // have more member initializers coming; we'll diagnose it just 4165 // once in ActOnMemInitializers. 4166 return true; 4167 } 4168 4169 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4170 4171 // C++ [class.base.init]p2: 4172 // Names in a mem-initializer-id are looked up in the scope of the 4173 // constructor's class and, if not found in that scope, are looked 4174 // up in the scope containing the constructor's definition. 4175 // [Note: if the constructor's class contains a member with the 4176 // same name as a direct or virtual base class of the class, a 4177 // mem-initializer-id naming the member or base class and composed 4178 // of a single identifier refers to the class member. A 4179 // mem-initializer-id for the hidden base class may be specified 4180 // using a qualified name. ] 4181 4182 // Look for a member, first. 4183 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4184 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4185 if (EllipsisLoc.isValid()) 4186 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4187 << MemberOrBase 4188 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4189 4190 return BuildMemberInitializer(Member, Init, IdLoc); 4191 } 4192 // It didn't name a member, so see if it names a class. 4193 QualType BaseType; 4194 TypeSourceInfo *TInfo = nullptr; 4195 4196 if (TemplateTypeTy) { 4197 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4198 if (BaseType.isNull()) 4199 return true; 4200 } else if (DS.getTypeSpecType() == TST_decltype) { 4201 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4202 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4203 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4204 return true; 4205 } else { 4206 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4207 LookupParsedName(R, S, &SS); 4208 4209 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4210 if (!TyD) { 4211 if (R.isAmbiguous()) return true; 4212 4213 // We don't want access-control diagnostics here. 4214 R.suppressDiagnostics(); 4215 4216 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4217 bool NotUnknownSpecialization = false; 4218 DeclContext *DC = computeDeclContext(SS, false); 4219 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4220 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4221 4222 if (!NotUnknownSpecialization) { 4223 // When the scope specifier can refer to a member of an unknown 4224 // specialization, we take it as a type name. 4225 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4226 SS.getWithLocInContext(Context), 4227 *MemberOrBase, IdLoc); 4228 if (BaseType.isNull()) 4229 return true; 4230 4231 TInfo = Context.CreateTypeSourceInfo(BaseType); 4232 DependentNameTypeLoc TL = 4233 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4234 if (!TL.isNull()) { 4235 TL.setNameLoc(IdLoc); 4236 TL.setElaboratedKeywordLoc(SourceLocation()); 4237 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4238 } 4239 4240 R.clear(); 4241 R.setLookupName(MemberOrBase); 4242 } 4243 } 4244 4245 // If no results were found, try to correct typos. 4246 TypoCorrection Corr; 4247 MemInitializerValidatorCCC CCC(ClassDecl); 4248 if (R.empty() && BaseType.isNull() && 4249 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4250 CCC, CTK_ErrorRecovery, ClassDecl))) { 4251 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4252 // We have found a non-static data member with a similar 4253 // name to what was typed; complain and initialize that 4254 // member. 4255 diagnoseTypo(Corr, 4256 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4257 << MemberOrBase << true); 4258 return BuildMemberInitializer(Member, Init, IdLoc); 4259 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4260 const CXXBaseSpecifier *DirectBaseSpec; 4261 const CXXBaseSpecifier *VirtualBaseSpec; 4262 if (FindBaseInitializer(*this, ClassDecl, 4263 Context.getTypeDeclType(Type), 4264 DirectBaseSpec, VirtualBaseSpec)) { 4265 // We have found a direct or virtual base class with a 4266 // similar name to what was typed; complain and initialize 4267 // that base class. 4268 diagnoseTypo(Corr, 4269 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4270 << MemberOrBase << false, 4271 PDiag() /*Suppress note, we provide our own.*/); 4272 4273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4274 : VirtualBaseSpec; 4275 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4276 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4277 4278 TyD = Type; 4279 } 4280 } 4281 } 4282 4283 if (!TyD && BaseType.isNull()) { 4284 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4285 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4286 return true; 4287 } 4288 } 4289 4290 if (BaseType.isNull()) { 4291 BaseType = Context.getTypeDeclType(TyD); 4292 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4293 if (SS.isSet()) { 4294 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4295 BaseType); 4296 TInfo = Context.CreateTypeSourceInfo(BaseType); 4297 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4298 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4299 TL.setElaboratedKeywordLoc(SourceLocation()); 4300 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4301 } 4302 } 4303 } 4304 4305 if (!TInfo) 4306 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4307 4308 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4309 } 4310 4311 MemInitResult 4312 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4313 SourceLocation IdLoc) { 4314 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4315 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4316 assert((DirectMember || IndirectMember) && 4317 "Member must be a FieldDecl or IndirectFieldDecl"); 4318 4319 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4320 return true; 4321 4322 if (Member->isInvalidDecl()) 4323 return true; 4324 4325 MultiExprArg Args; 4326 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4327 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4328 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4329 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4330 } else { 4331 // Template instantiation doesn't reconstruct ParenListExprs for us. 4332 Args = Init; 4333 } 4334 4335 SourceRange InitRange = Init->getSourceRange(); 4336 4337 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4338 // Can't check initialization for a member of dependent type or when 4339 // any of the arguments are type-dependent expressions. 4340 DiscardCleanupsInEvaluationContext(); 4341 } else { 4342 bool InitList = false; 4343 if (isa<InitListExpr>(Init)) { 4344 InitList = true; 4345 Args = Init; 4346 } 4347 4348 // Initialize the member. 4349 InitializedEntity MemberEntity = 4350 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4351 : InitializedEntity::InitializeMember(IndirectMember, 4352 nullptr); 4353 InitializationKind Kind = 4354 InitList ? InitializationKind::CreateDirectList( 4355 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4356 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4357 InitRange.getEnd()); 4358 4359 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4360 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4361 nullptr); 4362 if (MemberInit.isInvalid()) 4363 return true; 4364 4365 // C++11 [class.base.init]p7: 4366 // The initialization of each base and member constitutes a 4367 // full-expression. 4368 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4369 /*DiscardedValue*/ false); 4370 if (MemberInit.isInvalid()) 4371 return true; 4372 4373 Init = MemberInit.get(); 4374 } 4375 4376 if (DirectMember) { 4377 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4378 InitRange.getBegin(), Init, 4379 InitRange.getEnd()); 4380 } else { 4381 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4382 InitRange.getBegin(), Init, 4383 InitRange.getEnd()); 4384 } 4385 } 4386 4387 MemInitResult 4388 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4389 CXXRecordDecl *ClassDecl) { 4390 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4391 if (!LangOpts.CPlusPlus11) 4392 return Diag(NameLoc, diag::err_delegating_ctor) 4393 << TInfo->getTypeLoc().getLocalSourceRange(); 4394 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4395 4396 bool InitList = true; 4397 MultiExprArg Args = Init; 4398 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4399 InitList = false; 4400 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4401 } 4402 4403 SourceRange InitRange = Init->getSourceRange(); 4404 // Initialize the object. 4405 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4406 QualType(ClassDecl->getTypeForDecl(), 0)); 4407 InitializationKind Kind = 4408 InitList ? InitializationKind::CreateDirectList( 4409 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4410 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4411 InitRange.getEnd()); 4412 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4413 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4414 Args, nullptr); 4415 if (DelegationInit.isInvalid()) 4416 return true; 4417 4418 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4419 "Delegating constructor with no target?"); 4420 4421 // C++11 [class.base.init]p7: 4422 // The initialization of each base and member constitutes a 4423 // full-expression. 4424 DelegationInit = ActOnFinishFullExpr( 4425 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4426 if (DelegationInit.isInvalid()) 4427 return true; 4428 4429 // If we are in a dependent context, template instantiation will 4430 // perform this type-checking again. Just save the arguments that we 4431 // received in a ParenListExpr. 4432 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4433 // of the information that we have about the base 4434 // initializer. However, deconstructing the ASTs is a dicey process, 4435 // and this approach is far more likely to get the corner cases right. 4436 if (CurContext->isDependentContext()) 4437 DelegationInit = Init; 4438 4439 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4440 DelegationInit.getAs<Expr>(), 4441 InitRange.getEnd()); 4442 } 4443 4444 MemInitResult 4445 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4446 Expr *Init, CXXRecordDecl *ClassDecl, 4447 SourceLocation EllipsisLoc) { 4448 SourceLocation BaseLoc 4449 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4450 4451 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4452 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4453 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4454 4455 // C++ [class.base.init]p2: 4456 // [...] Unless the mem-initializer-id names a nonstatic data 4457 // member of the constructor's class or a direct or virtual base 4458 // of that class, the mem-initializer is ill-formed. A 4459 // mem-initializer-list can initialize a base class using any 4460 // name that denotes that base class type. 4461 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4462 4463 SourceRange InitRange = Init->getSourceRange(); 4464 if (EllipsisLoc.isValid()) { 4465 // This is a pack expansion. 4466 if (!BaseType->containsUnexpandedParameterPack()) { 4467 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4468 << SourceRange(BaseLoc, InitRange.getEnd()); 4469 4470 EllipsisLoc = SourceLocation(); 4471 } 4472 } else { 4473 // Check for any unexpanded parameter packs. 4474 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4475 return true; 4476 4477 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4478 return true; 4479 } 4480 4481 // Check for direct and virtual base classes. 4482 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4483 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4484 if (!Dependent) { 4485 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4486 BaseType)) 4487 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4488 4489 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4490 VirtualBaseSpec); 4491 4492 // C++ [base.class.init]p2: 4493 // Unless the mem-initializer-id names a nonstatic data member of the 4494 // constructor's class or a direct or virtual base of that class, the 4495 // mem-initializer is ill-formed. 4496 if (!DirectBaseSpec && !VirtualBaseSpec) { 4497 // If the class has any dependent bases, then it's possible that 4498 // one of those types will resolve to the same type as 4499 // BaseType. Therefore, just treat this as a dependent base 4500 // class initialization. FIXME: Should we try to check the 4501 // initialization anyway? It seems odd. 4502 if (ClassDecl->hasAnyDependentBases()) 4503 Dependent = true; 4504 else 4505 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4506 << BaseType << Context.getTypeDeclType(ClassDecl) 4507 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4508 } 4509 } 4510 4511 if (Dependent) { 4512 DiscardCleanupsInEvaluationContext(); 4513 4514 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4515 /*IsVirtual=*/false, 4516 InitRange.getBegin(), Init, 4517 InitRange.getEnd(), EllipsisLoc); 4518 } 4519 4520 // C++ [base.class.init]p2: 4521 // If a mem-initializer-id is ambiguous because it designates both 4522 // a direct non-virtual base class and an inherited virtual base 4523 // class, the mem-initializer is ill-formed. 4524 if (DirectBaseSpec && VirtualBaseSpec) 4525 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4526 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4527 4528 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4529 if (!BaseSpec) 4530 BaseSpec = VirtualBaseSpec; 4531 4532 // Initialize the base. 4533 bool InitList = true; 4534 MultiExprArg Args = Init; 4535 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4536 InitList = false; 4537 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4538 } 4539 4540 InitializedEntity BaseEntity = 4541 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4542 InitializationKind Kind = 4543 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4544 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4545 InitRange.getEnd()); 4546 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4547 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4548 if (BaseInit.isInvalid()) 4549 return true; 4550 4551 // C++11 [class.base.init]p7: 4552 // The initialization of each base and member constitutes a 4553 // full-expression. 4554 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4555 /*DiscardedValue*/ false); 4556 if (BaseInit.isInvalid()) 4557 return true; 4558 4559 // If we are in a dependent context, template instantiation will 4560 // perform this type-checking again. Just save the arguments that we 4561 // received in a ParenListExpr. 4562 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4563 // of the information that we have about the base 4564 // initializer. However, deconstructing the ASTs is a dicey process, 4565 // and this approach is far more likely to get the corner cases right. 4566 if (CurContext->isDependentContext()) 4567 BaseInit = Init; 4568 4569 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4570 BaseSpec->isVirtual(), 4571 InitRange.getBegin(), 4572 BaseInit.getAs<Expr>(), 4573 InitRange.getEnd(), EllipsisLoc); 4574 } 4575 4576 // Create a static_cast\<T&&>(expr). 4577 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4578 if (T.isNull()) T = E->getType(); 4579 QualType TargetType = SemaRef.BuildReferenceType( 4580 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4581 SourceLocation ExprLoc = E->getBeginLoc(); 4582 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4583 TargetType, ExprLoc); 4584 4585 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4586 SourceRange(ExprLoc, ExprLoc), 4587 E->getSourceRange()).get(); 4588 } 4589 4590 /// ImplicitInitializerKind - How an implicit base or member initializer should 4591 /// initialize its base or member. 4592 enum ImplicitInitializerKind { 4593 IIK_Default, 4594 IIK_Copy, 4595 IIK_Move, 4596 IIK_Inherit 4597 }; 4598 4599 static bool 4600 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4601 ImplicitInitializerKind ImplicitInitKind, 4602 CXXBaseSpecifier *BaseSpec, 4603 bool IsInheritedVirtualBase, 4604 CXXCtorInitializer *&CXXBaseInit) { 4605 InitializedEntity InitEntity 4606 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4607 IsInheritedVirtualBase); 4608 4609 ExprResult BaseInit; 4610 4611 switch (ImplicitInitKind) { 4612 case IIK_Inherit: 4613 case IIK_Default: { 4614 InitializationKind InitKind 4615 = InitializationKind::CreateDefault(Constructor->getLocation()); 4616 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4617 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4618 break; 4619 } 4620 4621 case IIK_Move: 4622 case IIK_Copy: { 4623 bool Moving = ImplicitInitKind == IIK_Move; 4624 ParmVarDecl *Param = Constructor->getParamDecl(0); 4625 QualType ParamType = Param->getType().getNonReferenceType(); 4626 4627 Expr *CopyCtorArg = 4628 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4629 SourceLocation(), Param, false, 4630 Constructor->getLocation(), ParamType, 4631 VK_LValue, nullptr); 4632 4633 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4634 4635 // Cast to the base class to avoid ambiguities. 4636 QualType ArgTy = 4637 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4638 ParamType.getQualifiers()); 4639 4640 if (Moving) { 4641 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4642 } 4643 4644 CXXCastPath BasePath; 4645 BasePath.push_back(BaseSpec); 4646 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4647 CK_UncheckedDerivedToBase, 4648 Moving ? VK_XValue : VK_LValue, 4649 &BasePath).get(); 4650 4651 InitializationKind InitKind 4652 = InitializationKind::CreateDirect(Constructor->getLocation(), 4653 SourceLocation(), SourceLocation()); 4654 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4655 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4656 break; 4657 } 4658 } 4659 4660 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4661 if (BaseInit.isInvalid()) 4662 return true; 4663 4664 CXXBaseInit = 4665 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4666 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4667 SourceLocation()), 4668 BaseSpec->isVirtual(), 4669 SourceLocation(), 4670 BaseInit.getAs<Expr>(), 4671 SourceLocation(), 4672 SourceLocation()); 4673 4674 return false; 4675 } 4676 4677 static bool RefersToRValueRef(Expr *MemRef) { 4678 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4679 return Referenced->getType()->isRValueReferenceType(); 4680 } 4681 4682 static bool 4683 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4684 ImplicitInitializerKind ImplicitInitKind, 4685 FieldDecl *Field, IndirectFieldDecl *Indirect, 4686 CXXCtorInitializer *&CXXMemberInit) { 4687 if (Field->isInvalidDecl()) 4688 return true; 4689 4690 SourceLocation Loc = Constructor->getLocation(); 4691 4692 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4693 bool Moving = ImplicitInitKind == IIK_Move; 4694 ParmVarDecl *Param = Constructor->getParamDecl(0); 4695 QualType ParamType = Param->getType().getNonReferenceType(); 4696 4697 // Suppress copying zero-width bitfields. 4698 if (Field->isZeroLengthBitField(SemaRef.Context)) 4699 return false; 4700 4701 Expr *MemberExprBase = 4702 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4703 SourceLocation(), Param, false, 4704 Loc, ParamType, VK_LValue, nullptr); 4705 4706 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4707 4708 if (Moving) { 4709 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4710 } 4711 4712 // Build a reference to this field within the parameter. 4713 CXXScopeSpec SS; 4714 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4715 Sema::LookupMemberName); 4716 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4717 : cast<ValueDecl>(Field), AS_public); 4718 MemberLookup.resolveKind(); 4719 ExprResult CtorArg 4720 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4721 ParamType, Loc, 4722 /*IsArrow=*/false, 4723 SS, 4724 /*TemplateKWLoc=*/SourceLocation(), 4725 /*FirstQualifierInScope=*/nullptr, 4726 MemberLookup, 4727 /*TemplateArgs=*/nullptr, 4728 /*S*/nullptr); 4729 if (CtorArg.isInvalid()) 4730 return true; 4731 4732 // C++11 [class.copy]p15: 4733 // - if a member m has rvalue reference type T&&, it is direct-initialized 4734 // with static_cast<T&&>(x.m); 4735 if (RefersToRValueRef(CtorArg.get())) { 4736 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4737 } 4738 4739 InitializedEntity Entity = 4740 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4741 /*Implicit*/ true) 4742 : InitializedEntity::InitializeMember(Field, nullptr, 4743 /*Implicit*/ true); 4744 4745 // Direct-initialize to use the copy constructor. 4746 InitializationKind InitKind = 4747 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4748 4749 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4750 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4751 ExprResult MemberInit = 4752 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4753 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4754 if (MemberInit.isInvalid()) 4755 return true; 4756 4757 if (Indirect) 4758 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4759 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4760 else 4761 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4762 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4763 return false; 4764 } 4765 4766 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4767 "Unhandled implicit init kind!"); 4768 4769 QualType FieldBaseElementType = 4770 SemaRef.Context.getBaseElementType(Field->getType()); 4771 4772 if (FieldBaseElementType->isRecordType()) { 4773 InitializedEntity InitEntity = 4774 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4775 /*Implicit*/ true) 4776 : InitializedEntity::InitializeMember(Field, nullptr, 4777 /*Implicit*/ true); 4778 InitializationKind InitKind = 4779 InitializationKind::CreateDefault(Loc); 4780 4781 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4782 ExprResult MemberInit = 4783 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4784 4785 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4786 if (MemberInit.isInvalid()) 4787 return true; 4788 4789 if (Indirect) 4790 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4791 Indirect, Loc, 4792 Loc, 4793 MemberInit.get(), 4794 Loc); 4795 else 4796 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4797 Field, Loc, Loc, 4798 MemberInit.get(), 4799 Loc); 4800 return false; 4801 } 4802 4803 if (!Field->getParent()->isUnion()) { 4804 if (FieldBaseElementType->isReferenceType()) { 4805 SemaRef.Diag(Constructor->getLocation(), 4806 diag::err_uninitialized_member_in_ctor) 4807 << (int)Constructor->isImplicit() 4808 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4809 << 0 << Field->getDeclName(); 4810 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4811 return true; 4812 } 4813 4814 if (FieldBaseElementType.isConstQualified()) { 4815 SemaRef.Diag(Constructor->getLocation(), 4816 diag::err_uninitialized_member_in_ctor) 4817 << (int)Constructor->isImplicit() 4818 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4819 << 1 << Field->getDeclName(); 4820 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4821 return true; 4822 } 4823 } 4824 4825 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4826 // ARC and Weak: 4827 // Default-initialize Objective-C pointers to NULL. 4828 CXXMemberInit 4829 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4830 Loc, Loc, 4831 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4832 Loc); 4833 return false; 4834 } 4835 4836 // Nothing to initialize. 4837 CXXMemberInit = nullptr; 4838 return false; 4839 } 4840 4841 namespace { 4842 struct BaseAndFieldInfo { 4843 Sema &S; 4844 CXXConstructorDecl *Ctor; 4845 bool AnyErrorsInInits; 4846 ImplicitInitializerKind IIK; 4847 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4848 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4849 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4850 4851 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4852 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4853 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4854 if (Ctor->getInheritedConstructor()) 4855 IIK = IIK_Inherit; 4856 else if (Generated && Ctor->isCopyConstructor()) 4857 IIK = IIK_Copy; 4858 else if (Generated && Ctor->isMoveConstructor()) 4859 IIK = IIK_Move; 4860 else 4861 IIK = IIK_Default; 4862 } 4863 4864 bool isImplicitCopyOrMove() const { 4865 switch (IIK) { 4866 case IIK_Copy: 4867 case IIK_Move: 4868 return true; 4869 4870 case IIK_Default: 4871 case IIK_Inherit: 4872 return false; 4873 } 4874 4875 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4876 } 4877 4878 bool addFieldInitializer(CXXCtorInitializer *Init) { 4879 AllToInit.push_back(Init); 4880 4881 // Check whether this initializer makes the field "used". 4882 if (Init->getInit()->HasSideEffects(S.Context)) 4883 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4884 4885 return false; 4886 } 4887 4888 bool isInactiveUnionMember(FieldDecl *Field) { 4889 RecordDecl *Record = Field->getParent(); 4890 if (!Record->isUnion()) 4891 return false; 4892 4893 if (FieldDecl *Active = 4894 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4895 return Active != Field->getCanonicalDecl(); 4896 4897 // In an implicit copy or move constructor, ignore any in-class initializer. 4898 if (isImplicitCopyOrMove()) 4899 return true; 4900 4901 // If there's no explicit initialization, the field is active only if it 4902 // has an in-class initializer... 4903 if (Field->hasInClassInitializer()) 4904 return false; 4905 // ... or it's an anonymous struct or union whose class has an in-class 4906 // initializer. 4907 if (!Field->isAnonymousStructOrUnion()) 4908 return true; 4909 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4910 return !FieldRD->hasInClassInitializer(); 4911 } 4912 4913 /// Determine whether the given field is, or is within, a union member 4914 /// that is inactive (because there was an initializer given for a different 4915 /// member of the union, or because the union was not initialized at all). 4916 bool isWithinInactiveUnionMember(FieldDecl *Field, 4917 IndirectFieldDecl *Indirect) { 4918 if (!Indirect) 4919 return isInactiveUnionMember(Field); 4920 4921 for (auto *C : Indirect->chain()) { 4922 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4923 if (Field && isInactiveUnionMember(Field)) 4924 return true; 4925 } 4926 return false; 4927 } 4928 }; 4929 } 4930 4931 /// Determine whether the given type is an incomplete or zero-lenfgth 4932 /// array type. 4933 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4934 if (T->isIncompleteArrayType()) 4935 return true; 4936 4937 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4938 if (!ArrayT->getSize()) 4939 return true; 4940 4941 T = ArrayT->getElementType(); 4942 } 4943 4944 return false; 4945 } 4946 4947 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4948 FieldDecl *Field, 4949 IndirectFieldDecl *Indirect = nullptr) { 4950 if (Field->isInvalidDecl()) 4951 return false; 4952 4953 // Overwhelmingly common case: we have a direct initializer for this field. 4954 if (CXXCtorInitializer *Init = 4955 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4956 return Info.addFieldInitializer(Init); 4957 4958 // C++11 [class.base.init]p8: 4959 // if the entity is a non-static data member that has a 4960 // brace-or-equal-initializer and either 4961 // -- the constructor's class is a union and no other variant member of that 4962 // union is designated by a mem-initializer-id or 4963 // -- the constructor's class is not a union, and, if the entity is a member 4964 // of an anonymous union, no other member of that union is designated by 4965 // a mem-initializer-id, 4966 // the entity is initialized as specified in [dcl.init]. 4967 // 4968 // We also apply the same rules to handle anonymous structs within anonymous 4969 // unions. 4970 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4971 return false; 4972 4973 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4974 ExprResult DIE = 4975 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4976 if (DIE.isInvalid()) 4977 return true; 4978 4979 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4980 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4981 4982 CXXCtorInitializer *Init; 4983 if (Indirect) 4984 Init = new (SemaRef.Context) 4985 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4986 SourceLocation(), DIE.get(), SourceLocation()); 4987 else 4988 Init = new (SemaRef.Context) 4989 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4990 SourceLocation(), DIE.get(), SourceLocation()); 4991 return Info.addFieldInitializer(Init); 4992 } 4993 4994 // Don't initialize incomplete or zero-length arrays. 4995 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4996 return false; 4997 4998 // Don't try to build an implicit initializer if there were semantic 4999 // errors in any of the initializers (and therefore we might be 5000 // missing some that the user actually wrote). 5001 if (Info.AnyErrorsInInits) 5002 return false; 5003 5004 CXXCtorInitializer *Init = nullptr; 5005 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5006 Indirect, Init)) 5007 return true; 5008 5009 if (!Init) 5010 return false; 5011 5012 return Info.addFieldInitializer(Init); 5013 } 5014 5015 bool 5016 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5017 CXXCtorInitializer *Initializer) { 5018 assert(Initializer->isDelegatingInitializer()); 5019 Constructor->setNumCtorInitializers(1); 5020 CXXCtorInitializer **initializer = 5021 new (Context) CXXCtorInitializer*[1]; 5022 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5023 Constructor->setCtorInitializers(initializer); 5024 5025 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5026 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5027 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5028 } 5029 5030 DelegatingCtorDecls.push_back(Constructor); 5031 5032 DiagnoseUninitializedFields(*this, Constructor); 5033 5034 return false; 5035 } 5036 5037 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5038 ArrayRef<CXXCtorInitializer *> Initializers) { 5039 if (Constructor->isDependentContext()) { 5040 // Just store the initializers as written, they will be checked during 5041 // instantiation. 5042 if (!Initializers.empty()) { 5043 Constructor->setNumCtorInitializers(Initializers.size()); 5044 CXXCtorInitializer **baseOrMemberInitializers = 5045 new (Context) CXXCtorInitializer*[Initializers.size()]; 5046 memcpy(baseOrMemberInitializers, Initializers.data(), 5047 Initializers.size() * sizeof(CXXCtorInitializer*)); 5048 Constructor->setCtorInitializers(baseOrMemberInitializers); 5049 } 5050 5051 // Let template instantiation know whether we had errors. 5052 if (AnyErrors) 5053 Constructor->setInvalidDecl(); 5054 5055 return false; 5056 } 5057 5058 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5059 5060 // We need to build the initializer AST according to order of construction 5061 // and not what user specified in the Initializers list. 5062 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5063 if (!ClassDecl) 5064 return true; 5065 5066 bool HadError = false; 5067 5068 for (unsigned i = 0; i < Initializers.size(); i++) { 5069 CXXCtorInitializer *Member = Initializers[i]; 5070 5071 if (Member->isBaseInitializer()) 5072 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5073 else { 5074 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5075 5076 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5077 for (auto *C : F->chain()) { 5078 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5079 if (FD && FD->getParent()->isUnion()) 5080 Info.ActiveUnionMember.insert(std::make_pair( 5081 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5082 } 5083 } else if (FieldDecl *FD = Member->getMember()) { 5084 if (FD->getParent()->isUnion()) 5085 Info.ActiveUnionMember.insert(std::make_pair( 5086 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5087 } 5088 } 5089 } 5090 5091 // Keep track of the direct virtual bases. 5092 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5093 for (auto &I : ClassDecl->bases()) { 5094 if (I.isVirtual()) 5095 DirectVBases.insert(&I); 5096 } 5097 5098 // Push virtual bases before others. 5099 for (auto &VBase : ClassDecl->vbases()) { 5100 if (CXXCtorInitializer *Value 5101 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5102 // [class.base.init]p7, per DR257: 5103 // A mem-initializer where the mem-initializer-id names a virtual base 5104 // class is ignored during execution of a constructor of any class that 5105 // is not the most derived class. 5106 if (ClassDecl->isAbstract()) { 5107 // FIXME: Provide a fixit to remove the base specifier. This requires 5108 // tracking the location of the associated comma for a base specifier. 5109 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5110 << VBase.getType() << ClassDecl; 5111 DiagnoseAbstractType(ClassDecl); 5112 } 5113 5114 Info.AllToInit.push_back(Value); 5115 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5116 // [class.base.init]p8, per DR257: 5117 // If a given [...] base class is not named by a mem-initializer-id 5118 // [...] and the entity is not a virtual base class of an abstract 5119 // class, then [...] the entity is default-initialized. 5120 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5121 CXXCtorInitializer *CXXBaseInit; 5122 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5123 &VBase, IsInheritedVirtualBase, 5124 CXXBaseInit)) { 5125 HadError = true; 5126 continue; 5127 } 5128 5129 Info.AllToInit.push_back(CXXBaseInit); 5130 } 5131 } 5132 5133 // Non-virtual bases. 5134 for (auto &Base : ClassDecl->bases()) { 5135 // Virtuals are in the virtual base list and already constructed. 5136 if (Base.isVirtual()) 5137 continue; 5138 5139 if (CXXCtorInitializer *Value 5140 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5141 Info.AllToInit.push_back(Value); 5142 } else if (!AnyErrors) { 5143 CXXCtorInitializer *CXXBaseInit; 5144 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5145 &Base, /*IsInheritedVirtualBase=*/false, 5146 CXXBaseInit)) { 5147 HadError = true; 5148 continue; 5149 } 5150 5151 Info.AllToInit.push_back(CXXBaseInit); 5152 } 5153 } 5154 5155 // Fields. 5156 for (auto *Mem : ClassDecl->decls()) { 5157 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5158 // C++ [class.bit]p2: 5159 // A declaration for a bit-field that omits the identifier declares an 5160 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5161 // initialized. 5162 if (F->isUnnamedBitfield()) 5163 continue; 5164 5165 // If we're not generating the implicit copy/move constructor, then we'll 5166 // handle anonymous struct/union fields based on their individual 5167 // indirect fields. 5168 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5169 continue; 5170 5171 if (CollectFieldInitializer(*this, Info, F)) 5172 HadError = true; 5173 continue; 5174 } 5175 5176 // Beyond this point, we only consider default initialization. 5177 if (Info.isImplicitCopyOrMove()) 5178 continue; 5179 5180 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5181 if (F->getType()->isIncompleteArrayType()) { 5182 assert(ClassDecl->hasFlexibleArrayMember() && 5183 "Incomplete array type is not valid"); 5184 continue; 5185 } 5186 5187 // Initialize each field of an anonymous struct individually. 5188 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5189 HadError = true; 5190 5191 continue; 5192 } 5193 } 5194 5195 unsigned NumInitializers = Info.AllToInit.size(); 5196 if (NumInitializers > 0) { 5197 Constructor->setNumCtorInitializers(NumInitializers); 5198 CXXCtorInitializer **baseOrMemberInitializers = 5199 new (Context) CXXCtorInitializer*[NumInitializers]; 5200 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5201 NumInitializers * sizeof(CXXCtorInitializer*)); 5202 Constructor->setCtorInitializers(baseOrMemberInitializers); 5203 5204 // Constructors implicitly reference the base and member 5205 // destructors. 5206 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5207 Constructor->getParent()); 5208 } 5209 5210 return HadError; 5211 } 5212 5213 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5214 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5215 const RecordDecl *RD = RT->getDecl(); 5216 if (RD->isAnonymousStructOrUnion()) { 5217 for (auto *Field : RD->fields()) 5218 PopulateKeysForFields(Field, IdealInits); 5219 return; 5220 } 5221 } 5222 IdealInits.push_back(Field->getCanonicalDecl()); 5223 } 5224 5225 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5226 return Context.getCanonicalType(BaseType).getTypePtr(); 5227 } 5228 5229 static const void *GetKeyForMember(ASTContext &Context, 5230 CXXCtorInitializer *Member) { 5231 if (!Member->isAnyMemberInitializer()) 5232 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5233 5234 return Member->getAnyMember()->getCanonicalDecl(); 5235 } 5236 5237 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5238 const CXXCtorInitializer *Previous, 5239 const CXXCtorInitializer *Current) { 5240 if (Previous->isAnyMemberInitializer()) 5241 Diag << 0 << Previous->getAnyMember(); 5242 else 5243 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5244 5245 if (Current->isAnyMemberInitializer()) 5246 Diag << 0 << Current->getAnyMember(); 5247 else 5248 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5249 } 5250 5251 static void DiagnoseBaseOrMemInitializerOrder( 5252 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5253 ArrayRef<CXXCtorInitializer *> Inits) { 5254 if (Constructor->getDeclContext()->isDependentContext()) 5255 return; 5256 5257 // Don't check initializers order unless the warning is enabled at the 5258 // location of at least one initializer. 5259 bool ShouldCheckOrder = false; 5260 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5261 CXXCtorInitializer *Init = Inits[InitIndex]; 5262 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5263 Init->getSourceLocation())) { 5264 ShouldCheckOrder = true; 5265 break; 5266 } 5267 } 5268 if (!ShouldCheckOrder) 5269 return; 5270 5271 // Build the list of bases and members in the order that they'll 5272 // actually be initialized. The explicit initializers should be in 5273 // this same order but may be missing things. 5274 SmallVector<const void*, 32> IdealInitKeys; 5275 5276 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5277 5278 // 1. Virtual bases. 5279 for (const auto &VBase : ClassDecl->vbases()) 5280 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5281 5282 // 2. Non-virtual bases. 5283 for (const auto &Base : ClassDecl->bases()) { 5284 if (Base.isVirtual()) 5285 continue; 5286 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5287 } 5288 5289 // 3. Direct fields. 5290 for (auto *Field : ClassDecl->fields()) { 5291 if (Field->isUnnamedBitfield()) 5292 continue; 5293 5294 PopulateKeysForFields(Field, IdealInitKeys); 5295 } 5296 5297 unsigned NumIdealInits = IdealInitKeys.size(); 5298 unsigned IdealIndex = 0; 5299 5300 // Track initializers that are in an incorrect order for either a warning or 5301 // note if multiple ones occur. 5302 SmallVector<unsigned> WarnIndexes; 5303 // Correlates the index of an initializer in the init-list to the index of 5304 // the field/base in the class. 5305 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5306 5307 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5308 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5309 5310 // Scan forward to try to find this initializer in the idealized 5311 // initializers list. 5312 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5313 if (InitKey == IdealInitKeys[IdealIndex]) 5314 break; 5315 5316 // If we didn't find this initializer, it must be because we 5317 // scanned past it on a previous iteration. That can only 5318 // happen if we're out of order; emit a warning. 5319 if (IdealIndex == NumIdealInits && InitIndex) { 5320 WarnIndexes.push_back(InitIndex); 5321 5322 // Move back to the initializer's location in the ideal list. 5323 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5324 if (InitKey == IdealInitKeys[IdealIndex]) 5325 break; 5326 5327 assert(IdealIndex < NumIdealInits && 5328 "initializer not found in initializer list"); 5329 } 5330 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5331 } 5332 5333 if (WarnIndexes.empty()) 5334 return; 5335 5336 // Sort based on the ideal order, first in the pair. 5337 llvm::sort(CorrelatedInitOrder, 5338 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5339 5340 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5341 // emit the diagnostic before we can try adding notes. 5342 { 5343 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5344 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5345 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5346 : diag::warn_some_initializers_out_of_order); 5347 5348 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5349 if (CorrelatedInitOrder[I].second == I) 5350 continue; 5351 // Ideally we would be using InsertFromRange here, but clang doesn't 5352 // appear to handle InsertFromRange correctly when the source range is 5353 // modified by another fix-it. 5354 D << FixItHint::CreateReplacement( 5355 Inits[I]->getSourceRange(), 5356 Lexer::getSourceText( 5357 CharSourceRange::getTokenRange( 5358 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5359 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5360 } 5361 5362 // If there is only 1 item out of order, the warning expects the name and 5363 // type of each being added to it. 5364 if (WarnIndexes.size() == 1) { 5365 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5366 Inits[WarnIndexes.front()]); 5367 return; 5368 } 5369 } 5370 // More than 1 item to warn, create notes letting the user know which ones 5371 // are bad. 5372 for (unsigned WarnIndex : WarnIndexes) { 5373 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5374 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5375 diag::note_initializer_out_of_order); 5376 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5377 D << PrevInit->getSourceRange(); 5378 } 5379 } 5380 5381 namespace { 5382 bool CheckRedundantInit(Sema &S, 5383 CXXCtorInitializer *Init, 5384 CXXCtorInitializer *&PrevInit) { 5385 if (!PrevInit) { 5386 PrevInit = Init; 5387 return false; 5388 } 5389 5390 if (FieldDecl *Field = Init->getAnyMember()) 5391 S.Diag(Init->getSourceLocation(), 5392 diag::err_multiple_mem_initialization) 5393 << Field->getDeclName() 5394 << Init->getSourceRange(); 5395 else { 5396 const Type *BaseClass = Init->getBaseClass(); 5397 assert(BaseClass && "neither field nor base"); 5398 S.Diag(Init->getSourceLocation(), 5399 diag::err_multiple_base_initialization) 5400 << QualType(BaseClass, 0) 5401 << Init->getSourceRange(); 5402 } 5403 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5404 << 0 << PrevInit->getSourceRange(); 5405 5406 return true; 5407 } 5408 5409 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5410 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5411 5412 bool CheckRedundantUnionInit(Sema &S, 5413 CXXCtorInitializer *Init, 5414 RedundantUnionMap &Unions) { 5415 FieldDecl *Field = Init->getAnyMember(); 5416 RecordDecl *Parent = Field->getParent(); 5417 NamedDecl *Child = Field; 5418 5419 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5420 if (Parent->isUnion()) { 5421 UnionEntry &En = Unions[Parent]; 5422 if (En.first && En.first != Child) { 5423 S.Diag(Init->getSourceLocation(), 5424 diag::err_multiple_mem_union_initialization) 5425 << Field->getDeclName() 5426 << Init->getSourceRange(); 5427 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5428 << 0 << En.second->getSourceRange(); 5429 return true; 5430 } 5431 if (!En.first) { 5432 En.first = Child; 5433 En.second = Init; 5434 } 5435 if (!Parent->isAnonymousStructOrUnion()) 5436 return false; 5437 } 5438 5439 Child = Parent; 5440 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5441 } 5442 5443 return false; 5444 } 5445 } // namespace 5446 5447 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5448 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5449 SourceLocation ColonLoc, 5450 ArrayRef<CXXCtorInitializer*> MemInits, 5451 bool AnyErrors) { 5452 if (!ConstructorDecl) 5453 return; 5454 5455 AdjustDeclIfTemplate(ConstructorDecl); 5456 5457 CXXConstructorDecl *Constructor 5458 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5459 5460 if (!Constructor) { 5461 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5462 return; 5463 } 5464 5465 // Mapping for the duplicate initializers check. 5466 // For member initializers, this is keyed with a FieldDecl*. 5467 // For base initializers, this is keyed with a Type*. 5468 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5469 5470 // Mapping for the inconsistent anonymous-union initializers check. 5471 RedundantUnionMap MemberUnions; 5472 5473 bool HadError = false; 5474 for (unsigned i = 0; i < MemInits.size(); i++) { 5475 CXXCtorInitializer *Init = MemInits[i]; 5476 5477 // Set the source order index. 5478 Init->setSourceOrder(i); 5479 5480 if (Init->isAnyMemberInitializer()) { 5481 const void *Key = GetKeyForMember(Context, Init); 5482 if (CheckRedundantInit(*this, Init, Members[Key]) || 5483 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5484 HadError = true; 5485 } else if (Init->isBaseInitializer()) { 5486 const void *Key = GetKeyForMember(Context, Init); 5487 if (CheckRedundantInit(*this, Init, Members[Key])) 5488 HadError = true; 5489 } else { 5490 assert(Init->isDelegatingInitializer()); 5491 // This must be the only initializer 5492 if (MemInits.size() != 1) { 5493 Diag(Init->getSourceLocation(), 5494 diag::err_delegating_initializer_alone) 5495 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5496 // We will treat this as being the only initializer. 5497 } 5498 SetDelegatingInitializer(Constructor, MemInits[i]); 5499 // Return immediately as the initializer is set. 5500 return; 5501 } 5502 } 5503 5504 if (HadError) 5505 return; 5506 5507 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5508 5509 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5510 5511 DiagnoseUninitializedFields(*this, Constructor); 5512 } 5513 5514 void 5515 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5516 CXXRecordDecl *ClassDecl) { 5517 // Ignore dependent contexts. Also ignore unions, since their members never 5518 // have destructors implicitly called. 5519 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5520 return; 5521 5522 // FIXME: all the access-control diagnostics are positioned on the 5523 // field/base declaration. That's probably good; that said, the 5524 // user might reasonably want to know why the destructor is being 5525 // emitted, and we currently don't say. 5526 5527 // Non-static data members. 5528 for (auto *Field : ClassDecl->fields()) { 5529 if (Field->isInvalidDecl()) 5530 continue; 5531 5532 // Don't destroy incomplete or zero-length arrays. 5533 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5534 continue; 5535 5536 QualType FieldType = Context.getBaseElementType(Field->getType()); 5537 5538 const RecordType* RT = FieldType->getAs<RecordType>(); 5539 if (!RT) 5540 continue; 5541 5542 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5543 if (FieldClassDecl->isInvalidDecl()) 5544 continue; 5545 if (FieldClassDecl->hasIrrelevantDestructor()) 5546 continue; 5547 // The destructor for an implicit anonymous union member is never invoked. 5548 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5549 continue; 5550 5551 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5552 assert(Dtor && "No dtor found for FieldClassDecl!"); 5553 CheckDestructorAccess(Field->getLocation(), Dtor, 5554 PDiag(diag::err_access_dtor_field) 5555 << Field->getDeclName() 5556 << FieldType); 5557 5558 MarkFunctionReferenced(Location, Dtor); 5559 DiagnoseUseOfDecl(Dtor, Location); 5560 } 5561 5562 // We only potentially invoke the destructors of potentially constructed 5563 // subobjects. 5564 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5565 5566 // If the destructor exists and has already been marked used in the MS ABI, 5567 // then virtual base destructors have already been checked and marked used. 5568 // Skip checking them again to avoid duplicate diagnostics. 5569 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5570 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5571 if (Dtor && Dtor->isUsed()) 5572 VisitVirtualBases = false; 5573 } 5574 5575 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5576 5577 // Bases. 5578 for (const auto &Base : ClassDecl->bases()) { 5579 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5580 if (!RT) 5581 continue; 5582 5583 // Remember direct virtual bases. 5584 if (Base.isVirtual()) { 5585 if (!VisitVirtualBases) 5586 continue; 5587 DirectVirtualBases.insert(RT); 5588 } 5589 5590 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5591 // If our base class is invalid, we probably can't get its dtor anyway. 5592 if (BaseClassDecl->isInvalidDecl()) 5593 continue; 5594 if (BaseClassDecl->hasIrrelevantDestructor()) 5595 continue; 5596 5597 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5598 assert(Dtor && "No dtor found for BaseClassDecl!"); 5599 5600 // FIXME: caret should be on the start of the class name 5601 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5602 PDiag(diag::err_access_dtor_base) 5603 << Base.getType() << Base.getSourceRange(), 5604 Context.getTypeDeclType(ClassDecl)); 5605 5606 MarkFunctionReferenced(Location, Dtor); 5607 DiagnoseUseOfDecl(Dtor, Location); 5608 } 5609 5610 if (VisitVirtualBases) 5611 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5612 &DirectVirtualBases); 5613 } 5614 5615 void Sema::MarkVirtualBaseDestructorsReferenced( 5616 SourceLocation Location, CXXRecordDecl *ClassDecl, 5617 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5618 // Virtual bases. 5619 for (const auto &VBase : ClassDecl->vbases()) { 5620 // Bases are always records in a well-formed non-dependent class. 5621 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5622 5623 // Ignore already visited direct virtual bases. 5624 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5625 continue; 5626 5627 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5628 // If our base class is invalid, we probably can't get its dtor anyway. 5629 if (BaseClassDecl->isInvalidDecl()) 5630 continue; 5631 if (BaseClassDecl->hasIrrelevantDestructor()) 5632 continue; 5633 5634 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5635 assert(Dtor && "No dtor found for BaseClassDecl!"); 5636 if (CheckDestructorAccess( 5637 ClassDecl->getLocation(), Dtor, 5638 PDiag(diag::err_access_dtor_vbase) 5639 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5640 Context.getTypeDeclType(ClassDecl)) == 5641 AR_accessible) { 5642 CheckDerivedToBaseConversion( 5643 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5644 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5645 SourceRange(), DeclarationName(), nullptr); 5646 } 5647 5648 MarkFunctionReferenced(Location, Dtor); 5649 DiagnoseUseOfDecl(Dtor, Location); 5650 } 5651 } 5652 5653 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5654 if (!CDtorDecl) 5655 return; 5656 5657 if (CXXConstructorDecl *Constructor 5658 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5659 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5660 DiagnoseUninitializedFields(*this, Constructor); 5661 } 5662 } 5663 5664 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5665 if (!getLangOpts().CPlusPlus) 5666 return false; 5667 5668 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5669 if (!RD) 5670 return false; 5671 5672 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5673 // class template specialization here, but doing so breaks a lot of code. 5674 5675 // We can't answer whether something is abstract until it has a 5676 // definition. If it's currently being defined, we'll walk back 5677 // over all the declarations when we have a full definition. 5678 const CXXRecordDecl *Def = RD->getDefinition(); 5679 if (!Def || Def->isBeingDefined()) 5680 return false; 5681 5682 return RD->isAbstract(); 5683 } 5684 5685 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5686 TypeDiagnoser &Diagnoser) { 5687 if (!isAbstractType(Loc, T)) 5688 return false; 5689 5690 T = Context.getBaseElementType(T); 5691 Diagnoser.diagnose(*this, Loc, T); 5692 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5693 return true; 5694 } 5695 5696 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5697 // Check if we've already emitted the list of pure virtual functions 5698 // for this class. 5699 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5700 return; 5701 5702 // If the diagnostic is suppressed, don't emit the notes. We're only 5703 // going to emit them once, so try to attach them to a diagnostic we're 5704 // actually going to show. 5705 if (Diags.isLastDiagnosticIgnored()) 5706 return; 5707 5708 CXXFinalOverriderMap FinalOverriders; 5709 RD->getFinalOverriders(FinalOverriders); 5710 5711 // Keep a set of seen pure methods so we won't diagnose the same method 5712 // more than once. 5713 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5714 5715 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5716 MEnd = FinalOverriders.end(); 5717 M != MEnd; 5718 ++M) { 5719 for (OverridingMethods::iterator SO = M->second.begin(), 5720 SOEnd = M->second.end(); 5721 SO != SOEnd; ++SO) { 5722 // C++ [class.abstract]p4: 5723 // A class is abstract if it contains or inherits at least one 5724 // pure virtual function for which the final overrider is pure 5725 // virtual. 5726 5727 // 5728 if (SO->second.size() != 1) 5729 continue; 5730 5731 if (!SO->second.front().Method->isPure()) 5732 continue; 5733 5734 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5735 continue; 5736 5737 Diag(SO->second.front().Method->getLocation(), 5738 diag::note_pure_virtual_function) 5739 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5740 } 5741 } 5742 5743 if (!PureVirtualClassDiagSet) 5744 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5745 PureVirtualClassDiagSet->insert(RD); 5746 } 5747 5748 namespace { 5749 struct AbstractUsageInfo { 5750 Sema &S; 5751 CXXRecordDecl *Record; 5752 CanQualType AbstractType; 5753 bool Invalid; 5754 5755 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5756 : S(S), Record(Record), 5757 AbstractType(S.Context.getCanonicalType( 5758 S.Context.getTypeDeclType(Record))), 5759 Invalid(false) {} 5760 5761 void DiagnoseAbstractType() { 5762 if (Invalid) return; 5763 S.DiagnoseAbstractType(Record); 5764 Invalid = true; 5765 } 5766 5767 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5768 }; 5769 5770 struct CheckAbstractUsage { 5771 AbstractUsageInfo &Info; 5772 const NamedDecl *Ctx; 5773 5774 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5775 : Info(Info), Ctx(Ctx) {} 5776 5777 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5778 switch (TL.getTypeLocClass()) { 5779 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5780 #define TYPELOC(CLASS, PARENT) \ 5781 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5782 #include "clang/AST/TypeLocNodes.def" 5783 } 5784 } 5785 5786 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5787 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5788 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5789 if (!TL.getParam(I)) 5790 continue; 5791 5792 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5793 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5794 } 5795 } 5796 5797 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5798 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5799 } 5800 5801 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5802 // Visit the type parameters from a permissive context. 5803 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5804 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5805 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5806 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5807 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5808 // TODO: other template argument types? 5809 } 5810 } 5811 5812 // Visit pointee types from a permissive context. 5813 #define CheckPolymorphic(Type) \ 5814 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5815 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5816 } 5817 CheckPolymorphic(PointerTypeLoc) 5818 CheckPolymorphic(ReferenceTypeLoc) 5819 CheckPolymorphic(MemberPointerTypeLoc) 5820 CheckPolymorphic(BlockPointerTypeLoc) 5821 CheckPolymorphic(AtomicTypeLoc) 5822 5823 /// Handle all the types we haven't given a more specific 5824 /// implementation for above. 5825 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5826 // Every other kind of type that we haven't called out already 5827 // that has an inner type is either (1) sugar or (2) contains that 5828 // inner type in some way as a subobject. 5829 if (TypeLoc Next = TL.getNextTypeLoc()) 5830 return Visit(Next, Sel); 5831 5832 // If there's no inner type and we're in a permissive context, 5833 // don't diagnose. 5834 if (Sel == Sema::AbstractNone) return; 5835 5836 // Check whether the type matches the abstract type. 5837 QualType T = TL.getType(); 5838 if (T->isArrayType()) { 5839 Sel = Sema::AbstractArrayType; 5840 T = Info.S.Context.getBaseElementType(T); 5841 } 5842 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5843 if (CT != Info.AbstractType) return; 5844 5845 // It matched; do some magic. 5846 if (Sel == Sema::AbstractArrayType) { 5847 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5848 << T << TL.getSourceRange(); 5849 } else { 5850 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5851 << Sel << T << TL.getSourceRange(); 5852 } 5853 Info.DiagnoseAbstractType(); 5854 } 5855 }; 5856 5857 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5858 Sema::AbstractDiagSelID Sel) { 5859 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5860 } 5861 5862 } 5863 5864 /// Check for invalid uses of an abstract type in a method declaration. 5865 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5866 CXXMethodDecl *MD) { 5867 // No need to do the check on definitions, which require that 5868 // the return/param types be complete. 5869 if (MD->doesThisDeclarationHaveABody()) 5870 return; 5871 5872 // For safety's sake, just ignore it if we don't have type source 5873 // information. This should never happen for non-implicit methods, 5874 // but... 5875 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5876 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5877 } 5878 5879 /// Check for invalid uses of an abstract type within a class definition. 5880 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5881 CXXRecordDecl *RD) { 5882 for (auto *D : RD->decls()) { 5883 if (D->isImplicit()) continue; 5884 5885 // Methods and method templates. 5886 if (isa<CXXMethodDecl>(D)) { 5887 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5888 } else if (isa<FunctionTemplateDecl>(D)) { 5889 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5890 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5891 5892 // Fields and static variables. 5893 } else if (isa<FieldDecl>(D)) { 5894 FieldDecl *FD = cast<FieldDecl>(D); 5895 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5896 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5897 } else if (isa<VarDecl>(D)) { 5898 VarDecl *VD = cast<VarDecl>(D); 5899 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5900 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5901 5902 // Nested classes and class templates. 5903 } else if (isa<CXXRecordDecl>(D)) { 5904 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5905 } else if (isa<ClassTemplateDecl>(D)) { 5906 CheckAbstractClassUsage(Info, 5907 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5908 } 5909 } 5910 } 5911 5912 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5913 Attr *ClassAttr = getDLLAttr(Class); 5914 if (!ClassAttr) 5915 return; 5916 5917 assert(ClassAttr->getKind() == attr::DLLExport); 5918 5919 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5920 5921 if (TSK == TSK_ExplicitInstantiationDeclaration) 5922 // Don't go any further if this is just an explicit instantiation 5923 // declaration. 5924 return; 5925 5926 // Add a context note to explain how we got to any diagnostics produced below. 5927 struct MarkingClassDllexported { 5928 Sema &S; 5929 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5930 SourceLocation AttrLoc) 5931 : S(S) { 5932 Sema::CodeSynthesisContext Ctx; 5933 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5934 Ctx.PointOfInstantiation = AttrLoc; 5935 Ctx.Entity = Class; 5936 S.pushCodeSynthesisContext(Ctx); 5937 } 5938 ~MarkingClassDllexported() { 5939 S.popCodeSynthesisContext(); 5940 } 5941 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5942 5943 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5944 S.MarkVTableUsed(Class->getLocation(), Class, true); 5945 5946 for (Decl *Member : Class->decls()) { 5947 // Defined static variables that are members of an exported base 5948 // class must be marked export too. 5949 auto *VD = dyn_cast<VarDecl>(Member); 5950 if (VD && Member->getAttr<DLLExportAttr>() && 5951 VD->getStorageClass() == SC_Static && 5952 TSK == TSK_ImplicitInstantiation) 5953 S.MarkVariableReferenced(VD->getLocation(), VD); 5954 5955 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5956 if (!MD) 5957 continue; 5958 5959 if (Member->getAttr<DLLExportAttr>()) { 5960 if (MD->isUserProvided()) { 5961 // Instantiate non-default class member functions ... 5962 5963 // .. except for certain kinds of template specializations. 5964 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5965 continue; 5966 5967 S.MarkFunctionReferenced(Class->getLocation(), MD); 5968 5969 // The function will be passed to the consumer when its definition is 5970 // encountered. 5971 } else if (MD->isExplicitlyDefaulted()) { 5972 // Synthesize and instantiate explicitly defaulted methods. 5973 S.MarkFunctionReferenced(Class->getLocation(), MD); 5974 5975 if (TSK != TSK_ExplicitInstantiationDefinition) { 5976 // Except for explicit instantiation defs, we will not see the 5977 // definition again later, so pass it to the consumer now. 5978 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5979 } 5980 } else if (!MD->isTrivial() || 5981 MD->isCopyAssignmentOperator() || 5982 MD->isMoveAssignmentOperator()) { 5983 // Synthesize and instantiate non-trivial implicit methods, and the copy 5984 // and move assignment operators. The latter are exported even if they 5985 // are trivial, because the address of an operator can be taken and 5986 // should compare equal across libraries. 5987 S.MarkFunctionReferenced(Class->getLocation(), MD); 5988 5989 // There is no later point when we will see the definition of this 5990 // function, so pass it to the consumer now. 5991 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5992 } 5993 } 5994 } 5995 } 5996 5997 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5998 CXXRecordDecl *Class) { 5999 // Only the MS ABI has default constructor closures, so we don't need to do 6000 // this semantic checking anywhere else. 6001 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6002 return; 6003 6004 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6005 for (Decl *Member : Class->decls()) { 6006 // Look for exported default constructors. 6007 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6008 if (!CD || !CD->isDefaultConstructor()) 6009 continue; 6010 auto *Attr = CD->getAttr<DLLExportAttr>(); 6011 if (!Attr) 6012 continue; 6013 6014 // If the class is non-dependent, mark the default arguments as ODR-used so 6015 // that we can properly codegen the constructor closure. 6016 if (!Class->isDependentContext()) { 6017 for (ParmVarDecl *PD : CD->parameters()) { 6018 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6019 S.DiscardCleanupsInEvaluationContext(); 6020 } 6021 } 6022 6023 if (LastExportedDefaultCtor) { 6024 S.Diag(LastExportedDefaultCtor->getLocation(), 6025 diag::err_attribute_dll_ambiguous_default_ctor) 6026 << Class; 6027 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6028 << CD->getDeclName(); 6029 return; 6030 } 6031 LastExportedDefaultCtor = CD; 6032 } 6033 } 6034 6035 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6036 CXXRecordDecl *Class) { 6037 bool ErrorReported = false; 6038 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6039 ClassTemplateDecl *TD) { 6040 if (ErrorReported) 6041 return; 6042 S.Diag(TD->getLocation(), 6043 diag::err_cuda_device_builtin_surftex_cls_template) 6044 << /*surface*/ 0 << TD; 6045 ErrorReported = true; 6046 }; 6047 6048 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6049 if (!TD) { 6050 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6051 if (!SD) { 6052 S.Diag(Class->getLocation(), 6053 diag::err_cuda_device_builtin_surftex_ref_decl) 6054 << /*surface*/ 0 << Class; 6055 S.Diag(Class->getLocation(), 6056 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6057 << Class; 6058 return; 6059 } 6060 TD = SD->getSpecializedTemplate(); 6061 } 6062 6063 TemplateParameterList *Params = TD->getTemplateParameters(); 6064 unsigned N = Params->size(); 6065 6066 if (N != 2) { 6067 reportIllegalClassTemplate(S, TD); 6068 S.Diag(TD->getLocation(), 6069 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6070 << TD << 2; 6071 } 6072 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6073 reportIllegalClassTemplate(S, TD); 6074 S.Diag(TD->getLocation(), 6075 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6076 << TD << /*1st*/ 0 << /*type*/ 0; 6077 } 6078 if (N > 1) { 6079 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6080 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6081 reportIllegalClassTemplate(S, TD); 6082 S.Diag(TD->getLocation(), 6083 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6084 << TD << /*2nd*/ 1 << /*integer*/ 1; 6085 } 6086 } 6087 } 6088 6089 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6090 CXXRecordDecl *Class) { 6091 bool ErrorReported = false; 6092 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6093 ClassTemplateDecl *TD) { 6094 if (ErrorReported) 6095 return; 6096 S.Diag(TD->getLocation(), 6097 diag::err_cuda_device_builtin_surftex_cls_template) 6098 << /*texture*/ 1 << TD; 6099 ErrorReported = true; 6100 }; 6101 6102 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6103 if (!TD) { 6104 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6105 if (!SD) { 6106 S.Diag(Class->getLocation(), 6107 diag::err_cuda_device_builtin_surftex_ref_decl) 6108 << /*texture*/ 1 << Class; 6109 S.Diag(Class->getLocation(), 6110 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6111 << Class; 6112 return; 6113 } 6114 TD = SD->getSpecializedTemplate(); 6115 } 6116 6117 TemplateParameterList *Params = TD->getTemplateParameters(); 6118 unsigned N = Params->size(); 6119 6120 if (N != 3) { 6121 reportIllegalClassTemplate(S, TD); 6122 S.Diag(TD->getLocation(), 6123 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6124 << TD << 3; 6125 } 6126 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6127 reportIllegalClassTemplate(S, TD); 6128 S.Diag(TD->getLocation(), 6129 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6130 << TD << /*1st*/ 0 << /*type*/ 0; 6131 } 6132 if (N > 1) { 6133 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6134 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6135 reportIllegalClassTemplate(S, TD); 6136 S.Diag(TD->getLocation(), 6137 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6138 << TD << /*2nd*/ 1 << /*integer*/ 1; 6139 } 6140 } 6141 if (N > 2) { 6142 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6143 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6144 reportIllegalClassTemplate(S, TD); 6145 S.Diag(TD->getLocation(), 6146 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6147 << TD << /*3rd*/ 2 << /*integer*/ 1; 6148 } 6149 } 6150 } 6151 6152 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6153 // Mark any compiler-generated routines with the implicit code_seg attribute. 6154 for (auto *Method : Class->methods()) { 6155 if (Method->isUserProvided()) 6156 continue; 6157 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6158 Method->addAttr(A); 6159 } 6160 } 6161 6162 /// Check class-level dllimport/dllexport attribute. 6163 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6164 Attr *ClassAttr = getDLLAttr(Class); 6165 6166 // MSVC inherits DLL attributes to partial class template specializations. 6167 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6168 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6169 if (Attr *TemplateAttr = 6170 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6171 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6172 A->setInherited(true); 6173 ClassAttr = A; 6174 } 6175 } 6176 } 6177 6178 if (!ClassAttr) 6179 return; 6180 6181 if (!Class->isExternallyVisible()) { 6182 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6183 << Class << ClassAttr; 6184 return; 6185 } 6186 6187 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6188 !ClassAttr->isInherited()) { 6189 // Diagnose dll attributes on members of class with dll attribute. 6190 for (Decl *Member : Class->decls()) { 6191 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6192 continue; 6193 InheritableAttr *MemberAttr = getDLLAttr(Member); 6194 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6195 continue; 6196 6197 Diag(MemberAttr->getLocation(), 6198 diag::err_attribute_dll_member_of_dll_class) 6199 << MemberAttr << ClassAttr; 6200 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6201 Member->setInvalidDecl(); 6202 } 6203 } 6204 6205 if (Class->getDescribedClassTemplate()) 6206 // Don't inherit dll attribute until the template is instantiated. 6207 return; 6208 6209 // The class is either imported or exported. 6210 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6211 6212 // Check if this was a dllimport attribute propagated from a derived class to 6213 // a base class template specialization. We don't apply these attributes to 6214 // static data members. 6215 const bool PropagatedImport = 6216 !ClassExported && 6217 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6218 6219 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6220 6221 // Ignore explicit dllexport on explicit class template instantiation 6222 // declarations, except in MinGW mode. 6223 if (ClassExported && !ClassAttr->isInherited() && 6224 TSK == TSK_ExplicitInstantiationDeclaration && 6225 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6226 Class->dropAttr<DLLExportAttr>(); 6227 return; 6228 } 6229 6230 // Force declaration of implicit members so they can inherit the attribute. 6231 ForceDeclarationOfImplicitMembers(Class); 6232 6233 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6234 // seem to be true in practice? 6235 6236 for (Decl *Member : Class->decls()) { 6237 VarDecl *VD = dyn_cast<VarDecl>(Member); 6238 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6239 6240 // Only methods and static fields inherit the attributes. 6241 if (!VD && !MD) 6242 continue; 6243 6244 if (MD) { 6245 // Don't process deleted methods. 6246 if (MD->isDeleted()) 6247 continue; 6248 6249 if (MD->isInlined()) { 6250 // MinGW does not import or export inline methods. But do it for 6251 // template instantiations. 6252 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6253 TSK != TSK_ExplicitInstantiationDeclaration && 6254 TSK != TSK_ExplicitInstantiationDefinition) 6255 continue; 6256 6257 // MSVC versions before 2015 don't export the move assignment operators 6258 // and move constructor, so don't attempt to import/export them if 6259 // we have a definition. 6260 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6261 if ((MD->isMoveAssignmentOperator() || 6262 (Ctor && Ctor->isMoveConstructor())) && 6263 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6264 continue; 6265 6266 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6267 // operator is exported anyway. 6268 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6269 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6270 continue; 6271 } 6272 } 6273 6274 // Don't apply dllimport attributes to static data members of class template 6275 // instantiations when the attribute is propagated from a derived class. 6276 if (VD && PropagatedImport) 6277 continue; 6278 6279 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6280 continue; 6281 6282 if (!getDLLAttr(Member)) { 6283 InheritableAttr *NewAttr = nullptr; 6284 6285 // Do not export/import inline function when -fno-dllexport-inlines is 6286 // passed. But add attribute for later local static var check. 6287 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6288 TSK != TSK_ExplicitInstantiationDeclaration && 6289 TSK != TSK_ExplicitInstantiationDefinition) { 6290 if (ClassExported) { 6291 NewAttr = ::new (getASTContext()) 6292 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6293 } else { 6294 NewAttr = ::new (getASTContext()) 6295 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6296 } 6297 } else { 6298 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6299 } 6300 6301 NewAttr->setInherited(true); 6302 Member->addAttr(NewAttr); 6303 6304 if (MD) { 6305 // Propagate DLLAttr to friend re-declarations of MD that have already 6306 // been constructed. 6307 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6308 FD = FD->getPreviousDecl()) { 6309 if (FD->getFriendObjectKind() == Decl::FOK_None) 6310 continue; 6311 assert(!getDLLAttr(FD) && 6312 "friend re-decl should not already have a DLLAttr"); 6313 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6314 NewAttr->setInherited(true); 6315 FD->addAttr(NewAttr); 6316 } 6317 } 6318 } 6319 } 6320 6321 if (ClassExported) 6322 DelayedDllExportClasses.push_back(Class); 6323 } 6324 6325 /// Perform propagation of DLL attributes from a derived class to a 6326 /// templated base class for MS compatibility. 6327 void Sema::propagateDLLAttrToBaseClassTemplate( 6328 CXXRecordDecl *Class, Attr *ClassAttr, 6329 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6330 if (getDLLAttr( 6331 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6332 // If the base class template has a DLL attribute, don't try to change it. 6333 return; 6334 } 6335 6336 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6337 if (!getDLLAttr(BaseTemplateSpec) && 6338 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6339 TSK == TSK_ImplicitInstantiation)) { 6340 // The template hasn't been instantiated yet (or it has, but only as an 6341 // explicit instantiation declaration or implicit instantiation, which means 6342 // we haven't codegenned any members yet), so propagate the attribute. 6343 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6344 NewAttr->setInherited(true); 6345 BaseTemplateSpec->addAttr(NewAttr); 6346 6347 // If this was an import, mark that we propagated it from a derived class to 6348 // a base class template specialization. 6349 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6350 ImportAttr->setPropagatedToBaseTemplate(); 6351 6352 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6353 // needs to be run again to work see the new attribute. Otherwise this will 6354 // get run whenever the template is instantiated. 6355 if (TSK != TSK_Undeclared) 6356 checkClassLevelDLLAttribute(BaseTemplateSpec); 6357 6358 return; 6359 } 6360 6361 if (getDLLAttr(BaseTemplateSpec)) { 6362 // The template has already been specialized or instantiated with an 6363 // attribute, explicitly or through propagation. We should not try to change 6364 // it. 6365 return; 6366 } 6367 6368 // The template was previously instantiated or explicitly specialized without 6369 // a dll attribute, It's too late for us to add an attribute, so warn that 6370 // this is unsupported. 6371 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6372 << BaseTemplateSpec->isExplicitSpecialization(); 6373 Diag(ClassAttr->getLocation(), diag::note_attribute); 6374 if (BaseTemplateSpec->isExplicitSpecialization()) { 6375 Diag(BaseTemplateSpec->getLocation(), 6376 diag::note_template_class_explicit_specialization_was_here) 6377 << BaseTemplateSpec; 6378 } else { 6379 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6380 diag::note_template_class_instantiation_was_here) 6381 << BaseTemplateSpec; 6382 } 6383 } 6384 6385 /// Determine the kind of defaulting that would be done for a given function. 6386 /// 6387 /// If the function is both a default constructor and a copy / move constructor 6388 /// (due to having a default argument for the first parameter), this picks 6389 /// CXXDefaultConstructor. 6390 /// 6391 /// FIXME: Check that case is properly handled by all callers. 6392 Sema::DefaultedFunctionKind 6393 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6394 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6395 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6396 if (Ctor->isDefaultConstructor()) 6397 return Sema::CXXDefaultConstructor; 6398 6399 if (Ctor->isCopyConstructor()) 6400 return Sema::CXXCopyConstructor; 6401 6402 if (Ctor->isMoveConstructor()) 6403 return Sema::CXXMoveConstructor; 6404 } 6405 6406 if (MD->isCopyAssignmentOperator()) 6407 return Sema::CXXCopyAssignment; 6408 6409 if (MD->isMoveAssignmentOperator()) 6410 return Sema::CXXMoveAssignment; 6411 6412 if (isa<CXXDestructorDecl>(FD)) 6413 return Sema::CXXDestructor; 6414 } 6415 6416 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6417 case OO_EqualEqual: 6418 return DefaultedComparisonKind::Equal; 6419 6420 case OO_ExclaimEqual: 6421 return DefaultedComparisonKind::NotEqual; 6422 6423 case OO_Spaceship: 6424 // No point allowing this if <=> doesn't exist in the current language mode. 6425 if (!getLangOpts().CPlusPlus20) 6426 break; 6427 return DefaultedComparisonKind::ThreeWay; 6428 6429 case OO_Less: 6430 case OO_LessEqual: 6431 case OO_Greater: 6432 case OO_GreaterEqual: 6433 // No point allowing this if <=> doesn't exist in the current language mode. 6434 if (!getLangOpts().CPlusPlus20) 6435 break; 6436 return DefaultedComparisonKind::Relational; 6437 6438 default: 6439 break; 6440 } 6441 6442 // Not defaultable. 6443 return DefaultedFunctionKind(); 6444 } 6445 6446 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6447 SourceLocation DefaultLoc) { 6448 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6449 if (DFK.isComparison()) 6450 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6451 6452 switch (DFK.asSpecialMember()) { 6453 case Sema::CXXDefaultConstructor: 6454 S.DefineImplicitDefaultConstructor(DefaultLoc, 6455 cast<CXXConstructorDecl>(FD)); 6456 break; 6457 case Sema::CXXCopyConstructor: 6458 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6459 break; 6460 case Sema::CXXCopyAssignment: 6461 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6462 break; 6463 case Sema::CXXDestructor: 6464 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6465 break; 6466 case Sema::CXXMoveConstructor: 6467 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6468 break; 6469 case Sema::CXXMoveAssignment: 6470 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6471 break; 6472 case Sema::CXXInvalid: 6473 llvm_unreachable("Invalid special member."); 6474 } 6475 } 6476 6477 /// Determine whether a type is permitted to be passed or returned in 6478 /// registers, per C++ [class.temporary]p3. 6479 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6480 TargetInfo::CallingConvKind CCK) { 6481 if (D->isDependentType() || D->isInvalidDecl()) 6482 return false; 6483 6484 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6485 // The PS4 platform ABI follows the behavior of Clang 3.2. 6486 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6487 return !D->hasNonTrivialDestructorForCall() && 6488 !D->hasNonTrivialCopyConstructorForCall(); 6489 6490 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6491 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6492 bool DtorIsTrivialForCall = false; 6493 6494 // If a class has at least one non-deleted, trivial copy constructor, it 6495 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6496 // 6497 // Note: This permits classes with non-trivial copy or move ctors to be 6498 // passed in registers, so long as they *also* have a trivial copy ctor, 6499 // which is non-conforming. 6500 if (D->needsImplicitCopyConstructor()) { 6501 if (!D->defaultedCopyConstructorIsDeleted()) { 6502 if (D->hasTrivialCopyConstructor()) 6503 CopyCtorIsTrivial = true; 6504 if (D->hasTrivialCopyConstructorForCall()) 6505 CopyCtorIsTrivialForCall = true; 6506 } 6507 } else { 6508 for (const CXXConstructorDecl *CD : D->ctors()) { 6509 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6510 if (CD->isTrivial()) 6511 CopyCtorIsTrivial = true; 6512 if (CD->isTrivialForCall()) 6513 CopyCtorIsTrivialForCall = true; 6514 } 6515 } 6516 } 6517 6518 if (D->needsImplicitDestructor()) { 6519 if (!D->defaultedDestructorIsDeleted() && 6520 D->hasTrivialDestructorForCall()) 6521 DtorIsTrivialForCall = true; 6522 } else if (const auto *DD = D->getDestructor()) { 6523 if (!DD->isDeleted() && DD->isTrivialForCall()) 6524 DtorIsTrivialForCall = true; 6525 } 6526 6527 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6528 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6529 return true; 6530 6531 // If a class has a destructor, we'd really like to pass it indirectly 6532 // because it allows us to elide copies. Unfortunately, MSVC makes that 6533 // impossible for small types, which it will pass in a single register or 6534 // stack slot. Most objects with dtors are large-ish, so handle that early. 6535 // We can't call out all large objects as being indirect because there are 6536 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6537 // how we pass large POD types. 6538 6539 // Note: This permits small classes with nontrivial destructors to be 6540 // passed in registers, which is non-conforming. 6541 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6542 uint64_t TypeSize = isAArch64 ? 128 : 64; 6543 6544 if (CopyCtorIsTrivial && 6545 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6546 return true; 6547 return false; 6548 } 6549 6550 // Per C++ [class.temporary]p3, the relevant condition is: 6551 // each copy constructor, move constructor, and destructor of X is 6552 // either trivial or deleted, and X has at least one non-deleted copy 6553 // or move constructor 6554 bool HasNonDeletedCopyOrMove = false; 6555 6556 if (D->needsImplicitCopyConstructor() && 6557 !D->defaultedCopyConstructorIsDeleted()) { 6558 if (!D->hasTrivialCopyConstructorForCall()) 6559 return false; 6560 HasNonDeletedCopyOrMove = true; 6561 } 6562 6563 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6564 !D->defaultedMoveConstructorIsDeleted()) { 6565 if (!D->hasTrivialMoveConstructorForCall()) 6566 return false; 6567 HasNonDeletedCopyOrMove = true; 6568 } 6569 6570 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6571 !D->hasTrivialDestructorForCall()) 6572 return false; 6573 6574 for (const CXXMethodDecl *MD : D->methods()) { 6575 if (MD->isDeleted()) 6576 continue; 6577 6578 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6579 if (CD && CD->isCopyOrMoveConstructor()) 6580 HasNonDeletedCopyOrMove = true; 6581 else if (!isa<CXXDestructorDecl>(MD)) 6582 continue; 6583 6584 if (!MD->isTrivialForCall()) 6585 return false; 6586 } 6587 6588 return HasNonDeletedCopyOrMove; 6589 } 6590 6591 /// Report an error regarding overriding, along with any relevant 6592 /// overridden methods. 6593 /// 6594 /// \param DiagID the primary error to report. 6595 /// \param MD the overriding method. 6596 static bool 6597 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6598 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6599 bool IssuedDiagnostic = false; 6600 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6601 if (Report(O)) { 6602 if (!IssuedDiagnostic) { 6603 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6604 IssuedDiagnostic = true; 6605 } 6606 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6607 } 6608 } 6609 return IssuedDiagnostic; 6610 } 6611 6612 /// Perform semantic checks on a class definition that has been 6613 /// completing, introducing implicitly-declared members, checking for 6614 /// abstract types, etc. 6615 /// 6616 /// \param S The scope in which the class was parsed. Null if we didn't just 6617 /// parse a class definition. 6618 /// \param Record The completed class. 6619 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6620 if (!Record) 6621 return; 6622 6623 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6624 AbstractUsageInfo Info(*this, Record); 6625 CheckAbstractClassUsage(Info, Record); 6626 } 6627 6628 // If this is not an aggregate type and has no user-declared constructor, 6629 // complain about any non-static data members of reference or const scalar 6630 // type, since they will never get initializers. 6631 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6632 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6633 !Record->isLambda()) { 6634 bool Complained = false; 6635 for (const auto *F : Record->fields()) { 6636 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6637 continue; 6638 6639 if (F->getType()->isReferenceType() || 6640 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6641 if (!Complained) { 6642 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6643 << Record->getTagKind() << Record; 6644 Complained = true; 6645 } 6646 6647 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6648 << F->getType()->isReferenceType() 6649 << F->getDeclName(); 6650 } 6651 } 6652 } 6653 6654 if (Record->getIdentifier()) { 6655 // C++ [class.mem]p13: 6656 // If T is the name of a class, then each of the following shall have a 6657 // name different from T: 6658 // - every member of every anonymous union that is a member of class T. 6659 // 6660 // C++ [class.mem]p14: 6661 // In addition, if class T has a user-declared constructor (12.1), every 6662 // non-static data member of class T shall have a name different from T. 6663 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6664 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6665 ++I) { 6666 NamedDecl *D = (*I)->getUnderlyingDecl(); 6667 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6668 Record->hasUserDeclaredConstructor()) || 6669 isa<IndirectFieldDecl>(D)) { 6670 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6671 << D->getDeclName(); 6672 break; 6673 } 6674 } 6675 } 6676 6677 // Warn if the class has virtual methods but non-virtual public destructor. 6678 if (Record->isPolymorphic() && !Record->isDependentType()) { 6679 CXXDestructorDecl *dtor = Record->getDestructor(); 6680 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6681 !Record->hasAttr<FinalAttr>()) 6682 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6683 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6684 } 6685 6686 if (Record->isAbstract()) { 6687 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6688 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6689 << FA->isSpelledAsSealed(); 6690 DiagnoseAbstractType(Record); 6691 } 6692 } 6693 6694 // Warn if the class has a final destructor but is not itself marked final. 6695 if (!Record->hasAttr<FinalAttr>()) { 6696 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6697 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6698 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6699 << FA->isSpelledAsSealed() 6700 << FixItHint::CreateInsertion( 6701 getLocForEndOfToken(Record->getLocation()), 6702 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6703 Diag(Record->getLocation(), 6704 diag::note_final_dtor_non_final_class_silence) 6705 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6706 } 6707 } 6708 } 6709 6710 // See if trivial_abi has to be dropped. 6711 if (Record->hasAttr<TrivialABIAttr>()) 6712 checkIllFormedTrivialABIStruct(*Record); 6713 6714 // Set HasTrivialSpecialMemberForCall if the record has attribute 6715 // "trivial_abi". 6716 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6717 6718 if (HasTrivialABI) 6719 Record->setHasTrivialSpecialMemberForCall(); 6720 6721 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6722 // We check these last because they can depend on the properties of the 6723 // primary comparison functions (==, <=>). 6724 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6725 6726 // Perform checks that can't be done until we know all the properties of a 6727 // member function (whether it's defaulted, deleted, virtual, overriding, 6728 // ...). 6729 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6730 // A static function cannot override anything. 6731 if (MD->getStorageClass() == SC_Static) { 6732 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6733 [](const CXXMethodDecl *) { return true; })) 6734 return; 6735 } 6736 6737 // A deleted function cannot override a non-deleted function and vice 6738 // versa. 6739 if (ReportOverrides(*this, 6740 MD->isDeleted() ? diag::err_deleted_override 6741 : diag::err_non_deleted_override, 6742 MD, [&](const CXXMethodDecl *V) { 6743 return MD->isDeleted() != V->isDeleted(); 6744 })) { 6745 if (MD->isDefaulted() && MD->isDeleted()) 6746 // Explain why this defaulted function was deleted. 6747 DiagnoseDeletedDefaultedFunction(MD); 6748 return; 6749 } 6750 6751 // A consteval function cannot override a non-consteval function and vice 6752 // versa. 6753 if (ReportOverrides(*this, 6754 MD->isConsteval() ? diag::err_consteval_override 6755 : diag::err_non_consteval_override, 6756 MD, [&](const CXXMethodDecl *V) { 6757 return MD->isConsteval() != V->isConsteval(); 6758 })) { 6759 if (MD->isDefaulted() && MD->isDeleted()) 6760 // Explain why this defaulted function was deleted. 6761 DiagnoseDeletedDefaultedFunction(MD); 6762 return; 6763 } 6764 }; 6765 6766 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6767 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6768 return false; 6769 6770 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6771 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6772 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6773 DefaultedSecondaryComparisons.push_back(FD); 6774 return true; 6775 } 6776 6777 CheckExplicitlyDefaultedFunction(S, FD); 6778 return false; 6779 }; 6780 6781 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6782 // Check whether the explicitly-defaulted members are valid. 6783 bool Incomplete = CheckForDefaultedFunction(M); 6784 6785 // Skip the rest of the checks for a member of a dependent class. 6786 if (Record->isDependentType()) 6787 return; 6788 6789 // For an explicitly defaulted or deleted special member, we defer 6790 // determining triviality until the class is complete. That time is now! 6791 CXXSpecialMember CSM = getSpecialMember(M); 6792 if (!M->isImplicit() && !M->isUserProvided()) { 6793 if (CSM != CXXInvalid) { 6794 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6795 // Inform the class that we've finished declaring this member. 6796 Record->finishedDefaultedOrDeletedMember(M); 6797 M->setTrivialForCall( 6798 HasTrivialABI || 6799 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6800 Record->setTrivialForCallFlags(M); 6801 } 6802 } 6803 6804 // Set triviality for the purpose of calls if this is a user-provided 6805 // copy/move constructor or destructor. 6806 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6807 CSM == CXXDestructor) && M->isUserProvided()) { 6808 M->setTrivialForCall(HasTrivialABI); 6809 Record->setTrivialForCallFlags(M); 6810 } 6811 6812 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6813 M->hasAttr<DLLExportAttr>()) { 6814 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6815 M->isTrivial() && 6816 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6817 CSM == CXXDestructor)) 6818 M->dropAttr<DLLExportAttr>(); 6819 6820 if (M->hasAttr<DLLExportAttr>()) { 6821 // Define after any fields with in-class initializers have been parsed. 6822 DelayedDllExportMemberFunctions.push_back(M); 6823 } 6824 } 6825 6826 // Define defaulted constexpr virtual functions that override a base class 6827 // function right away. 6828 // FIXME: We can defer doing this until the vtable is marked as used. 6829 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6830 DefineDefaultedFunction(*this, M, M->getLocation()); 6831 6832 if (!Incomplete) 6833 CheckCompletedMemberFunction(M); 6834 }; 6835 6836 // Check the destructor before any other member function. We need to 6837 // determine whether it's trivial in order to determine whether the claas 6838 // type is a literal type, which is a prerequisite for determining whether 6839 // other special member functions are valid and whether they're implicitly 6840 // 'constexpr'. 6841 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6842 CompleteMemberFunction(Dtor); 6843 6844 bool HasMethodWithOverrideControl = false, 6845 HasOverridingMethodWithoutOverrideControl = false; 6846 for (auto *D : Record->decls()) { 6847 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6848 // FIXME: We could do this check for dependent types with non-dependent 6849 // bases. 6850 if (!Record->isDependentType()) { 6851 // See if a method overloads virtual methods in a base 6852 // class without overriding any. 6853 if (!M->isStatic()) 6854 DiagnoseHiddenVirtualMethods(M); 6855 if (M->hasAttr<OverrideAttr>()) 6856 HasMethodWithOverrideControl = true; 6857 else if (M->size_overridden_methods() > 0) 6858 HasOverridingMethodWithoutOverrideControl = true; 6859 } 6860 6861 if (!isa<CXXDestructorDecl>(M)) 6862 CompleteMemberFunction(M); 6863 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6864 CheckForDefaultedFunction( 6865 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6866 } 6867 } 6868 6869 if (HasOverridingMethodWithoutOverrideControl) { 6870 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6871 for (auto *M : Record->methods()) 6872 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6873 } 6874 6875 // Check the defaulted secondary comparisons after any other member functions. 6876 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6877 CheckExplicitlyDefaultedFunction(S, FD); 6878 6879 // If this is a member function, we deferred checking it until now. 6880 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6881 CheckCompletedMemberFunction(MD); 6882 } 6883 6884 // ms_struct is a request to use the same ABI rules as MSVC. Check 6885 // whether this class uses any C++ features that are implemented 6886 // completely differently in MSVC, and if so, emit a diagnostic. 6887 // That diagnostic defaults to an error, but we allow projects to 6888 // map it down to a warning (or ignore it). It's a fairly common 6889 // practice among users of the ms_struct pragma to mass-annotate 6890 // headers, sweeping up a bunch of types that the project doesn't 6891 // really rely on MSVC-compatible layout for. We must therefore 6892 // support "ms_struct except for C++ stuff" as a secondary ABI. 6893 // Don't emit this diagnostic if the feature was enabled as a 6894 // language option (as opposed to via a pragma or attribute), as 6895 // the option -mms-bitfields otherwise essentially makes it impossible 6896 // to build C++ code, unless this diagnostic is turned off. 6897 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6898 (Record->isPolymorphic() || Record->getNumBases())) { 6899 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6900 } 6901 6902 checkClassLevelDLLAttribute(Record); 6903 checkClassLevelCodeSegAttribute(Record); 6904 6905 bool ClangABICompat4 = 6906 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6907 TargetInfo::CallingConvKind CCK = 6908 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6909 bool CanPass = canPassInRegisters(*this, Record, CCK); 6910 6911 // Do not change ArgPassingRestrictions if it has already been set to 6912 // APK_CanNeverPassInRegs. 6913 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6914 Record->setArgPassingRestrictions(CanPass 6915 ? RecordDecl::APK_CanPassInRegs 6916 : RecordDecl::APK_CannotPassInRegs); 6917 6918 // If canPassInRegisters returns true despite the record having a non-trivial 6919 // destructor, the record is destructed in the callee. This happens only when 6920 // the record or one of its subobjects has a field annotated with trivial_abi 6921 // or a field qualified with ObjC __strong/__weak. 6922 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6923 Record->setParamDestroyedInCallee(true); 6924 else if (Record->hasNonTrivialDestructor()) 6925 Record->setParamDestroyedInCallee(CanPass); 6926 6927 if (getLangOpts().ForceEmitVTables) { 6928 // If we want to emit all the vtables, we need to mark it as used. This 6929 // is especially required for cases like vtable assumption loads. 6930 MarkVTableUsed(Record->getInnerLocStart(), Record); 6931 } 6932 6933 if (getLangOpts().CUDA) { 6934 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6935 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6936 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6937 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6938 } 6939 } 6940 6941 /// Look up the special member function that would be called by a special 6942 /// member function for a subobject of class type. 6943 /// 6944 /// \param Class The class type of the subobject. 6945 /// \param CSM The kind of special member function. 6946 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6947 /// \param ConstRHS True if this is a copy operation with a const object 6948 /// on its RHS, that is, if the argument to the outer special member 6949 /// function is 'const' and this is not a field marked 'mutable'. 6950 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6951 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6952 unsigned FieldQuals, bool ConstRHS) { 6953 unsigned LHSQuals = 0; 6954 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6955 LHSQuals = FieldQuals; 6956 6957 unsigned RHSQuals = FieldQuals; 6958 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6959 RHSQuals = 0; 6960 else if (ConstRHS) 6961 RHSQuals |= Qualifiers::Const; 6962 6963 return S.LookupSpecialMember(Class, CSM, 6964 RHSQuals & Qualifiers::Const, 6965 RHSQuals & Qualifiers::Volatile, 6966 false, 6967 LHSQuals & Qualifiers::Const, 6968 LHSQuals & Qualifiers::Volatile); 6969 } 6970 6971 class Sema::InheritedConstructorInfo { 6972 Sema &S; 6973 SourceLocation UseLoc; 6974 6975 /// A mapping from the base classes through which the constructor was 6976 /// inherited to the using shadow declaration in that base class (or a null 6977 /// pointer if the constructor was declared in that base class). 6978 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6979 InheritedFromBases; 6980 6981 public: 6982 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6983 ConstructorUsingShadowDecl *Shadow) 6984 : S(S), UseLoc(UseLoc) { 6985 bool DiagnosedMultipleConstructedBases = false; 6986 CXXRecordDecl *ConstructedBase = nullptr; 6987 UsingDecl *ConstructedBaseUsing = nullptr; 6988 6989 // Find the set of such base class subobjects and check that there's a 6990 // unique constructed subobject. 6991 for (auto *D : Shadow->redecls()) { 6992 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6993 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6994 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6995 6996 InheritedFromBases.insert( 6997 std::make_pair(DNominatedBase->getCanonicalDecl(), 6998 DShadow->getNominatedBaseClassShadowDecl())); 6999 if (DShadow->constructsVirtualBase()) 7000 InheritedFromBases.insert( 7001 std::make_pair(DConstructedBase->getCanonicalDecl(), 7002 DShadow->getConstructedBaseClassShadowDecl())); 7003 else 7004 assert(DNominatedBase == DConstructedBase); 7005 7006 // [class.inhctor.init]p2: 7007 // If the constructor was inherited from multiple base class subobjects 7008 // of type B, the program is ill-formed. 7009 if (!ConstructedBase) { 7010 ConstructedBase = DConstructedBase; 7011 ConstructedBaseUsing = D->getUsingDecl(); 7012 } else if (ConstructedBase != DConstructedBase && 7013 !Shadow->isInvalidDecl()) { 7014 if (!DiagnosedMultipleConstructedBases) { 7015 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7016 << Shadow->getTargetDecl(); 7017 S.Diag(ConstructedBaseUsing->getLocation(), 7018 diag::note_ambiguous_inherited_constructor_using) 7019 << ConstructedBase; 7020 DiagnosedMultipleConstructedBases = true; 7021 } 7022 S.Diag(D->getUsingDecl()->getLocation(), 7023 diag::note_ambiguous_inherited_constructor_using) 7024 << DConstructedBase; 7025 } 7026 } 7027 7028 if (DiagnosedMultipleConstructedBases) 7029 Shadow->setInvalidDecl(); 7030 } 7031 7032 /// Find the constructor to use for inherited construction of a base class, 7033 /// and whether that base class constructor inherits the constructor from a 7034 /// virtual base class (in which case it won't actually invoke it). 7035 std::pair<CXXConstructorDecl *, bool> 7036 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7037 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7038 if (It == InheritedFromBases.end()) 7039 return std::make_pair(nullptr, false); 7040 7041 // This is an intermediary class. 7042 if (It->second) 7043 return std::make_pair( 7044 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7045 It->second->constructsVirtualBase()); 7046 7047 // This is the base class from which the constructor was inherited. 7048 return std::make_pair(Ctor, false); 7049 } 7050 }; 7051 7052 /// Is the special member function which would be selected to perform the 7053 /// specified operation on the specified class type a constexpr constructor? 7054 static bool 7055 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7056 Sema::CXXSpecialMember CSM, unsigned Quals, 7057 bool ConstRHS, 7058 CXXConstructorDecl *InheritedCtor = nullptr, 7059 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7060 // If we're inheriting a constructor, see if we need to call it for this base 7061 // class. 7062 if (InheritedCtor) { 7063 assert(CSM == Sema::CXXDefaultConstructor); 7064 auto BaseCtor = 7065 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7066 if (BaseCtor) 7067 return BaseCtor->isConstexpr(); 7068 } 7069 7070 if (CSM == Sema::CXXDefaultConstructor) 7071 return ClassDecl->hasConstexprDefaultConstructor(); 7072 if (CSM == Sema::CXXDestructor) 7073 return ClassDecl->hasConstexprDestructor(); 7074 7075 Sema::SpecialMemberOverloadResult SMOR = 7076 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7077 if (!SMOR.getMethod()) 7078 // A constructor we wouldn't select can't be "involved in initializing" 7079 // anything. 7080 return true; 7081 return SMOR.getMethod()->isConstexpr(); 7082 } 7083 7084 /// Determine whether the specified special member function would be constexpr 7085 /// if it were implicitly defined. 7086 static bool defaultedSpecialMemberIsConstexpr( 7087 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7088 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7089 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7090 if (!S.getLangOpts().CPlusPlus11) 7091 return false; 7092 7093 // C++11 [dcl.constexpr]p4: 7094 // In the definition of a constexpr constructor [...] 7095 bool Ctor = true; 7096 switch (CSM) { 7097 case Sema::CXXDefaultConstructor: 7098 if (Inherited) 7099 break; 7100 // Since default constructor lookup is essentially trivial (and cannot 7101 // involve, for instance, template instantiation), we compute whether a 7102 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7103 // 7104 // This is important for performance; we need to know whether the default 7105 // constructor is constexpr to determine whether the type is a literal type. 7106 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7107 7108 case Sema::CXXCopyConstructor: 7109 case Sema::CXXMoveConstructor: 7110 // For copy or move constructors, we need to perform overload resolution. 7111 break; 7112 7113 case Sema::CXXCopyAssignment: 7114 case Sema::CXXMoveAssignment: 7115 if (!S.getLangOpts().CPlusPlus14) 7116 return false; 7117 // In C++1y, we need to perform overload resolution. 7118 Ctor = false; 7119 break; 7120 7121 case Sema::CXXDestructor: 7122 return ClassDecl->defaultedDestructorIsConstexpr(); 7123 7124 case Sema::CXXInvalid: 7125 return false; 7126 } 7127 7128 // -- if the class is a non-empty union, or for each non-empty anonymous 7129 // union member of a non-union class, exactly one non-static data member 7130 // shall be initialized; [DR1359] 7131 // 7132 // If we squint, this is guaranteed, since exactly one non-static data member 7133 // will be initialized (if the constructor isn't deleted), we just don't know 7134 // which one. 7135 if (Ctor && ClassDecl->isUnion()) 7136 return CSM == Sema::CXXDefaultConstructor 7137 ? ClassDecl->hasInClassInitializer() || 7138 !ClassDecl->hasVariantMembers() 7139 : true; 7140 7141 // -- the class shall not have any virtual base classes; 7142 if (Ctor && ClassDecl->getNumVBases()) 7143 return false; 7144 7145 // C++1y [class.copy]p26: 7146 // -- [the class] is a literal type, and 7147 if (!Ctor && !ClassDecl->isLiteral()) 7148 return false; 7149 7150 // -- every constructor involved in initializing [...] base class 7151 // sub-objects shall be a constexpr constructor; 7152 // -- the assignment operator selected to copy/move each direct base 7153 // class is a constexpr function, and 7154 for (const auto &B : ClassDecl->bases()) { 7155 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7156 if (!BaseType) continue; 7157 7158 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7159 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7160 InheritedCtor, Inherited)) 7161 return false; 7162 } 7163 7164 // -- every constructor involved in initializing non-static data members 7165 // [...] shall be a constexpr constructor; 7166 // -- every non-static data member and base class sub-object shall be 7167 // initialized 7168 // -- for each non-static data member of X that is of class type (or array 7169 // thereof), the assignment operator selected to copy/move that member is 7170 // a constexpr function 7171 for (const auto *F : ClassDecl->fields()) { 7172 if (F->isInvalidDecl()) 7173 continue; 7174 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7175 continue; 7176 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7177 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7178 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7179 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7180 BaseType.getCVRQualifiers(), 7181 ConstArg && !F->isMutable())) 7182 return false; 7183 } else if (CSM == Sema::CXXDefaultConstructor) { 7184 return false; 7185 } 7186 } 7187 7188 // All OK, it's constexpr! 7189 return true; 7190 } 7191 7192 namespace { 7193 /// RAII object to register a defaulted function as having its exception 7194 /// specification computed. 7195 struct ComputingExceptionSpec { 7196 Sema &S; 7197 7198 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7199 : S(S) { 7200 Sema::CodeSynthesisContext Ctx; 7201 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7202 Ctx.PointOfInstantiation = Loc; 7203 Ctx.Entity = FD; 7204 S.pushCodeSynthesisContext(Ctx); 7205 } 7206 ~ComputingExceptionSpec() { 7207 S.popCodeSynthesisContext(); 7208 } 7209 }; 7210 } 7211 7212 static Sema::ImplicitExceptionSpecification 7213 ComputeDefaultedSpecialMemberExceptionSpec( 7214 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7215 Sema::InheritedConstructorInfo *ICI); 7216 7217 static Sema::ImplicitExceptionSpecification 7218 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7219 FunctionDecl *FD, 7220 Sema::DefaultedComparisonKind DCK); 7221 7222 static Sema::ImplicitExceptionSpecification 7223 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7224 auto DFK = S.getDefaultedFunctionKind(FD); 7225 if (DFK.isSpecialMember()) 7226 return ComputeDefaultedSpecialMemberExceptionSpec( 7227 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7228 if (DFK.isComparison()) 7229 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7230 DFK.asComparison()); 7231 7232 auto *CD = cast<CXXConstructorDecl>(FD); 7233 assert(CD->getInheritedConstructor() && 7234 "only defaulted functions and inherited constructors have implicit " 7235 "exception specs"); 7236 Sema::InheritedConstructorInfo ICI( 7237 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7238 return ComputeDefaultedSpecialMemberExceptionSpec( 7239 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7240 } 7241 7242 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7243 CXXMethodDecl *MD) { 7244 FunctionProtoType::ExtProtoInfo EPI; 7245 7246 // Build an exception specification pointing back at this member. 7247 EPI.ExceptionSpec.Type = EST_Unevaluated; 7248 EPI.ExceptionSpec.SourceDecl = MD; 7249 7250 // Set the calling convention to the default for C++ instance methods. 7251 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7252 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7253 /*IsCXXMethod=*/true)); 7254 return EPI; 7255 } 7256 7257 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7258 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7259 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7260 return; 7261 7262 // Evaluate the exception specification. 7263 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7264 auto ESI = IES.getExceptionSpec(); 7265 7266 // Update the type of the special member to use it. 7267 UpdateExceptionSpec(FD, ESI); 7268 } 7269 7270 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7271 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7272 7273 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7274 if (!DefKind) { 7275 assert(FD->getDeclContext()->isDependentContext()); 7276 return; 7277 } 7278 7279 if (DefKind.isSpecialMember() 7280 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7281 DefKind.asSpecialMember()) 7282 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7283 FD->setInvalidDecl(); 7284 } 7285 7286 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7287 CXXSpecialMember CSM) { 7288 CXXRecordDecl *RD = MD->getParent(); 7289 7290 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7291 "not an explicitly-defaulted special member"); 7292 7293 // Defer all checking for special members of a dependent type. 7294 if (RD->isDependentType()) 7295 return false; 7296 7297 // Whether this was the first-declared instance of the constructor. 7298 // This affects whether we implicitly add an exception spec and constexpr. 7299 bool First = MD == MD->getCanonicalDecl(); 7300 7301 bool HadError = false; 7302 7303 // C++11 [dcl.fct.def.default]p1: 7304 // A function that is explicitly defaulted shall 7305 // -- be a special member function [...] (checked elsewhere), 7306 // -- have the same type (except for ref-qualifiers, and except that a 7307 // copy operation can take a non-const reference) as an implicit 7308 // declaration, and 7309 // -- not have default arguments. 7310 // C++2a changes the second bullet to instead delete the function if it's 7311 // defaulted on its first declaration, unless it's "an assignment operator, 7312 // and its return type differs or its parameter type is not a reference". 7313 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7314 bool ShouldDeleteForTypeMismatch = false; 7315 unsigned ExpectedParams = 1; 7316 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7317 ExpectedParams = 0; 7318 if (MD->getNumParams() != ExpectedParams) { 7319 // This checks for default arguments: a copy or move constructor with a 7320 // default argument is classified as a default constructor, and assignment 7321 // operations and destructors can't have default arguments. 7322 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7323 << CSM << MD->getSourceRange(); 7324 HadError = true; 7325 } else if (MD->isVariadic()) { 7326 if (DeleteOnTypeMismatch) 7327 ShouldDeleteForTypeMismatch = true; 7328 else { 7329 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7330 << CSM << MD->getSourceRange(); 7331 HadError = true; 7332 } 7333 } 7334 7335 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7336 7337 bool CanHaveConstParam = false; 7338 if (CSM == CXXCopyConstructor) 7339 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7340 else if (CSM == CXXCopyAssignment) 7341 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7342 7343 QualType ReturnType = Context.VoidTy; 7344 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7345 // Check for return type matching. 7346 ReturnType = Type->getReturnType(); 7347 7348 QualType DeclType = Context.getTypeDeclType(RD); 7349 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7350 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7351 7352 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7353 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7354 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7355 HadError = true; 7356 } 7357 7358 // A defaulted special member cannot have cv-qualifiers. 7359 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7360 if (DeleteOnTypeMismatch) 7361 ShouldDeleteForTypeMismatch = true; 7362 else { 7363 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7364 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7365 HadError = true; 7366 } 7367 } 7368 } 7369 7370 // Check for parameter type matching. 7371 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7372 bool HasConstParam = false; 7373 if (ExpectedParams && ArgType->isReferenceType()) { 7374 // Argument must be reference to possibly-const T. 7375 QualType ReferentType = ArgType->getPointeeType(); 7376 HasConstParam = ReferentType.isConstQualified(); 7377 7378 if (ReferentType.isVolatileQualified()) { 7379 if (DeleteOnTypeMismatch) 7380 ShouldDeleteForTypeMismatch = true; 7381 else { 7382 Diag(MD->getLocation(), 7383 diag::err_defaulted_special_member_volatile_param) << CSM; 7384 HadError = true; 7385 } 7386 } 7387 7388 if (HasConstParam && !CanHaveConstParam) { 7389 if (DeleteOnTypeMismatch) 7390 ShouldDeleteForTypeMismatch = true; 7391 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7392 Diag(MD->getLocation(), 7393 diag::err_defaulted_special_member_copy_const_param) 7394 << (CSM == CXXCopyAssignment); 7395 // FIXME: Explain why this special member can't be const. 7396 HadError = true; 7397 } else { 7398 Diag(MD->getLocation(), 7399 diag::err_defaulted_special_member_move_const_param) 7400 << (CSM == CXXMoveAssignment); 7401 HadError = true; 7402 } 7403 } 7404 } else if (ExpectedParams) { 7405 // A copy assignment operator can take its argument by value, but a 7406 // defaulted one cannot. 7407 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7408 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7409 HadError = true; 7410 } 7411 7412 // C++11 [dcl.fct.def.default]p2: 7413 // An explicitly-defaulted function may be declared constexpr only if it 7414 // would have been implicitly declared as constexpr, 7415 // Do not apply this rule to members of class templates, since core issue 1358 7416 // makes such functions always instantiate to constexpr functions. For 7417 // functions which cannot be constexpr (for non-constructors in C++11 and for 7418 // destructors in C++14 and C++17), this is checked elsewhere. 7419 // 7420 // FIXME: This should not apply if the member is deleted. 7421 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7422 HasConstParam); 7423 if ((getLangOpts().CPlusPlus20 || 7424 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7425 : isa<CXXConstructorDecl>(MD))) && 7426 MD->isConstexpr() && !Constexpr && 7427 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7428 Diag(MD->getBeginLoc(), MD->isConsteval() 7429 ? diag::err_incorrect_defaulted_consteval 7430 : diag::err_incorrect_defaulted_constexpr) 7431 << CSM; 7432 // FIXME: Explain why the special member can't be constexpr. 7433 HadError = true; 7434 } 7435 7436 if (First) { 7437 // C++2a [dcl.fct.def.default]p3: 7438 // If a function is explicitly defaulted on its first declaration, it is 7439 // implicitly considered to be constexpr if the implicit declaration 7440 // would be. 7441 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7442 ? ConstexprSpecKind::Consteval 7443 : ConstexprSpecKind::Constexpr) 7444 : ConstexprSpecKind::Unspecified); 7445 7446 if (!Type->hasExceptionSpec()) { 7447 // C++2a [except.spec]p3: 7448 // If a declaration of a function does not have a noexcept-specifier 7449 // [and] is defaulted on its first declaration, [...] the exception 7450 // specification is as specified below 7451 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7452 EPI.ExceptionSpec.Type = EST_Unevaluated; 7453 EPI.ExceptionSpec.SourceDecl = MD; 7454 MD->setType(Context.getFunctionType(ReturnType, 7455 llvm::makeArrayRef(&ArgType, 7456 ExpectedParams), 7457 EPI)); 7458 } 7459 } 7460 7461 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7462 if (First) { 7463 SetDeclDeleted(MD, MD->getLocation()); 7464 if (!inTemplateInstantiation() && !HadError) { 7465 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7466 if (ShouldDeleteForTypeMismatch) { 7467 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7468 } else { 7469 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7470 } 7471 } 7472 if (ShouldDeleteForTypeMismatch && !HadError) { 7473 Diag(MD->getLocation(), 7474 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7475 } 7476 } else { 7477 // C++11 [dcl.fct.def.default]p4: 7478 // [For a] user-provided explicitly-defaulted function [...] if such a 7479 // function is implicitly defined as deleted, the program is ill-formed. 7480 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7481 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7482 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7483 HadError = true; 7484 } 7485 } 7486 7487 return HadError; 7488 } 7489 7490 namespace { 7491 /// Helper class for building and checking a defaulted comparison. 7492 /// 7493 /// Defaulted functions are built in two phases: 7494 /// 7495 /// * First, the set of operations that the function will perform are 7496 /// identified, and some of them are checked. If any of the checked 7497 /// operations is invalid in certain ways, the comparison function is 7498 /// defined as deleted and no body is built. 7499 /// * Then, if the function is not defined as deleted, the body is built. 7500 /// 7501 /// This is accomplished by performing two visitation steps over the eventual 7502 /// body of the function. 7503 template<typename Derived, typename ResultList, typename Result, 7504 typename Subobject> 7505 class DefaultedComparisonVisitor { 7506 public: 7507 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7508 7509 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7510 DefaultedComparisonKind DCK) 7511 : S(S), RD(RD), FD(FD), DCK(DCK) { 7512 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7513 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7514 // UnresolvedSet to avoid this copy. 7515 Fns.assign(Info->getUnqualifiedLookups().begin(), 7516 Info->getUnqualifiedLookups().end()); 7517 } 7518 } 7519 7520 ResultList visit() { 7521 // The type of an lvalue naming a parameter of this function. 7522 QualType ParamLvalType = 7523 FD->getParamDecl(0)->getType().getNonReferenceType(); 7524 7525 ResultList Results; 7526 7527 switch (DCK) { 7528 case DefaultedComparisonKind::None: 7529 llvm_unreachable("not a defaulted comparison"); 7530 7531 case DefaultedComparisonKind::Equal: 7532 case DefaultedComparisonKind::ThreeWay: 7533 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7534 return Results; 7535 7536 case DefaultedComparisonKind::NotEqual: 7537 case DefaultedComparisonKind::Relational: 7538 Results.add(getDerived().visitExpandedSubobject( 7539 ParamLvalType, getDerived().getCompleteObject())); 7540 return Results; 7541 } 7542 llvm_unreachable(""); 7543 } 7544 7545 protected: 7546 Derived &getDerived() { return static_cast<Derived&>(*this); } 7547 7548 /// Visit the expanded list of subobjects of the given type, as specified in 7549 /// C++2a [class.compare.default]. 7550 /// 7551 /// \return \c true if the ResultList object said we're done, \c false if not. 7552 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7553 Qualifiers Quals) { 7554 // C++2a [class.compare.default]p4: 7555 // The direct base class subobjects of C 7556 for (CXXBaseSpecifier &Base : Record->bases()) 7557 if (Results.add(getDerived().visitSubobject( 7558 S.Context.getQualifiedType(Base.getType(), Quals), 7559 getDerived().getBase(&Base)))) 7560 return true; 7561 7562 // followed by the non-static data members of C 7563 for (FieldDecl *Field : Record->fields()) { 7564 // Recursively expand anonymous structs. 7565 if (Field->isAnonymousStructOrUnion()) { 7566 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7567 Quals)) 7568 return true; 7569 continue; 7570 } 7571 7572 // Figure out the type of an lvalue denoting this field. 7573 Qualifiers FieldQuals = Quals; 7574 if (Field->isMutable()) 7575 FieldQuals.removeConst(); 7576 QualType FieldType = 7577 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7578 7579 if (Results.add(getDerived().visitSubobject( 7580 FieldType, getDerived().getField(Field)))) 7581 return true; 7582 } 7583 7584 // form a list of subobjects. 7585 return false; 7586 } 7587 7588 Result visitSubobject(QualType Type, Subobject Subobj) { 7589 // In that list, any subobject of array type is recursively expanded 7590 const ArrayType *AT = S.Context.getAsArrayType(Type); 7591 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7592 return getDerived().visitSubobjectArray(CAT->getElementType(), 7593 CAT->getSize(), Subobj); 7594 return getDerived().visitExpandedSubobject(Type, Subobj); 7595 } 7596 7597 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7598 Subobject Subobj) { 7599 return getDerived().visitSubobject(Type, Subobj); 7600 } 7601 7602 protected: 7603 Sema &S; 7604 CXXRecordDecl *RD; 7605 FunctionDecl *FD; 7606 DefaultedComparisonKind DCK; 7607 UnresolvedSet<16> Fns; 7608 }; 7609 7610 /// Information about a defaulted comparison, as determined by 7611 /// DefaultedComparisonAnalyzer. 7612 struct DefaultedComparisonInfo { 7613 bool Deleted = false; 7614 bool Constexpr = true; 7615 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7616 7617 static DefaultedComparisonInfo deleted() { 7618 DefaultedComparisonInfo Deleted; 7619 Deleted.Deleted = true; 7620 return Deleted; 7621 } 7622 7623 bool add(const DefaultedComparisonInfo &R) { 7624 Deleted |= R.Deleted; 7625 Constexpr &= R.Constexpr; 7626 Category = commonComparisonType(Category, R.Category); 7627 return Deleted; 7628 } 7629 }; 7630 7631 /// An element in the expanded list of subobjects of a defaulted comparison, as 7632 /// specified in C++2a [class.compare.default]p4. 7633 struct DefaultedComparisonSubobject { 7634 enum { CompleteObject, Member, Base } Kind; 7635 NamedDecl *Decl; 7636 SourceLocation Loc; 7637 }; 7638 7639 /// A visitor over the notional body of a defaulted comparison that determines 7640 /// whether that body would be deleted or constexpr. 7641 class DefaultedComparisonAnalyzer 7642 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7643 DefaultedComparisonInfo, 7644 DefaultedComparisonInfo, 7645 DefaultedComparisonSubobject> { 7646 public: 7647 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7648 7649 private: 7650 DiagnosticKind Diagnose; 7651 7652 public: 7653 using Base = DefaultedComparisonVisitor; 7654 using Result = DefaultedComparisonInfo; 7655 using Subobject = DefaultedComparisonSubobject; 7656 7657 friend Base; 7658 7659 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7660 DefaultedComparisonKind DCK, 7661 DiagnosticKind Diagnose = NoDiagnostics) 7662 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7663 7664 Result visit() { 7665 if ((DCK == DefaultedComparisonKind::Equal || 7666 DCK == DefaultedComparisonKind::ThreeWay) && 7667 RD->hasVariantMembers()) { 7668 // C++2a [class.compare.default]p2 [P2002R0]: 7669 // A defaulted comparison operator function for class C is defined as 7670 // deleted if [...] C has variant members. 7671 if (Diagnose == ExplainDeleted) { 7672 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7673 << FD << RD->isUnion() << RD; 7674 } 7675 return Result::deleted(); 7676 } 7677 7678 return Base::visit(); 7679 } 7680 7681 private: 7682 Subobject getCompleteObject() { 7683 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7684 } 7685 7686 Subobject getBase(CXXBaseSpecifier *Base) { 7687 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7688 Base->getBaseTypeLoc()}; 7689 } 7690 7691 Subobject getField(FieldDecl *Field) { 7692 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7693 } 7694 7695 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7696 // C++2a [class.compare.default]p2 [P2002R0]: 7697 // A defaulted <=> or == operator function for class C is defined as 7698 // deleted if any non-static data member of C is of reference type 7699 if (Type->isReferenceType()) { 7700 if (Diagnose == ExplainDeleted) { 7701 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7702 << FD << RD; 7703 } 7704 return Result::deleted(); 7705 } 7706 7707 // [...] Let xi be an lvalue denoting the ith element [...] 7708 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7709 Expr *Args[] = {&Xi, &Xi}; 7710 7711 // All operators start by trying to apply that same operator recursively. 7712 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7713 assert(OO != OO_None && "not an overloaded operator!"); 7714 return visitBinaryOperator(OO, Args, Subobj); 7715 } 7716 7717 Result 7718 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7719 Subobject Subobj, 7720 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7721 // Note that there is no need to consider rewritten candidates here if 7722 // we've already found there is no viable 'operator<=>' candidate (and are 7723 // considering synthesizing a '<=>' from '==' and '<'). 7724 OverloadCandidateSet CandidateSet( 7725 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7726 OverloadCandidateSet::OperatorRewriteInfo( 7727 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7728 7729 /// C++2a [class.compare.default]p1 [P2002R0]: 7730 /// [...] the defaulted function itself is never a candidate for overload 7731 /// resolution [...] 7732 CandidateSet.exclude(FD); 7733 7734 if (Args[0]->getType()->isOverloadableType()) 7735 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7736 else if (OO == OO_EqualEqual || 7737 !Args[0]->getType()->isFunctionPointerType()) { 7738 // FIXME: We determine whether this is a valid expression by checking to 7739 // see if there's a viable builtin operator candidate for it. That isn't 7740 // really what the rules ask us to do, but should give the right results. 7741 // 7742 // Note that the builtin operator for relational comparisons on function 7743 // pointers is the only known case which cannot be used. 7744 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7745 } 7746 7747 Result R; 7748 7749 OverloadCandidateSet::iterator Best; 7750 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7751 case OR_Success: { 7752 // C++2a [class.compare.secondary]p2 [P2002R0]: 7753 // The operator function [...] is defined as deleted if [...] the 7754 // candidate selected by overload resolution is not a rewritten 7755 // candidate. 7756 if ((DCK == DefaultedComparisonKind::NotEqual || 7757 DCK == DefaultedComparisonKind::Relational) && 7758 !Best->RewriteKind) { 7759 if (Diagnose == ExplainDeleted) { 7760 S.Diag(Best->Function->getLocation(), 7761 diag::note_defaulted_comparison_not_rewritten_callee) 7762 << FD; 7763 } 7764 return Result::deleted(); 7765 } 7766 7767 // Throughout C++2a [class.compare]: if overload resolution does not 7768 // result in a usable function, the candidate function is defined as 7769 // deleted. This requires that we selected an accessible function. 7770 // 7771 // Note that this only considers the access of the function when named 7772 // within the type of the subobject, and not the access path for any 7773 // derived-to-base conversion. 7774 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7775 if (ArgClass && Best->FoundDecl.getDecl() && 7776 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7777 QualType ObjectType = Subobj.Kind == Subobject::Member 7778 ? Args[0]->getType() 7779 : S.Context.getRecordType(RD); 7780 if (!S.isMemberAccessibleForDeletion( 7781 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7782 Diagnose == ExplainDeleted 7783 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7784 << FD << Subobj.Kind << Subobj.Decl 7785 : S.PDiag())) 7786 return Result::deleted(); 7787 } 7788 7789 // C++2a [class.compare.default]p3 [P2002R0]: 7790 // A defaulted comparison function is constexpr-compatible if [...] 7791 // no overlod resolution performed [...] results in a non-constexpr 7792 // function. 7793 if (FunctionDecl *BestFD = Best->Function) { 7794 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7795 // If it's not constexpr, explain why not. 7796 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7797 if (Subobj.Kind != Subobject::CompleteObject) 7798 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7799 << Subobj.Kind << Subobj.Decl; 7800 S.Diag(BestFD->getLocation(), 7801 diag::note_defaulted_comparison_not_constexpr_here); 7802 // Bail out after explaining; we don't want any more notes. 7803 return Result::deleted(); 7804 } 7805 R.Constexpr &= BestFD->isConstexpr(); 7806 } 7807 7808 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7809 if (auto *BestFD = Best->Function) { 7810 // If any callee has an undeduced return type, deduce it now. 7811 // FIXME: It's not clear how a failure here should be handled. For 7812 // now, we produce an eager diagnostic, because that is forward 7813 // compatible with most (all?) other reasonable options. 7814 if (BestFD->getReturnType()->isUndeducedType() && 7815 S.DeduceReturnType(BestFD, FD->getLocation(), 7816 /*Diagnose=*/false)) { 7817 // Don't produce a duplicate error when asked to explain why the 7818 // comparison is deleted: we diagnosed that when initially checking 7819 // the defaulted operator. 7820 if (Diagnose == NoDiagnostics) { 7821 S.Diag( 7822 FD->getLocation(), 7823 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7824 << Subobj.Kind << Subobj.Decl; 7825 S.Diag( 7826 Subobj.Loc, 7827 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7828 << Subobj.Kind << Subobj.Decl; 7829 S.Diag(BestFD->getLocation(), 7830 diag::note_defaulted_comparison_cannot_deduce_callee) 7831 << Subobj.Kind << Subobj.Decl; 7832 } 7833 return Result::deleted(); 7834 } 7835 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7836 BestFD->getCallResultType())) { 7837 R.Category = Info->Kind; 7838 } else { 7839 if (Diagnose == ExplainDeleted) { 7840 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7841 << Subobj.Kind << Subobj.Decl 7842 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7843 S.Diag(BestFD->getLocation(), 7844 diag::note_defaulted_comparison_cannot_deduce_callee) 7845 << Subobj.Kind << Subobj.Decl; 7846 } 7847 return Result::deleted(); 7848 } 7849 } else { 7850 Optional<ComparisonCategoryType> Cat = 7851 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7852 assert(Cat && "no category for builtin comparison?"); 7853 R.Category = *Cat; 7854 } 7855 } 7856 7857 // Note that we might be rewriting to a different operator. That call is 7858 // not considered until we come to actually build the comparison function. 7859 break; 7860 } 7861 7862 case OR_Ambiguous: 7863 if (Diagnose == ExplainDeleted) { 7864 unsigned Kind = 0; 7865 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7866 Kind = OO == OO_EqualEqual ? 1 : 2; 7867 CandidateSet.NoteCandidates( 7868 PartialDiagnosticAt( 7869 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7870 << FD << Kind << Subobj.Kind << Subobj.Decl), 7871 S, OCD_AmbiguousCandidates, Args); 7872 } 7873 R = Result::deleted(); 7874 break; 7875 7876 case OR_Deleted: 7877 if (Diagnose == ExplainDeleted) { 7878 if ((DCK == DefaultedComparisonKind::NotEqual || 7879 DCK == DefaultedComparisonKind::Relational) && 7880 !Best->RewriteKind) { 7881 S.Diag(Best->Function->getLocation(), 7882 diag::note_defaulted_comparison_not_rewritten_callee) 7883 << FD; 7884 } else { 7885 S.Diag(Subobj.Loc, 7886 diag::note_defaulted_comparison_calls_deleted) 7887 << FD << Subobj.Kind << Subobj.Decl; 7888 S.NoteDeletedFunction(Best->Function); 7889 } 7890 } 7891 R = Result::deleted(); 7892 break; 7893 7894 case OR_No_Viable_Function: 7895 // If there's no usable candidate, we're done unless we can rewrite a 7896 // '<=>' in terms of '==' and '<'. 7897 if (OO == OO_Spaceship && 7898 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7899 // For any kind of comparison category return type, we need a usable 7900 // '==' and a usable '<'. 7901 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7902 &CandidateSet))) 7903 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7904 break; 7905 } 7906 7907 if (Diagnose == ExplainDeleted) { 7908 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7909 << FD << Subobj.Kind << Subobj.Decl; 7910 7911 // For a three-way comparison, list both the candidates for the 7912 // original operator and the candidates for the synthesized operator. 7913 if (SpaceshipCandidates) { 7914 SpaceshipCandidates->NoteCandidates( 7915 S, Args, 7916 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7917 Args, FD->getLocation())); 7918 S.Diag(Subobj.Loc, 7919 diag::note_defaulted_comparison_no_viable_function_synthesized) 7920 << (OO == OO_EqualEqual ? 0 : 1); 7921 } 7922 7923 CandidateSet.NoteCandidates( 7924 S, Args, 7925 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7926 FD->getLocation())); 7927 } 7928 R = Result::deleted(); 7929 break; 7930 } 7931 7932 return R; 7933 } 7934 }; 7935 7936 /// A list of statements. 7937 struct StmtListResult { 7938 bool IsInvalid = false; 7939 llvm::SmallVector<Stmt*, 16> Stmts; 7940 7941 bool add(const StmtResult &S) { 7942 IsInvalid |= S.isInvalid(); 7943 if (IsInvalid) 7944 return true; 7945 Stmts.push_back(S.get()); 7946 return false; 7947 } 7948 }; 7949 7950 /// A visitor over the notional body of a defaulted comparison that synthesizes 7951 /// the actual body. 7952 class DefaultedComparisonSynthesizer 7953 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7954 StmtListResult, StmtResult, 7955 std::pair<ExprResult, ExprResult>> { 7956 SourceLocation Loc; 7957 unsigned ArrayDepth = 0; 7958 7959 public: 7960 using Base = DefaultedComparisonVisitor; 7961 using ExprPair = std::pair<ExprResult, ExprResult>; 7962 7963 friend Base; 7964 7965 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7966 DefaultedComparisonKind DCK, 7967 SourceLocation BodyLoc) 7968 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7969 7970 /// Build a suitable function body for this defaulted comparison operator. 7971 StmtResult build() { 7972 Sema::CompoundScopeRAII CompoundScope(S); 7973 7974 StmtListResult Stmts = visit(); 7975 if (Stmts.IsInvalid) 7976 return StmtError(); 7977 7978 ExprResult RetVal; 7979 switch (DCK) { 7980 case DefaultedComparisonKind::None: 7981 llvm_unreachable("not a defaulted comparison"); 7982 7983 case DefaultedComparisonKind::Equal: { 7984 // C++2a [class.eq]p3: 7985 // [...] compar[e] the corresponding elements [...] until the first 7986 // index i where xi == yi yields [...] false. If no such index exists, 7987 // V is true. Otherwise, V is false. 7988 // 7989 // Join the comparisons with '&&'s and return the result. Use a right 7990 // fold (traversing the conditions right-to-left), because that 7991 // short-circuits more naturally. 7992 auto OldStmts = std::move(Stmts.Stmts); 7993 Stmts.Stmts.clear(); 7994 ExprResult CmpSoFar; 7995 // Finish a particular comparison chain. 7996 auto FinishCmp = [&] { 7997 if (Expr *Prior = CmpSoFar.get()) { 7998 // Convert the last expression to 'return ...;' 7999 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8000 RetVal = CmpSoFar; 8001 // Convert any prior comparison to 'if (!(...)) return false;' 8002 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8003 return true; 8004 CmpSoFar = ExprResult(); 8005 } 8006 return false; 8007 }; 8008 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8009 Expr *E = dyn_cast<Expr>(EAsStmt); 8010 if (!E) { 8011 // Found an array comparison. 8012 if (FinishCmp() || Stmts.add(EAsStmt)) 8013 return StmtError(); 8014 continue; 8015 } 8016 8017 if (CmpSoFar.isUnset()) { 8018 CmpSoFar = E; 8019 continue; 8020 } 8021 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8022 if (CmpSoFar.isInvalid()) 8023 return StmtError(); 8024 } 8025 if (FinishCmp()) 8026 return StmtError(); 8027 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8028 // If no such index exists, V is true. 8029 if (RetVal.isUnset()) 8030 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8031 break; 8032 } 8033 8034 case DefaultedComparisonKind::ThreeWay: { 8035 // Per C++2a [class.spaceship]p3, as a fallback add: 8036 // return static_cast<R>(std::strong_ordering::equal); 8037 QualType StrongOrdering = S.CheckComparisonCategoryType( 8038 ComparisonCategoryType::StrongOrdering, Loc, 8039 Sema::ComparisonCategoryUsage::DefaultedOperator); 8040 if (StrongOrdering.isNull()) 8041 return StmtError(); 8042 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8043 .getValueInfo(ComparisonCategoryResult::Equal) 8044 ->VD; 8045 RetVal = getDecl(EqualVD); 8046 if (RetVal.isInvalid()) 8047 return StmtError(); 8048 RetVal = buildStaticCastToR(RetVal.get()); 8049 break; 8050 } 8051 8052 case DefaultedComparisonKind::NotEqual: 8053 case DefaultedComparisonKind::Relational: 8054 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8055 break; 8056 } 8057 8058 // Build the final return statement. 8059 if (RetVal.isInvalid()) 8060 return StmtError(); 8061 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8062 if (ReturnStmt.isInvalid()) 8063 return StmtError(); 8064 Stmts.Stmts.push_back(ReturnStmt.get()); 8065 8066 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8067 } 8068 8069 private: 8070 ExprResult getDecl(ValueDecl *VD) { 8071 return S.BuildDeclarationNameExpr( 8072 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8073 } 8074 8075 ExprResult getParam(unsigned I) { 8076 ParmVarDecl *PD = FD->getParamDecl(I); 8077 return getDecl(PD); 8078 } 8079 8080 ExprPair getCompleteObject() { 8081 unsigned Param = 0; 8082 ExprResult LHS; 8083 if (isa<CXXMethodDecl>(FD)) { 8084 // LHS is '*this'. 8085 LHS = S.ActOnCXXThis(Loc); 8086 if (!LHS.isInvalid()) 8087 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8088 } else { 8089 LHS = getParam(Param++); 8090 } 8091 ExprResult RHS = getParam(Param++); 8092 assert(Param == FD->getNumParams()); 8093 return {LHS, RHS}; 8094 } 8095 8096 ExprPair getBase(CXXBaseSpecifier *Base) { 8097 ExprPair Obj = getCompleteObject(); 8098 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8099 return {ExprError(), ExprError()}; 8100 CXXCastPath Path = {Base}; 8101 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8102 CK_DerivedToBase, VK_LValue, &Path), 8103 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8104 CK_DerivedToBase, VK_LValue, &Path)}; 8105 } 8106 8107 ExprPair getField(FieldDecl *Field) { 8108 ExprPair Obj = getCompleteObject(); 8109 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8110 return {ExprError(), ExprError()}; 8111 8112 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8113 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8114 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8115 CXXScopeSpec(), Field, Found, NameInfo), 8116 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8117 CXXScopeSpec(), Field, Found, NameInfo)}; 8118 } 8119 8120 // FIXME: When expanding a subobject, register a note in the code synthesis 8121 // stack to say which subobject we're comparing. 8122 8123 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8124 if (Cond.isInvalid()) 8125 return StmtError(); 8126 8127 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8128 if (NotCond.isInvalid()) 8129 return StmtError(); 8130 8131 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8132 assert(!False.isInvalid() && "should never fail"); 8133 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8134 if (ReturnFalse.isInvalid()) 8135 return StmtError(); 8136 8137 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8138 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8139 Sema::ConditionKind::Boolean), 8140 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8141 } 8142 8143 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8144 ExprPair Subobj) { 8145 QualType SizeType = S.Context.getSizeType(); 8146 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8147 8148 // Build 'size_t i$n = 0'. 8149 IdentifierInfo *IterationVarName = nullptr; 8150 { 8151 SmallString<8> Str; 8152 llvm::raw_svector_ostream OS(Str); 8153 OS << "i" << ArrayDepth; 8154 IterationVarName = &S.Context.Idents.get(OS.str()); 8155 } 8156 VarDecl *IterationVar = VarDecl::Create( 8157 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8158 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8159 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8160 IterationVar->setInit( 8161 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8162 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8163 8164 auto IterRef = [&] { 8165 ExprResult Ref = S.BuildDeclarationNameExpr( 8166 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8167 IterationVar); 8168 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8169 return Ref.get(); 8170 }; 8171 8172 // Build 'i$n != Size'. 8173 ExprResult Cond = S.CreateBuiltinBinOp( 8174 Loc, BO_NE, IterRef(), 8175 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8176 assert(!Cond.isInvalid() && "should never fail"); 8177 8178 // Build '++i$n'. 8179 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8180 assert(!Inc.isInvalid() && "should never fail"); 8181 8182 // Build 'a[i$n]' and 'b[i$n]'. 8183 auto Index = [&](ExprResult E) { 8184 if (E.isInvalid()) 8185 return ExprError(); 8186 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8187 }; 8188 Subobj.first = Index(Subobj.first); 8189 Subobj.second = Index(Subobj.second); 8190 8191 // Compare the array elements. 8192 ++ArrayDepth; 8193 StmtResult Substmt = visitSubobject(Type, Subobj); 8194 --ArrayDepth; 8195 8196 if (Substmt.isInvalid()) 8197 return StmtError(); 8198 8199 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8200 // For outer levels or for an 'operator<=>' we already have a suitable 8201 // statement that returns as necessary. 8202 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8203 assert(DCK == DefaultedComparisonKind::Equal && 8204 "should have non-expression statement"); 8205 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8206 if (Substmt.isInvalid()) 8207 return StmtError(); 8208 } 8209 8210 // Build 'for (...) ...' 8211 return S.ActOnForStmt(Loc, Loc, Init, 8212 S.ActOnCondition(nullptr, Loc, Cond.get(), 8213 Sema::ConditionKind::Boolean), 8214 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8215 Substmt.get()); 8216 } 8217 8218 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8219 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8220 return StmtError(); 8221 8222 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8223 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8224 ExprResult Op; 8225 if (Type->isOverloadableType()) 8226 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8227 Obj.second.get(), /*PerformADL=*/true, 8228 /*AllowRewrittenCandidates=*/true, FD); 8229 else 8230 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8231 if (Op.isInvalid()) 8232 return StmtError(); 8233 8234 switch (DCK) { 8235 case DefaultedComparisonKind::None: 8236 llvm_unreachable("not a defaulted comparison"); 8237 8238 case DefaultedComparisonKind::Equal: 8239 // Per C++2a [class.eq]p2, each comparison is individually contextually 8240 // converted to bool. 8241 Op = S.PerformContextuallyConvertToBool(Op.get()); 8242 if (Op.isInvalid()) 8243 return StmtError(); 8244 return Op.get(); 8245 8246 case DefaultedComparisonKind::ThreeWay: { 8247 // Per C++2a [class.spaceship]p3, form: 8248 // if (R cmp = static_cast<R>(op); cmp != 0) 8249 // return cmp; 8250 QualType R = FD->getReturnType(); 8251 Op = buildStaticCastToR(Op.get()); 8252 if (Op.isInvalid()) 8253 return StmtError(); 8254 8255 // R cmp = ...; 8256 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8257 VarDecl *VD = 8258 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8259 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8260 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8261 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8262 8263 // cmp != 0 8264 ExprResult VDRef = getDecl(VD); 8265 if (VDRef.isInvalid()) 8266 return StmtError(); 8267 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8268 Expr *Zero = 8269 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8270 ExprResult Comp; 8271 if (VDRef.get()->getType()->isOverloadableType()) 8272 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8273 true, FD); 8274 else 8275 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8276 if (Comp.isInvalid()) 8277 return StmtError(); 8278 Sema::ConditionResult Cond = S.ActOnCondition( 8279 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8280 if (Cond.isInvalid()) 8281 return StmtError(); 8282 8283 // return cmp; 8284 VDRef = getDecl(VD); 8285 if (VDRef.isInvalid()) 8286 return StmtError(); 8287 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8288 if (ReturnStmt.isInvalid()) 8289 return StmtError(); 8290 8291 // if (...) 8292 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8293 ReturnStmt.get(), 8294 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8295 } 8296 8297 case DefaultedComparisonKind::NotEqual: 8298 case DefaultedComparisonKind::Relational: 8299 // C++2a [class.compare.secondary]p2: 8300 // Otherwise, the operator function yields x @ y. 8301 return Op.get(); 8302 } 8303 llvm_unreachable(""); 8304 } 8305 8306 /// Build "static_cast<R>(E)". 8307 ExprResult buildStaticCastToR(Expr *E) { 8308 QualType R = FD->getReturnType(); 8309 assert(!R->isUndeducedType() && "type should have been deduced already"); 8310 8311 // Don't bother forming a no-op cast in the common case. 8312 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8313 return E; 8314 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8315 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8316 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8317 } 8318 }; 8319 } 8320 8321 /// Perform the unqualified lookups that might be needed to form a defaulted 8322 /// comparison function for the given operator. 8323 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8324 UnresolvedSetImpl &Operators, 8325 OverloadedOperatorKind Op) { 8326 auto Lookup = [&](OverloadedOperatorKind OO) { 8327 Self.LookupOverloadedOperatorName(OO, S, Operators); 8328 }; 8329 8330 // Every defaulted operator looks up itself. 8331 Lookup(Op); 8332 // ... and the rewritten form of itself, if any. 8333 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8334 Lookup(ExtraOp); 8335 8336 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8337 // synthesize a three-way comparison from '<' and '=='. In a dependent 8338 // context, we also need to look up '==' in case we implicitly declare a 8339 // defaulted 'operator=='. 8340 if (Op == OO_Spaceship) { 8341 Lookup(OO_ExclaimEqual); 8342 Lookup(OO_Less); 8343 Lookup(OO_EqualEqual); 8344 } 8345 } 8346 8347 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8348 DefaultedComparisonKind DCK) { 8349 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8350 8351 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8352 assert(RD && "defaulted comparison is not defaulted in a class"); 8353 8354 // Perform any unqualified lookups we're going to need to default this 8355 // function. 8356 if (S) { 8357 UnresolvedSet<32> Operators; 8358 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8359 FD->getOverloadedOperator()); 8360 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8361 Context, Operators.pairs())); 8362 } 8363 8364 // C++2a [class.compare.default]p1: 8365 // A defaulted comparison operator function for some class C shall be a 8366 // non-template function declared in the member-specification of C that is 8367 // -- a non-static const member of C having one parameter of type 8368 // const C&, or 8369 // -- a friend of C having two parameters of type const C& or two 8370 // parameters of type C. 8371 QualType ExpectedParmType1 = Context.getRecordType(RD); 8372 QualType ExpectedParmType2 = 8373 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8374 if (isa<CXXMethodDecl>(FD)) 8375 ExpectedParmType1 = ExpectedParmType2; 8376 for (const ParmVarDecl *Param : FD->parameters()) { 8377 if (!Param->getType()->isDependentType() && 8378 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8379 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8380 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8381 // corresponding defaulted 'operator<=>' already. 8382 if (!FD->isImplicit()) { 8383 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8384 << (int)DCK << Param->getType() << ExpectedParmType1 8385 << !isa<CXXMethodDecl>(FD) 8386 << ExpectedParmType2 << Param->getSourceRange(); 8387 } 8388 return true; 8389 } 8390 } 8391 if (FD->getNumParams() == 2 && 8392 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8393 FD->getParamDecl(1)->getType())) { 8394 if (!FD->isImplicit()) { 8395 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8396 << (int)DCK 8397 << FD->getParamDecl(0)->getType() 8398 << FD->getParamDecl(0)->getSourceRange() 8399 << FD->getParamDecl(1)->getType() 8400 << FD->getParamDecl(1)->getSourceRange(); 8401 } 8402 return true; 8403 } 8404 8405 // ... non-static const member ... 8406 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8407 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8408 if (!MD->isConst()) { 8409 SourceLocation InsertLoc; 8410 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8411 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8412 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8413 // corresponding defaulted 'operator<=>' already. 8414 if (!MD->isImplicit()) { 8415 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8416 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8417 } 8418 8419 // Add the 'const' to the type to recover. 8420 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8421 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8422 EPI.TypeQuals.addConst(); 8423 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8424 FPT->getParamTypes(), EPI)); 8425 } 8426 } else { 8427 // A non-member function declared in a class must be a friend. 8428 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8429 } 8430 8431 // C++2a [class.eq]p1, [class.rel]p1: 8432 // A [defaulted comparison other than <=>] shall have a declared return 8433 // type bool. 8434 if (DCK != DefaultedComparisonKind::ThreeWay && 8435 !FD->getDeclaredReturnType()->isDependentType() && 8436 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8437 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8438 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8439 << FD->getReturnTypeSourceRange(); 8440 return true; 8441 } 8442 // C++2a [class.spaceship]p2 [P2002R0]: 8443 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8444 // R shall not contain a placeholder type. 8445 if (DCK == DefaultedComparisonKind::ThreeWay && 8446 FD->getDeclaredReturnType()->getContainedDeducedType() && 8447 !Context.hasSameType(FD->getDeclaredReturnType(), 8448 Context.getAutoDeductType())) { 8449 Diag(FD->getLocation(), 8450 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8451 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8452 << FD->getReturnTypeSourceRange(); 8453 return true; 8454 } 8455 8456 // For a defaulted function in a dependent class, defer all remaining checks 8457 // until instantiation. 8458 if (RD->isDependentType()) 8459 return false; 8460 8461 // Determine whether the function should be defined as deleted. 8462 DefaultedComparisonInfo Info = 8463 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8464 8465 bool First = FD == FD->getCanonicalDecl(); 8466 8467 // If we want to delete the function, then do so; there's nothing else to 8468 // check in that case. 8469 if (Info.Deleted) { 8470 if (!First) { 8471 // C++11 [dcl.fct.def.default]p4: 8472 // [For a] user-provided explicitly-defaulted function [...] if such a 8473 // function is implicitly defined as deleted, the program is ill-formed. 8474 // 8475 // This is really just a consequence of the general rule that you can 8476 // only delete a function on its first declaration. 8477 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8478 << FD->isImplicit() << (int)DCK; 8479 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8480 DefaultedComparisonAnalyzer::ExplainDeleted) 8481 .visit(); 8482 return true; 8483 } 8484 8485 SetDeclDeleted(FD, FD->getLocation()); 8486 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8487 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8488 << (int)DCK; 8489 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8490 DefaultedComparisonAnalyzer::ExplainDeleted) 8491 .visit(); 8492 } 8493 return false; 8494 } 8495 8496 // C++2a [class.spaceship]p2: 8497 // The return type is deduced as the common comparison type of R0, R1, ... 8498 if (DCK == DefaultedComparisonKind::ThreeWay && 8499 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8500 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8501 if (RetLoc.isInvalid()) 8502 RetLoc = FD->getBeginLoc(); 8503 // FIXME: Should we really care whether we have the complete type and the 8504 // 'enumerator' constants here? A forward declaration seems sufficient. 8505 QualType Cat = CheckComparisonCategoryType( 8506 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8507 if (Cat.isNull()) 8508 return true; 8509 Context.adjustDeducedFunctionResultType( 8510 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8511 } 8512 8513 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8514 // An explicitly-defaulted function that is not defined as deleted may be 8515 // declared constexpr or consteval only if it is constexpr-compatible. 8516 // C++2a [class.compare.default]p3 [P2002R0]: 8517 // A defaulted comparison function is constexpr-compatible if it satisfies 8518 // the requirements for a constexpr function [...] 8519 // The only relevant requirements are that the parameter and return types are 8520 // literal types. The remaining conditions are checked by the analyzer. 8521 if (FD->isConstexpr()) { 8522 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8523 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8524 !Info.Constexpr) { 8525 Diag(FD->getBeginLoc(), 8526 diag::err_incorrect_defaulted_comparison_constexpr) 8527 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8528 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8529 DefaultedComparisonAnalyzer::ExplainConstexpr) 8530 .visit(); 8531 } 8532 } 8533 8534 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8535 // If a constexpr-compatible function is explicitly defaulted on its first 8536 // declaration, it is implicitly considered to be constexpr. 8537 // FIXME: Only applying this to the first declaration seems problematic, as 8538 // simple reorderings can affect the meaning of the program. 8539 if (First && !FD->isConstexpr() && Info.Constexpr) 8540 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8541 8542 // C++2a [except.spec]p3: 8543 // If a declaration of a function does not have a noexcept-specifier 8544 // [and] is defaulted on its first declaration, [...] the exception 8545 // specification is as specified below 8546 if (FD->getExceptionSpecType() == EST_None) { 8547 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8548 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8549 EPI.ExceptionSpec.Type = EST_Unevaluated; 8550 EPI.ExceptionSpec.SourceDecl = FD; 8551 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8552 FPT->getParamTypes(), EPI)); 8553 } 8554 8555 return false; 8556 } 8557 8558 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8559 FunctionDecl *Spaceship) { 8560 Sema::CodeSynthesisContext Ctx; 8561 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8562 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8563 Ctx.Entity = Spaceship; 8564 pushCodeSynthesisContext(Ctx); 8565 8566 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8567 EqualEqual->setImplicit(); 8568 8569 popCodeSynthesisContext(); 8570 } 8571 8572 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8573 DefaultedComparisonKind DCK) { 8574 assert(FD->isDefaulted() && !FD->isDeleted() && 8575 !FD->doesThisDeclarationHaveABody()); 8576 if (FD->willHaveBody() || FD->isInvalidDecl()) 8577 return; 8578 8579 SynthesizedFunctionScope Scope(*this, FD); 8580 8581 // Add a context note for diagnostics produced after this point. 8582 Scope.addContextNote(UseLoc); 8583 8584 { 8585 // Build and set up the function body. 8586 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8587 SourceLocation BodyLoc = 8588 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8589 StmtResult Body = 8590 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8591 if (Body.isInvalid()) { 8592 FD->setInvalidDecl(); 8593 return; 8594 } 8595 FD->setBody(Body.get()); 8596 FD->markUsed(Context); 8597 } 8598 8599 // The exception specification is needed because we are defining the 8600 // function. Note that this will reuse the body we just built. 8601 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8602 8603 if (ASTMutationListener *L = getASTMutationListener()) 8604 L->CompletedImplicitDefinition(FD); 8605 } 8606 8607 static Sema::ImplicitExceptionSpecification 8608 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8609 FunctionDecl *FD, 8610 Sema::DefaultedComparisonKind DCK) { 8611 ComputingExceptionSpec CES(S, FD, Loc); 8612 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8613 8614 if (FD->isInvalidDecl()) 8615 return ExceptSpec; 8616 8617 // The common case is that we just defined the comparison function. In that 8618 // case, just look at whether the body can throw. 8619 if (FD->hasBody()) { 8620 ExceptSpec.CalledStmt(FD->getBody()); 8621 } else { 8622 // Otherwise, build a body so we can check it. This should ideally only 8623 // happen when we're not actually marking the function referenced. (This is 8624 // only really important for efficiency: we don't want to build and throw 8625 // away bodies for comparison functions more than we strictly need to.) 8626 8627 // Pretend to synthesize the function body in an unevaluated context. 8628 // Note that we can't actually just go ahead and define the function here: 8629 // we are not permitted to mark its callees as referenced. 8630 Sema::SynthesizedFunctionScope Scope(S, FD); 8631 EnterExpressionEvaluationContext Context( 8632 S, Sema::ExpressionEvaluationContext::Unevaluated); 8633 8634 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8635 SourceLocation BodyLoc = 8636 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8637 StmtResult Body = 8638 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8639 if (!Body.isInvalid()) 8640 ExceptSpec.CalledStmt(Body.get()); 8641 8642 // FIXME: Can we hold onto this body and just transform it to potentially 8643 // evaluated when we're asked to define the function rather than rebuilding 8644 // it? Either that, or we should only build the bits of the body that we 8645 // need (the expressions, not the statements). 8646 } 8647 8648 return ExceptSpec; 8649 } 8650 8651 void Sema::CheckDelayedMemberExceptionSpecs() { 8652 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8653 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8654 8655 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8656 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8657 8658 // Perform any deferred checking of exception specifications for virtual 8659 // destructors. 8660 for (auto &Check : Overriding) 8661 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8662 8663 // Perform any deferred checking of exception specifications for befriended 8664 // special members. 8665 for (auto &Check : Equivalent) 8666 CheckEquivalentExceptionSpec(Check.second, Check.first); 8667 } 8668 8669 namespace { 8670 /// CRTP base class for visiting operations performed by a special member 8671 /// function (or inherited constructor). 8672 template<typename Derived> 8673 struct SpecialMemberVisitor { 8674 Sema &S; 8675 CXXMethodDecl *MD; 8676 Sema::CXXSpecialMember CSM; 8677 Sema::InheritedConstructorInfo *ICI; 8678 8679 // Properties of the special member, computed for convenience. 8680 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8681 8682 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8683 Sema::InheritedConstructorInfo *ICI) 8684 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8685 switch (CSM) { 8686 case Sema::CXXDefaultConstructor: 8687 case Sema::CXXCopyConstructor: 8688 case Sema::CXXMoveConstructor: 8689 IsConstructor = true; 8690 break; 8691 case Sema::CXXCopyAssignment: 8692 case Sema::CXXMoveAssignment: 8693 IsAssignment = true; 8694 break; 8695 case Sema::CXXDestructor: 8696 break; 8697 case Sema::CXXInvalid: 8698 llvm_unreachable("invalid special member kind"); 8699 } 8700 8701 if (MD->getNumParams()) { 8702 if (const ReferenceType *RT = 8703 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8704 ConstArg = RT->getPointeeType().isConstQualified(); 8705 } 8706 } 8707 8708 Derived &getDerived() { return static_cast<Derived&>(*this); } 8709 8710 /// Is this a "move" special member? 8711 bool isMove() const { 8712 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8713 } 8714 8715 /// Look up the corresponding special member in the given class. 8716 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8717 unsigned Quals, bool IsMutable) { 8718 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8719 ConstArg && !IsMutable); 8720 } 8721 8722 /// Look up the constructor for the specified base class to see if it's 8723 /// overridden due to this being an inherited constructor. 8724 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8725 if (!ICI) 8726 return {}; 8727 assert(CSM == Sema::CXXDefaultConstructor); 8728 auto *BaseCtor = 8729 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8730 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8731 return MD; 8732 return {}; 8733 } 8734 8735 /// A base or member subobject. 8736 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8737 8738 /// Get the location to use for a subobject in diagnostics. 8739 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8740 // FIXME: For an indirect virtual base, the direct base leading to 8741 // the indirect virtual base would be a more useful choice. 8742 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8743 return B->getBaseTypeLoc(); 8744 else 8745 return Subobj.get<FieldDecl*>()->getLocation(); 8746 } 8747 8748 enum BasesToVisit { 8749 /// Visit all non-virtual (direct) bases. 8750 VisitNonVirtualBases, 8751 /// Visit all direct bases, virtual or not. 8752 VisitDirectBases, 8753 /// Visit all non-virtual bases, and all virtual bases if the class 8754 /// is not abstract. 8755 VisitPotentiallyConstructedBases, 8756 /// Visit all direct or virtual bases. 8757 VisitAllBases 8758 }; 8759 8760 // Visit the bases and members of the class. 8761 bool visit(BasesToVisit Bases) { 8762 CXXRecordDecl *RD = MD->getParent(); 8763 8764 if (Bases == VisitPotentiallyConstructedBases) 8765 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8766 8767 for (auto &B : RD->bases()) 8768 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8769 getDerived().visitBase(&B)) 8770 return true; 8771 8772 if (Bases == VisitAllBases) 8773 for (auto &B : RD->vbases()) 8774 if (getDerived().visitBase(&B)) 8775 return true; 8776 8777 for (auto *F : RD->fields()) 8778 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8779 getDerived().visitField(F)) 8780 return true; 8781 8782 return false; 8783 } 8784 }; 8785 } 8786 8787 namespace { 8788 struct SpecialMemberDeletionInfo 8789 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8790 bool Diagnose; 8791 8792 SourceLocation Loc; 8793 8794 bool AllFieldsAreConst; 8795 8796 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8797 Sema::CXXSpecialMember CSM, 8798 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8799 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8800 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8801 8802 bool inUnion() const { return MD->getParent()->isUnion(); } 8803 8804 Sema::CXXSpecialMember getEffectiveCSM() { 8805 return ICI ? Sema::CXXInvalid : CSM; 8806 } 8807 8808 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8809 8810 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8811 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8812 8813 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8814 bool shouldDeleteForField(FieldDecl *FD); 8815 bool shouldDeleteForAllConstMembers(); 8816 8817 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8818 unsigned Quals); 8819 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8820 Sema::SpecialMemberOverloadResult SMOR, 8821 bool IsDtorCallInCtor); 8822 8823 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8824 }; 8825 } 8826 8827 /// Is the given special member inaccessible when used on the given 8828 /// sub-object. 8829 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8830 CXXMethodDecl *target) { 8831 /// If we're operating on a base class, the object type is the 8832 /// type of this special member. 8833 QualType objectTy; 8834 AccessSpecifier access = target->getAccess(); 8835 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8836 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8837 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8838 8839 // If we're operating on a field, the object type is the type of the field. 8840 } else { 8841 objectTy = S.Context.getTypeDeclType(target->getParent()); 8842 } 8843 8844 return S.isMemberAccessibleForDeletion( 8845 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8846 } 8847 8848 /// Check whether we should delete a special member due to the implicit 8849 /// definition containing a call to a special member of a subobject. 8850 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8851 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8852 bool IsDtorCallInCtor) { 8853 CXXMethodDecl *Decl = SMOR.getMethod(); 8854 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8855 8856 int DiagKind = -1; 8857 8858 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8859 DiagKind = !Decl ? 0 : 1; 8860 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8861 DiagKind = 2; 8862 else if (!isAccessible(Subobj, Decl)) 8863 DiagKind = 3; 8864 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8865 !Decl->isTrivial()) { 8866 // A member of a union must have a trivial corresponding special member. 8867 // As a weird special case, a destructor call from a union's constructor 8868 // must be accessible and non-deleted, but need not be trivial. Such a 8869 // destructor is never actually called, but is semantically checked as 8870 // if it were. 8871 DiagKind = 4; 8872 } 8873 8874 if (DiagKind == -1) 8875 return false; 8876 8877 if (Diagnose) { 8878 if (Field) { 8879 S.Diag(Field->getLocation(), 8880 diag::note_deleted_special_member_class_subobject) 8881 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8882 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8883 } else { 8884 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8885 S.Diag(Base->getBeginLoc(), 8886 diag::note_deleted_special_member_class_subobject) 8887 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8888 << Base->getType() << DiagKind << IsDtorCallInCtor 8889 << /*IsObjCPtr*/false; 8890 } 8891 8892 if (DiagKind == 1) 8893 S.NoteDeletedFunction(Decl); 8894 // FIXME: Explain inaccessibility if DiagKind == 3. 8895 } 8896 8897 return true; 8898 } 8899 8900 /// Check whether we should delete a special member function due to having a 8901 /// direct or virtual base class or non-static data member of class type M. 8902 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8903 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8904 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8905 bool IsMutable = Field && Field->isMutable(); 8906 8907 // C++11 [class.ctor]p5: 8908 // -- any direct or virtual base class, or non-static data member with no 8909 // brace-or-equal-initializer, has class type M (or array thereof) and 8910 // either M has no default constructor or overload resolution as applied 8911 // to M's default constructor results in an ambiguity or in a function 8912 // that is deleted or inaccessible 8913 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8914 // -- a direct or virtual base class B that cannot be copied/moved because 8915 // overload resolution, as applied to B's corresponding special member, 8916 // results in an ambiguity or a function that is deleted or inaccessible 8917 // from the defaulted special member 8918 // C++11 [class.dtor]p5: 8919 // -- any direct or virtual base class [...] has a type with a destructor 8920 // that is deleted or inaccessible 8921 if (!(CSM == Sema::CXXDefaultConstructor && 8922 Field && Field->hasInClassInitializer()) && 8923 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8924 false)) 8925 return true; 8926 8927 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8928 // -- any direct or virtual base class or non-static data member has a 8929 // type with a destructor that is deleted or inaccessible 8930 if (IsConstructor) { 8931 Sema::SpecialMemberOverloadResult SMOR = 8932 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8933 false, false, false, false, false); 8934 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8935 return true; 8936 } 8937 8938 return false; 8939 } 8940 8941 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8942 FieldDecl *FD, QualType FieldType) { 8943 // The defaulted special functions are defined as deleted if this is a variant 8944 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8945 // type under ARC. 8946 if (!FieldType.hasNonTrivialObjCLifetime()) 8947 return false; 8948 8949 // Don't make the defaulted default constructor defined as deleted if the 8950 // member has an in-class initializer. 8951 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8952 return false; 8953 8954 if (Diagnose) { 8955 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8956 S.Diag(FD->getLocation(), 8957 diag::note_deleted_special_member_class_subobject) 8958 << getEffectiveCSM() << ParentClass << /*IsField*/true 8959 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8960 } 8961 8962 return true; 8963 } 8964 8965 /// Check whether we should delete a special member function due to the class 8966 /// having a particular direct or virtual base class. 8967 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8968 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8969 // If program is correct, BaseClass cannot be null, but if it is, the error 8970 // must be reported elsewhere. 8971 if (!BaseClass) 8972 return false; 8973 // If we have an inheriting constructor, check whether we're calling an 8974 // inherited constructor instead of a default constructor. 8975 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8976 if (auto *BaseCtor = SMOR.getMethod()) { 8977 // Note that we do not check access along this path; other than that, 8978 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8979 // FIXME: Check that the base has a usable destructor! Sink this into 8980 // shouldDeleteForClassSubobject. 8981 if (BaseCtor->isDeleted() && Diagnose) { 8982 S.Diag(Base->getBeginLoc(), 8983 diag::note_deleted_special_member_class_subobject) 8984 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8985 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8986 << /*IsObjCPtr*/false; 8987 S.NoteDeletedFunction(BaseCtor); 8988 } 8989 return BaseCtor->isDeleted(); 8990 } 8991 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8992 } 8993 8994 /// Check whether we should delete a special member function due to the class 8995 /// having a particular non-static data member. 8996 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8997 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8998 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8999 9000 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9001 return true; 9002 9003 if (CSM == Sema::CXXDefaultConstructor) { 9004 // For a default constructor, all references must be initialized in-class 9005 // and, if a union, it must have a non-const member. 9006 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9007 if (Diagnose) 9008 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9009 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9010 return true; 9011 } 9012 // C++11 [class.ctor]p5: any non-variant non-static data member of 9013 // const-qualified type (or array thereof) with no 9014 // brace-or-equal-initializer does not have a user-provided default 9015 // constructor. 9016 if (!inUnion() && FieldType.isConstQualified() && 9017 !FD->hasInClassInitializer() && 9018 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9019 if (Diagnose) 9020 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9021 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9022 return true; 9023 } 9024 9025 if (inUnion() && !FieldType.isConstQualified()) 9026 AllFieldsAreConst = false; 9027 } else if (CSM == Sema::CXXCopyConstructor) { 9028 // For a copy constructor, data members must not be of rvalue reference 9029 // type. 9030 if (FieldType->isRValueReferenceType()) { 9031 if (Diagnose) 9032 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9033 << MD->getParent() << FD << FieldType; 9034 return true; 9035 } 9036 } else if (IsAssignment) { 9037 // For an assignment operator, data members must not be of reference type. 9038 if (FieldType->isReferenceType()) { 9039 if (Diagnose) 9040 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9041 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9042 return true; 9043 } 9044 if (!FieldRecord && FieldType.isConstQualified()) { 9045 // C++11 [class.copy]p23: 9046 // -- a non-static data member of const non-class type (or array thereof) 9047 if (Diagnose) 9048 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9049 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9050 return true; 9051 } 9052 } 9053 9054 if (FieldRecord) { 9055 // Some additional restrictions exist on the variant members. 9056 if (!inUnion() && FieldRecord->isUnion() && 9057 FieldRecord->isAnonymousStructOrUnion()) { 9058 bool AllVariantFieldsAreConst = true; 9059 9060 // FIXME: Handle anonymous unions declared within anonymous unions. 9061 for (auto *UI : FieldRecord->fields()) { 9062 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9063 9064 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9065 return true; 9066 9067 if (!UnionFieldType.isConstQualified()) 9068 AllVariantFieldsAreConst = false; 9069 9070 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9071 if (UnionFieldRecord && 9072 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9073 UnionFieldType.getCVRQualifiers())) 9074 return true; 9075 } 9076 9077 // At least one member in each anonymous union must be non-const 9078 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9079 !FieldRecord->field_empty()) { 9080 if (Diagnose) 9081 S.Diag(FieldRecord->getLocation(), 9082 diag::note_deleted_default_ctor_all_const) 9083 << !!ICI << MD->getParent() << /*anonymous union*/1; 9084 return true; 9085 } 9086 9087 // Don't check the implicit member of the anonymous union type. 9088 // This is technically non-conformant, but sanity demands it. 9089 return false; 9090 } 9091 9092 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9093 FieldType.getCVRQualifiers())) 9094 return true; 9095 } 9096 9097 return false; 9098 } 9099 9100 /// C++11 [class.ctor] p5: 9101 /// A defaulted default constructor for a class X is defined as deleted if 9102 /// X is a union and all of its variant members are of const-qualified type. 9103 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9104 // This is a silly definition, because it gives an empty union a deleted 9105 // default constructor. Don't do that. 9106 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9107 bool AnyFields = false; 9108 for (auto *F : MD->getParent()->fields()) 9109 if ((AnyFields = !F->isUnnamedBitfield())) 9110 break; 9111 if (!AnyFields) 9112 return false; 9113 if (Diagnose) 9114 S.Diag(MD->getParent()->getLocation(), 9115 diag::note_deleted_default_ctor_all_const) 9116 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9117 return true; 9118 } 9119 return false; 9120 } 9121 9122 /// Determine whether a defaulted special member function should be defined as 9123 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9124 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9125 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9126 InheritedConstructorInfo *ICI, 9127 bool Diagnose) { 9128 if (MD->isInvalidDecl()) 9129 return false; 9130 CXXRecordDecl *RD = MD->getParent(); 9131 assert(!RD->isDependentType() && "do deletion after instantiation"); 9132 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9133 return false; 9134 9135 // C++11 [expr.lambda.prim]p19: 9136 // The closure type associated with a lambda-expression has a 9137 // deleted (8.4.3) default constructor and a deleted copy 9138 // assignment operator. 9139 // C++2a adds back these operators if the lambda has no lambda-capture. 9140 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9141 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9142 if (Diagnose) 9143 Diag(RD->getLocation(), diag::note_lambda_decl); 9144 return true; 9145 } 9146 9147 // For an anonymous struct or union, the copy and assignment special members 9148 // will never be used, so skip the check. For an anonymous union declared at 9149 // namespace scope, the constructor and destructor are used. 9150 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9151 RD->isAnonymousStructOrUnion()) 9152 return false; 9153 9154 // C++11 [class.copy]p7, p18: 9155 // If the class definition declares a move constructor or move assignment 9156 // operator, an implicitly declared copy constructor or copy assignment 9157 // operator is defined as deleted. 9158 if (MD->isImplicit() && 9159 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9160 CXXMethodDecl *UserDeclaredMove = nullptr; 9161 9162 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9163 // deletion of the corresponding copy operation, not both copy operations. 9164 // MSVC 2015 has adopted the standards conforming behavior. 9165 bool DeletesOnlyMatchingCopy = 9166 getLangOpts().MSVCCompat && 9167 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9168 9169 if (RD->hasUserDeclaredMoveConstructor() && 9170 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9171 if (!Diagnose) return true; 9172 9173 // Find any user-declared move constructor. 9174 for (auto *I : RD->ctors()) { 9175 if (I->isMoveConstructor()) { 9176 UserDeclaredMove = I; 9177 break; 9178 } 9179 } 9180 assert(UserDeclaredMove); 9181 } else if (RD->hasUserDeclaredMoveAssignment() && 9182 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9183 if (!Diagnose) return true; 9184 9185 // Find any user-declared move assignment operator. 9186 for (auto *I : RD->methods()) { 9187 if (I->isMoveAssignmentOperator()) { 9188 UserDeclaredMove = I; 9189 break; 9190 } 9191 } 9192 assert(UserDeclaredMove); 9193 } 9194 9195 if (UserDeclaredMove) { 9196 Diag(UserDeclaredMove->getLocation(), 9197 diag::note_deleted_copy_user_declared_move) 9198 << (CSM == CXXCopyAssignment) << RD 9199 << UserDeclaredMove->isMoveAssignmentOperator(); 9200 return true; 9201 } 9202 } 9203 9204 // Do access control from the special member function 9205 ContextRAII MethodContext(*this, MD); 9206 9207 // C++11 [class.dtor]p5: 9208 // -- for a virtual destructor, lookup of the non-array deallocation function 9209 // results in an ambiguity or in a function that is deleted or inaccessible 9210 if (CSM == CXXDestructor && MD->isVirtual()) { 9211 FunctionDecl *OperatorDelete = nullptr; 9212 DeclarationName Name = 9213 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9214 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9215 OperatorDelete, /*Diagnose*/false)) { 9216 if (Diagnose) 9217 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9218 return true; 9219 } 9220 } 9221 9222 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9223 9224 // Per DR1611, do not consider virtual bases of constructors of abstract 9225 // classes, since we are not going to construct them. 9226 // Per DR1658, do not consider virtual bases of destructors of abstract 9227 // classes either. 9228 // Per DR2180, for assignment operators we only assign (and thus only 9229 // consider) direct bases. 9230 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9231 : SMI.VisitPotentiallyConstructedBases)) 9232 return true; 9233 9234 if (SMI.shouldDeleteForAllConstMembers()) 9235 return true; 9236 9237 if (getLangOpts().CUDA) { 9238 // We should delete the special member in CUDA mode if target inference 9239 // failed. 9240 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9241 // is treated as certain special member, which may not reflect what special 9242 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9243 // expects CSM to match MD, therefore recalculate CSM. 9244 assert(ICI || CSM == getSpecialMember(MD)); 9245 auto RealCSM = CSM; 9246 if (ICI) 9247 RealCSM = getSpecialMember(MD); 9248 9249 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9250 SMI.ConstArg, Diagnose); 9251 } 9252 9253 return false; 9254 } 9255 9256 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9257 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9258 assert(DFK && "not a defaultable function"); 9259 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9260 9261 if (DFK.isSpecialMember()) { 9262 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9263 nullptr, /*Diagnose=*/true); 9264 } else { 9265 DefaultedComparisonAnalyzer( 9266 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9267 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9268 .visit(); 9269 } 9270 } 9271 9272 /// Perform lookup for a special member of the specified kind, and determine 9273 /// whether it is trivial. If the triviality can be determined without the 9274 /// lookup, skip it. This is intended for use when determining whether a 9275 /// special member of a containing object is trivial, and thus does not ever 9276 /// perform overload resolution for default constructors. 9277 /// 9278 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9279 /// member that was most likely to be intended to be trivial, if any. 9280 /// 9281 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9282 /// determine whether the special member is trivial. 9283 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9284 Sema::CXXSpecialMember CSM, unsigned Quals, 9285 bool ConstRHS, 9286 Sema::TrivialABIHandling TAH, 9287 CXXMethodDecl **Selected) { 9288 if (Selected) 9289 *Selected = nullptr; 9290 9291 switch (CSM) { 9292 case Sema::CXXInvalid: 9293 llvm_unreachable("not a special member"); 9294 9295 case Sema::CXXDefaultConstructor: 9296 // C++11 [class.ctor]p5: 9297 // A default constructor is trivial if: 9298 // - all the [direct subobjects] have trivial default constructors 9299 // 9300 // Note, no overload resolution is performed in this case. 9301 if (RD->hasTrivialDefaultConstructor()) 9302 return true; 9303 9304 if (Selected) { 9305 // If there's a default constructor which could have been trivial, dig it 9306 // out. Otherwise, if there's any user-provided default constructor, point 9307 // to that as an example of why there's not a trivial one. 9308 CXXConstructorDecl *DefCtor = nullptr; 9309 if (RD->needsImplicitDefaultConstructor()) 9310 S.DeclareImplicitDefaultConstructor(RD); 9311 for (auto *CI : RD->ctors()) { 9312 if (!CI->isDefaultConstructor()) 9313 continue; 9314 DefCtor = CI; 9315 if (!DefCtor->isUserProvided()) 9316 break; 9317 } 9318 9319 *Selected = DefCtor; 9320 } 9321 9322 return false; 9323 9324 case Sema::CXXDestructor: 9325 // C++11 [class.dtor]p5: 9326 // A destructor is trivial if: 9327 // - all the direct [subobjects] have trivial destructors 9328 if (RD->hasTrivialDestructor() || 9329 (TAH == Sema::TAH_ConsiderTrivialABI && 9330 RD->hasTrivialDestructorForCall())) 9331 return true; 9332 9333 if (Selected) { 9334 if (RD->needsImplicitDestructor()) 9335 S.DeclareImplicitDestructor(RD); 9336 *Selected = RD->getDestructor(); 9337 } 9338 9339 return false; 9340 9341 case Sema::CXXCopyConstructor: 9342 // C++11 [class.copy]p12: 9343 // A copy constructor is trivial if: 9344 // - the constructor selected to copy each direct [subobject] is trivial 9345 if (RD->hasTrivialCopyConstructor() || 9346 (TAH == Sema::TAH_ConsiderTrivialABI && 9347 RD->hasTrivialCopyConstructorForCall())) { 9348 if (Quals == Qualifiers::Const) 9349 // We must either select the trivial copy constructor or reach an 9350 // ambiguity; no need to actually perform overload resolution. 9351 return true; 9352 } else if (!Selected) { 9353 return false; 9354 } 9355 // In C++98, we are not supposed to perform overload resolution here, but we 9356 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9357 // cases like B as having a non-trivial copy constructor: 9358 // struct A { template<typename T> A(T&); }; 9359 // struct B { mutable A a; }; 9360 goto NeedOverloadResolution; 9361 9362 case Sema::CXXCopyAssignment: 9363 // C++11 [class.copy]p25: 9364 // A copy assignment operator is trivial if: 9365 // - the assignment operator selected to copy each direct [subobject] is 9366 // trivial 9367 if (RD->hasTrivialCopyAssignment()) { 9368 if (Quals == Qualifiers::Const) 9369 return true; 9370 } else if (!Selected) { 9371 return false; 9372 } 9373 // In C++98, we are not supposed to perform overload resolution here, but we 9374 // treat that as a language defect. 9375 goto NeedOverloadResolution; 9376 9377 case Sema::CXXMoveConstructor: 9378 case Sema::CXXMoveAssignment: 9379 NeedOverloadResolution: 9380 Sema::SpecialMemberOverloadResult SMOR = 9381 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9382 9383 // The standard doesn't describe how to behave if the lookup is ambiguous. 9384 // We treat it as not making the member non-trivial, just like the standard 9385 // mandates for the default constructor. This should rarely matter, because 9386 // the member will also be deleted. 9387 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9388 return true; 9389 9390 if (!SMOR.getMethod()) { 9391 assert(SMOR.getKind() == 9392 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9393 return false; 9394 } 9395 9396 // We deliberately don't check if we found a deleted special member. We're 9397 // not supposed to! 9398 if (Selected) 9399 *Selected = SMOR.getMethod(); 9400 9401 if (TAH == Sema::TAH_ConsiderTrivialABI && 9402 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9403 return SMOR.getMethod()->isTrivialForCall(); 9404 return SMOR.getMethod()->isTrivial(); 9405 } 9406 9407 llvm_unreachable("unknown special method kind"); 9408 } 9409 9410 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9411 for (auto *CI : RD->ctors()) 9412 if (!CI->isImplicit()) 9413 return CI; 9414 9415 // Look for constructor templates. 9416 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9417 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9418 if (CXXConstructorDecl *CD = 9419 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9420 return CD; 9421 } 9422 9423 return nullptr; 9424 } 9425 9426 /// The kind of subobject we are checking for triviality. The values of this 9427 /// enumeration are used in diagnostics. 9428 enum TrivialSubobjectKind { 9429 /// The subobject is a base class. 9430 TSK_BaseClass, 9431 /// The subobject is a non-static data member. 9432 TSK_Field, 9433 /// The object is actually the complete object. 9434 TSK_CompleteObject 9435 }; 9436 9437 /// Check whether the special member selected for a given type would be trivial. 9438 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9439 QualType SubType, bool ConstRHS, 9440 Sema::CXXSpecialMember CSM, 9441 TrivialSubobjectKind Kind, 9442 Sema::TrivialABIHandling TAH, bool Diagnose) { 9443 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9444 if (!SubRD) 9445 return true; 9446 9447 CXXMethodDecl *Selected; 9448 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9449 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9450 return true; 9451 9452 if (Diagnose) { 9453 if (ConstRHS) 9454 SubType.addConst(); 9455 9456 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9457 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9458 << Kind << SubType.getUnqualifiedType(); 9459 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9460 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9461 } else if (!Selected) 9462 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9463 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9464 else if (Selected->isUserProvided()) { 9465 if (Kind == TSK_CompleteObject) 9466 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9467 << Kind << SubType.getUnqualifiedType() << CSM; 9468 else { 9469 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9470 << Kind << SubType.getUnqualifiedType() << CSM; 9471 S.Diag(Selected->getLocation(), diag::note_declared_at); 9472 } 9473 } else { 9474 if (Kind != TSK_CompleteObject) 9475 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9476 << Kind << SubType.getUnqualifiedType() << CSM; 9477 9478 // Explain why the defaulted or deleted special member isn't trivial. 9479 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9480 Diagnose); 9481 } 9482 } 9483 9484 return false; 9485 } 9486 9487 /// Check whether the members of a class type allow a special member to be 9488 /// trivial. 9489 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9490 Sema::CXXSpecialMember CSM, 9491 bool ConstArg, 9492 Sema::TrivialABIHandling TAH, 9493 bool Diagnose) { 9494 for (const auto *FI : RD->fields()) { 9495 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9496 continue; 9497 9498 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9499 9500 // Pretend anonymous struct or union members are members of this class. 9501 if (FI->isAnonymousStructOrUnion()) { 9502 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9503 CSM, ConstArg, TAH, Diagnose)) 9504 return false; 9505 continue; 9506 } 9507 9508 // C++11 [class.ctor]p5: 9509 // A default constructor is trivial if [...] 9510 // -- no non-static data member of its class has a 9511 // brace-or-equal-initializer 9512 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9513 if (Diagnose) 9514 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9515 << FI; 9516 return false; 9517 } 9518 9519 // Objective C ARC 4.3.5: 9520 // [...] nontrivally ownership-qualified types are [...] not trivially 9521 // default constructible, copy constructible, move constructible, copy 9522 // assignable, move assignable, or destructible [...] 9523 if (FieldType.hasNonTrivialObjCLifetime()) { 9524 if (Diagnose) 9525 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9526 << RD << FieldType.getObjCLifetime(); 9527 return false; 9528 } 9529 9530 bool ConstRHS = ConstArg && !FI->isMutable(); 9531 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9532 CSM, TSK_Field, TAH, Diagnose)) 9533 return false; 9534 } 9535 9536 return true; 9537 } 9538 9539 /// Diagnose why the specified class does not have a trivial special member of 9540 /// the given kind. 9541 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9542 QualType Ty = Context.getRecordType(RD); 9543 9544 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9545 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9546 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9547 /*Diagnose*/true); 9548 } 9549 9550 /// Determine whether a defaulted or deleted special member function is trivial, 9551 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9552 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9553 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9554 TrivialABIHandling TAH, bool Diagnose) { 9555 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9556 9557 CXXRecordDecl *RD = MD->getParent(); 9558 9559 bool ConstArg = false; 9560 9561 // C++11 [class.copy]p12, p25: [DR1593] 9562 // A [special member] is trivial if [...] its parameter-type-list is 9563 // equivalent to the parameter-type-list of an implicit declaration [...] 9564 switch (CSM) { 9565 case CXXDefaultConstructor: 9566 case CXXDestructor: 9567 // Trivial default constructors and destructors cannot have parameters. 9568 break; 9569 9570 case CXXCopyConstructor: 9571 case CXXCopyAssignment: { 9572 // Trivial copy operations always have const, non-volatile parameter types. 9573 ConstArg = true; 9574 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9575 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9576 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9577 if (Diagnose) 9578 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9579 << Param0->getSourceRange() << Param0->getType() 9580 << Context.getLValueReferenceType( 9581 Context.getRecordType(RD).withConst()); 9582 return false; 9583 } 9584 break; 9585 } 9586 9587 case CXXMoveConstructor: 9588 case CXXMoveAssignment: { 9589 // Trivial move operations always have non-cv-qualified parameters. 9590 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9591 const RValueReferenceType *RT = 9592 Param0->getType()->getAs<RValueReferenceType>(); 9593 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9594 if (Diagnose) 9595 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9596 << Param0->getSourceRange() << Param0->getType() 9597 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9598 return false; 9599 } 9600 break; 9601 } 9602 9603 case CXXInvalid: 9604 llvm_unreachable("not a special member"); 9605 } 9606 9607 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9608 if (Diagnose) 9609 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9610 diag::note_nontrivial_default_arg) 9611 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9612 return false; 9613 } 9614 if (MD->isVariadic()) { 9615 if (Diagnose) 9616 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9617 return false; 9618 } 9619 9620 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9621 // A copy/move [constructor or assignment operator] is trivial if 9622 // -- the [member] selected to copy/move each direct base class subobject 9623 // is trivial 9624 // 9625 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9626 // A [default constructor or destructor] is trivial if 9627 // -- all the direct base classes have trivial [default constructors or 9628 // destructors] 9629 for (const auto &BI : RD->bases()) 9630 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9631 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9632 return false; 9633 9634 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9635 // A copy/move [constructor or assignment operator] for a class X is 9636 // trivial if 9637 // -- for each non-static data member of X that is of class type (or array 9638 // thereof), the constructor selected to copy/move that member is 9639 // trivial 9640 // 9641 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9642 // A [default constructor or destructor] is trivial if 9643 // -- for all of the non-static data members of its class that are of class 9644 // type (or array thereof), each such class has a trivial [default 9645 // constructor or destructor] 9646 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9647 return false; 9648 9649 // C++11 [class.dtor]p5: 9650 // A destructor is trivial if [...] 9651 // -- the destructor is not virtual 9652 if (CSM == CXXDestructor && MD->isVirtual()) { 9653 if (Diagnose) 9654 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9655 return false; 9656 } 9657 9658 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9659 // A [special member] for class X is trivial if [...] 9660 // -- class X has no virtual functions and no virtual base classes 9661 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9662 if (!Diagnose) 9663 return false; 9664 9665 if (RD->getNumVBases()) { 9666 // Check for virtual bases. We already know that the corresponding 9667 // member in all bases is trivial, so vbases must all be direct. 9668 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9669 assert(BS.isVirtual()); 9670 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9671 return false; 9672 } 9673 9674 // Must have a virtual method. 9675 for (const auto *MI : RD->methods()) { 9676 if (MI->isVirtual()) { 9677 SourceLocation MLoc = MI->getBeginLoc(); 9678 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9679 return false; 9680 } 9681 } 9682 9683 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9684 } 9685 9686 // Looks like it's trivial! 9687 return true; 9688 } 9689 9690 namespace { 9691 struct FindHiddenVirtualMethod { 9692 Sema *S; 9693 CXXMethodDecl *Method; 9694 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9695 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9696 9697 private: 9698 /// Check whether any most overridden method from MD in Methods 9699 static bool CheckMostOverridenMethods( 9700 const CXXMethodDecl *MD, 9701 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9702 if (MD->size_overridden_methods() == 0) 9703 return Methods.count(MD->getCanonicalDecl()); 9704 for (const CXXMethodDecl *O : MD->overridden_methods()) 9705 if (CheckMostOverridenMethods(O, Methods)) 9706 return true; 9707 return false; 9708 } 9709 9710 public: 9711 /// Member lookup function that determines whether a given C++ 9712 /// method overloads virtual methods in a base class without overriding any, 9713 /// to be used with CXXRecordDecl::lookupInBases(). 9714 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9715 RecordDecl *BaseRecord = 9716 Specifier->getType()->castAs<RecordType>()->getDecl(); 9717 9718 DeclarationName Name = Method->getDeclName(); 9719 assert(Name.getNameKind() == DeclarationName::Identifier); 9720 9721 bool foundSameNameMethod = false; 9722 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9723 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9724 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9725 NamedDecl *D = *Path.Decls; 9726 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9727 MD = MD->getCanonicalDecl(); 9728 foundSameNameMethod = true; 9729 // Interested only in hidden virtual methods. 9730 if (!MD->isVirtual()) 9731 continue; 9732 // If the method we are checking overrides a method from its base 9733 // don't warn about the other overloaded methods. Clang deviates from 9734 // GCC by only diagnosing overloads of inherited virtual functions that 9735 // do not override any other virtual functions in the base. GCC's 9736 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9737 // function from a base class. These cases may be better served by a 9738 // warning (not specific to virtual functions) on call sites when the 9739 // call would select a different function from the base class, were it 9740 // visible. 9741 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9742 if (!S->IsOverload(Method, MD, false)) 9743 return true; 9744 // Collect the overload only if its hidden. 9745 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9746 overloadedMethods.push_back(MD); 9747 } 9748 } 9749 9750 if (foundSameNameMethod) 9751 OverloadedMethods.append(overloadedMethods.begin(), 9752 overloadedMethods.end()); 9753 return foundSameNameMethod; 9754 } 9755 }; 9756 } // end anonymous namespace 9757 9758 /// Add the most overriden methods from MD to Methods 9759 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9760 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9761 if (MD->size_overridden_methods() == 0) 9762 Methods.insert(MD->getCanonicalDecl()); 9763 else 9764 for (const CXXMethodDecl *O : MD->overridden_methods()) 9765 AddMostOverridenMethods(O, Methods); 9766 } 9767 9768 /// Check if a method overloads virtual methods in a base class without 9769 /// overriding any. 9770 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9771 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9772 if (!MD->getDeclName().isIdentifier()) 9773 return; 9774 9775 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9776 /*bool RecordPaths=*/false, 9777 /*bool DetectVirtual=*/false); 9778 FindHiddenVirtualMethod FHVM; 9779 FHVM.Method = MD; 9780 FHVM.S = this; 9781 9782 // Keep the base methods that were overridden or introduced in the subclass 9783 // by 'using' in a set. A base method not in this set is hidden. 9784 CXXRecordDecl *DC = MD->getParent(); 9785 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9786 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9787 NamedDecl *ND = *I; 9788 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9789 ND = shad->getTargetDecl(); 9790 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9791 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9792 } 9793 9794 if (DC->lookupInBases(FHVM, Paths)) 9795 OverloadedMethods = FHVM.OverloadedMethods; 9796 } 9797 9798 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9799 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9800 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9801 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9802 PartialDiagnostic PD = PDiag( 9803 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9804 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9805 Diag(overloadedMD->getLocation(), PD); 9806 } 9807 } 9808 9809 /// Diagnose methods which overload virtual methods in a base class 9810 /// without overriding any. 9811 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9812 if (MD->isInvalidDecl()) 9813 return; 9814 9815 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9816 return; 9817 9818 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9819 FindHiddenVirtualMethods(MD, OverloadedMethods); 9820 if (!OverloadedMethods.empty()) { 9821 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9822 << MD << (OverloadedMethods.size() > 1); 9823 9824 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9825 } 9826 } 9827 9828 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9829 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9830 // No diagnostics if this is a template instantiation. 9831 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9832 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9833 diag::ext_cannot_use_trivial_abi) << &RD; 9834 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9835 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9836 } 9837 RD.dropAttr<TrivialABIAttr>(); 9838 }; 9839 9840 // Ill-formed if the copy and move constructors are deleted. 9841 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9842 // If the type is dependent, then assume it might have 9843 // implicit copy or move ctor because we won't know yet at this point. 9844 if (RD.isDependentType()) 9845 return true; 9846 if (RD.needsImplicitCopyConstructor() && 9847 !RD.defaultedCopyConstructorIsDeleted()) 9848 return true; 9849 if (RD.needsImplicitMoveConstructor() && 9850 !RD.defaultedMoveConstructorIsDeleted()) 9851 return true; 9852 for (const CXXConstructorDecl *CD : RD.ctors()) 9853 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9854 return true; 9855 return false; 9856 }; 9857 9858 if (!HasNonDeletedCopyOrMoveConstructor()) { 9859 PrintDiagAndRemoveAttr(0); 9860 return; 9861 } 9862 9863 // Ill-formed if the struct has virtual functions. 9864 if (RD.isPolymorphic()) { 9865 PrintDiagAndRemoveAttr(1); 9866 return; 9867 } 9868 9869 for (const auto &B : RD.bases()) { 9870 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9871 // virtual base. 9872 if (!B.getType()->isDependentType() && 9873 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9874 PrintDiagAndRemoveAttr(2); 9875 return; 9876 } 9877 9878 if (B.isVirtual()) { 9879 PrintDiagAndRemoveAttr(3); 9880 return; 9881 } 9882 } 9883 9884 for (const auto *FD : RD.fields()) { 9885 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9886 // non-trivial for the purpose of calls. 9887 QualType FT = FD->getType(); 9888 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9889 PrintDiagAndRemoveAttr(4); 9890 return; 9891 } 9892 9893 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9894 if (!RT->isDependentType() && 9895 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9896 PrintDiagAndRemoveAttr(5); 9897 return; 9898 } 9899 } 9900 } 9901 9902 void Sema::ActOnFinishCXXMemberSpecification( 9903 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9904 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9905 if (!TagDecl) 9906 return; 9907 9908 AdjustDeclIfTemplate(TagDecl); 9909 9910 for (const ParsedAttr &AL : AttrList) { 9911 if (AL.getKind() != ParsedAttr::AT_Visibility) 9912 continue; 9913 AL.setInvalid(); 9914 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9915 } 9916 9917 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9918 // strict aliasing violation! 9919 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9920 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9921 9922 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9923 } 9924 9925 /// Find the equality comparison functions that should be implicitly declared 9926 /// in a given class definition, per C++2a [class.compare.default]p3. 9927 static void findImplicitlyDeclaredEqualityComparisons( 9928 ASTContext &Ctx, CXXRecordDecl *RD, 9929 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9930 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9931 if (!RD->lookup(EqEq).empty()) 9932 // Member operator== explicitly declared: no implicit operator==s. 9933 return; 9934 9935 // Traverse friends looking for an '==' or a '<=>'. 9936 for (FriendDecl *Friend : RD->friends()) { 9937 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9938 if (!FD) continue; 9939 9940 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9941 // Friend operator== explicitly declared: no implicit operator==s. 9942 Spaceships.clear(); 9943 return; 9944 } 9945 9946 if (FD->getOverloadedOperator() == OO_Spaceship && 9947 FD->isExplicitlyDefaulted()) 9948 Spaceships.push_back(FD); 9949 } 9950 9951 // Look for members named 'operator<=>'. 9952 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9953 for (NamedDecl *ND : RD->lookup(Cmp)) { 9954 // Note that we could find a non-function here (either a function template 9955 // or a using-declaration). Neither case results in an implicit 9956 // 'operator=='. 9957 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9958 if (FD->isExplicitlyDefaulted()) 9959 Spaceships.push_back(FD); 9960 } 9961 } 9962 9963 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9964 /// special functions, such as the default constructor, copy 9965 /// constructor, or destructor, to the given C++ class (C++ 9966 /// [special]p1). This routine can only be executed just before the 9967 /// definition of the class is complete. 9968 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9969 // Don't add implicit special members to templated classes. 9970 // FIXME: This means unqualified lookups for 'operator=' within a class 9971 // template don't work properly. 9972 if (!ClassDecl->isDependentType()) { 9973 if (ClassDecl->needsImplicitDefaultConstructor()) { 9974 ++getASTContext().NumImplicitDefaultConstructors; 9975 9976 if (ClassDecl->hasInheritedConstructor()) 9977 DeclareImplicitDefaultConstructor(ClassDecl); 9978 } 9979 9980 if (ClassDecl->needsImplicitCopyConstructor()) { 9981 ++getASTContext().NumImplicitCopyConstructors; 9982 9983 // If the properties or semantics of the copy constructor couldn't be 9984 // determined while the class was being declared, force a declaration 9985 // of it now. 9986 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9987 ClassDecl->hasInheritedConstructor()) 9988 DeclareImplicitCopyConstructor(ClassDecl); 9989 // For the MS ABI we need to know whether the copy ctor is deleted. A 9990 // prerequisite for deleting the implicit copy ctor is that the class has 9991 // a move ctor or move assignment that is either user-declared or whose 9992 // semantics are inherited from a subobject. FIXME: We should provide a 9993 // more direct way for CodeGen to ask whether the constructor was deleted. 9994 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9995 (ClassDecl->hasUserDeclaredMoveConstructor() || 9996 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9997 ClassDecl->hasUserDeclaredMoveAssignment() || 9998 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9999 DeclareImplicitCopyConstructor(ClassDecl); 10000 } 10001 10002 if (getLangOpts().CPlusPlus11 && 10003 ClassDecl->needsImplicitMoveConstructor()) { 10004 ++getASTContext().NumImplicitMoveConstructors; 10005 10006 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10007 ClassDecl->hasInheritedConstructor()) 10008 DeclareImplicitMoveConstructor(ClassDecl); 10009 } 10010 10011 if (ClassDecl->needsImplicitCopyAssignment()) { 10012 ++getASTContext().NumImplicitCopyAssignmentOperators; 10013 10014 // If we have a dynamic class, then the copy assignment operator may be 10015 // virtual, so we have to declare it immediately. This ensures that, e.g., 10016 // it shows up in the right place in the vtable and that we diagnose 10017 // problems with the implicit exception specification. 10018 if (ClassDecl->isDynamicClass() || 10019 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10020 ClassDecl->hasInheritedAssignment()) 10021 DeclareImplicitCopyAssignment(ClassDecl); 10022 } 10023 10024 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10025 ++getASTContext().NumImplicitMoveAssignmentOperators; 10026 10027 // Likewise for the move assignment operator. 10028 if (ClassDecl->isDynamicClass() || 10029 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10030 ClassDecl->hasInheritedAssignment()) 10031 DeclareImplicitMoveAssignment(ClassDecl); 10032 } 10033 10034 if (ClassDecl->needsImplicitDestructor()) { 10035 ++getASTContext().NumImplicitDestructors; 10036 10037 // If we have a dynamic class, then the destructor may be virtual, so we 10038 // have to declare the destructor immediately. This ensures that, e.g., it 10039 // shows up in the right place in the vtable and that we diagnose problems 10040 // with the implicit exception specification. 10041 if (ClassDecl->isDynamicClass() || 10042 ClassDecl->needsOverloadResolutionForDestructor()) 10043 DeclareImplicitDestructor(ClassDecl); 10044 } 10045 } 10046 10047 // C++2a [class.compare.default]p3: 10048 // If the member-specification does not explicitly declare any member or 10049 // friend named operator==, an == operator function is declared implicitly 10050 // for each defaulted three-way comparison operator function defined in 10051 // the member-specification 10052 // FIXME: Consider doing this lazily. 10053 // We do this during the initial parse for a class template, not during 10054 // instantiation, so that we can handle unqualified lookups for 'operator==' 10055 // when parsing the template. 10056 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10057 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10058 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10059 DefaultedSpaceships); 10060 for (auto *FD : DefaultedSpaceships) 10061 DeclareImplicitEqualityComparison(ClassDecl, FD); 10062 } 10063 } 10064 10065 unsigned 10066 Sema::ActOnReenterTemplateScope(Decl *D, 10067 llvm::function_ref<Scope *()> EnterScope) { 10068 if (!D) 10069 return 0; 10070 AdjustDeclIfTemplate(D); 10071 10072 // In order to get name lookup right, reenter template scopes in order from 10073 // outermost to innermost. 10074 SmallVector<TemplateParameterList *, 4> ParameterLists; 10075 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10076 10077 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10078 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10079 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10080 10081 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10082 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10083 ParameterLists.push_back(FTD->getTemplateParameters()); 10084 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10085 LookupDC = VD->getDeclContext(); 10086 10087 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10088 ParameterLists.push_back(VTD->getTemplateParameters()); 10089 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10090 ParameterLists.push_back(PSD->getTemplateParameters()); 10091 } 10092 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10093 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10094 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10095 10096 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10097 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10098 ParameterLists.push_back(CTD->getTemplateParameters()); 10099 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10100 ParameterLists.push_back(PSD->getTemplateParameters()); 10101 } 10102 } 10103 // FIXME: Alias declarations and concepts. 10104 10105 unsigned Count = 0; 10106 Scope *InnermostTemplateScope = nullptr; 10107 for (TemplateParameterList *Params : ParameterLists) { 10108 // Ignore explicit specializations; they don't contribute to the template 10109 // depth. 10110 if (Params->size() == 0) 10111 continue; 10112 10113 InnermostTemplateScope = EnterScope(); 10114 for (NamedDecl *Param : *Params) { 10115 if (Param->getDeclName()) { 10116 InnermostTemplateScope->AddDecl(Param); 10117 IdResolver.AddDecl(Param); 10118 } 10119 } 10120 ++Count; 10121 } 10122 10123 // Associate the new template scopes with the corresponding entities. 10124 if (InnermostTemplateScope) { 10125 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10126 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10127 } 10128 10129 return Count; 10130 } 10131 10132 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10133 if (!RecordD) return; 10134 AdjustDeclIfTemplate(RecordD); 10135 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10136 PushDeclContext(S, Record); 10137 } 10138 10139 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10140 if (!RecordD) return; 10141 PopDeclContext(); 10142 } 10143 10144 /// This is used to implement the constant expression evaluation part of the 10145 /// attribute enable_if extension. There is nothing in standard C++ which would 10146 /// require reentering parameters. 10147 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10148 if (!Param) 10149 return; 10150 10151 S->AddDecl(Param); 10152 if (Param->getDeclName()) 10153 IdResolver.AddDecl(Param); 10154 } 10155 10156 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10157 /// parsing a top-level (non-nested) C++ class, and we are now 10158 /// parsing those parts of the given Method declaration that could 10159 /// not be parsed earlier (C++ [class.mem]p2), such as default 10160 /// arguments. This action should enter the scope of the given 10161 /// Method declaration as if we had just parsed the qualified method 10162 /// name. However, it should not bring the parameters into scope; 10163 /// that will be performed by ActOnDelayedCXXMethodParameter. 10164 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10165 } 10166 10167 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10168 /// C++ method declaration. We're (re-)introducing the given 10169 /// function parameter into scope for use in parsing later parts of 10170 /// the method declaration. For example, we could see an 10171 /// ActOnParamDefaultArgument event for this parameter. 10172 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10173 if (!ParamD) 10174 return; 10175 10176 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10177 10178 S->AddDecl(Param); 10179 if (Param->getDeclName()) 10180 IdResolver.AddDecl(Param); 10181 } 10182 10183 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10184 /// processing the delayed method declaration for Method. The method 10185 /// declaration is now considered finished. There may be a separate 10186 /// ActOnStartOfFunctionDef action later (not necessarily 10187 /// immediately!) for this method, if it was also defined inside the 10188 /// class body. 10189 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10190 if (!MethodD) 10191 return; 10192 10193 AdjustDeclIfTemplate(MethodD); 10194 10195 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10196 10197 // Now that we have our default arguments, check the constructor 10198 // again. It could produce additional diagnostics or affect whether 10199 // the class has implicitly-declared destructors, among other 10200 // things. 10201 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10202 CheckConstructor(Constructor); 10203 10204 // Check the default arguments, which we may have added. 10205 if (!Method->isInvalidDecl()) 10206 CheckCXXDefaultArguments(Method); 10207 } 10208 10209 // Emit the given diagnostic for each non-address-space qualifier. 10210 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10211 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10212 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10213 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10214 bool DiagOccured = false; 10215 FTI.MethodQualifiers->forEachQualifier( 10216 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10217 SourceLocation SL) { 10218 // This diagnostic should be emitted on any qualifier except an addr 10219 // space qualifier. However, forEachQualifier currently doesn't visit 10220 // addr space qualifiers, so there's no way to write this condition 10221 // right now; we just diagnose on everything. 10222 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10223 DiagOccured = true; 10224 }); 10225 if (DiagOccured) 10226 D.setInvalidType(); 10227 } 10228 } 10229 10230 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10231 /// the well-formedness of the constructor declarator @p D with type @p 10232 /// R. If there are any errors in the declarator, this routine will 10233 /// emit diagnostics and set the invalid bit to true. In any case, the type 10234 /// will be updated to reflect a well-formed type for the constructor and 10235 /// returned. 10236 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10237 StorageClass &SC) { 10238 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10239 10240 // C++ [class.ctor]p3: 10241 // A constructor shall not be virtual (10.3) or static (9.4). A 10242 // constructor can be invoked for a const, volatile or const 10243 // volatile object. A constructor shall not be declared const, 10244 // volatile, or const volatile (9.3.2). 10245 if (isVirtual) { 10246 if (!D.isInvalidType()) 10247 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10248 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10249 << SourceRange(D.getIdentifierLoc()); 10250 D.setInvalidType(); 10251 } 10252 if (SC == SC_Static) { 10253 if (!D.isInvalidType()) 10254 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10255 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10256 << SourceRange(D.getIdentifierLoc()); 10257 D.setInvalidType(); 10258 SC = SC_None; 10259 } 10260 10261 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10262 diagnoseIgnoredQualifiers( 10263 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10264 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10265 D.getDeclSpec().getRestrictSpecLoc(), 10266 D.getDeclSpec().getAtomicSpecLoc()); 10267 D.setInvalidType(); 10268 } 10269 10270 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10271 10272 // C++0x [class.ctor]p4: 10273 // A constructor shall not be declared with a ref-qualifier. 10274 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10275 if (FTI.hasRefQualifier()) { 10276 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10277 << FTI.RefQualifierIsLValueRef 10278 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10279 D.setInvalidType(); 10280 } 10281 10282 // Rebuild the function type "R" without any type qualifiers (in 10283 // case any of the errors above fired) and with "void" as the 10284 // return type, since constructors don't have return types. 10285 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10286 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10287 return R; 10288 10289 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10290 EPI.TypeQuals = Qualifiers(); 10291 EPI.RefQualifier = RQ_None; 10292 10293 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10294 } 10295 10296 /// CheckConstructor - Checks a fully-formed constructor for 10297 /// well-formedness, issuing any diagnostics required. Returns true if 10298 /// the constructor declarator is invalid. 10299 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10300 CXXRecordDecl *ClassDecl 10301 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10302 if (!ClassDecl) 10303 return Constructor->setInvalidDecl(); 10304 10305 // C++ [class.copy]p3: 10306 // A declaration of a constructor for a class X is ill-formed if 10307 // its first parameter is of type (optionally cv-qualified) X and 10308 // either there are no other parameters or else all other 10309 // parameters have default arguments. 10310 if (!Constructor->isInvalidDecl() && 10311 Constructor->hasOneParamOrDefaultArgs() && 10312 Constructor->getTemplateSpecializationKind() != 10313 TSK_ImplicitInstantiation) { 10314 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10315 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10316 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10317 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10318 const char *ConstRef 10319 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10320 : " const &"; 10321 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10322 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10323 10324 // FIXME: Rather that making the constructor invalid, we should endeavor 10325 // to fix the type. 10326 Constructor->setInvalidDecl(); 10327 } 10328 } 10329 } 10330 10331 /// CheckDestructor - Checks a fully-formed destructor definition for 10332 /// well-formedness, issuing any diagnostics required. Returns true 10333 /// on error. 10334 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10335 CXXRecordDecl *RD = Destructor->getParent(); 10336 10337 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10338 SourceLocation Loc; 10339 10340 if (!Destructor->isImplicit()) 10341 Loc = Destructor->getLocation(); 10342 else 10343 Loc = RD->getLocation(); 10344 10345 // If we have a virtual destructor, look up the deallocation function 10346 if (FunctionDecl *OperatorDelete = 10347 FindDeallocationFunctionForDestructor(Loc, RD)) { 10348 Expr *ThisArg = nullptr; 10349 10350 // If the notional 'delete this' expression requires a non-trivial 10351 // conversion from 'this' to the type of a destroying operator delete's 10352 // first parameter, perform that conversion now. 10353 if (OperatorDelete->isDestroyingOperatorDelete()) { 10354 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10355 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10356 // C++ [class.dtor]p13: 10357 // ... as if for the expression 'delete this' appearing in a 10358 // non-virtual destructor of the destructor's class. 10359 ContextRAII SwitchContext(*this, Destructor); 10360 ExprResult This = 10361 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10362 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10363 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10364 if (This.isInvalid()) { 10365 // FIXME: Register this as a context note so that it comes out 10366 // in the right order. 10367 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10368 return true; 10369 } 10370 ThisArg = This.get(); 10371 } 10372 } 10373 10374 DiagnoseUseOfDecl(OperatorDelete, Loc); 10375 MarkFunctionReferenced(Loc, OperatorDelete); 10376 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10377 } 10378 } 10379 10380 return false; 10381 } 10382 10383 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10384 /// the well-formednes of the destructor declarator @p D with type @p 10385 /// R. If there are any errors in the declarator, this routine will 10386 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10387 /// will be updated to reflect a well-formed type for the destructor and 10388 /// returned. 10389 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10390 StorageClass& SC) { 10391 // C++ [class.dtor]p1: 10392 // [...] A typedef-name that names a class is a class-name 10393 // (7.1.3); however, a typedef-name that names a class shall not 10394 // be used as the identifier in the declarator for a destructor 10395 // declaration. 10396 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10397 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10398 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10399 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10400 else if (const TemplateSpecializationType *TST = 10401 DeclaratorType->getAs<TemplateSpecializationType>()) 10402 if (TST->isTypeAlias()) 10403 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10404 << DeclaratorType << 1; 10405 10406 // C++ [class.dtor]p2: 10407 // A destructor is used to destroy objects of its class type. A 10408 // destructor takes no parameters, and no return type can be 10409 // specified for it (not even void). The address of a destructor 10410 // shall not be taken. A destructor shall not be static. A 10411 // destructor can be invoked for a const, volatile or const 10412 // volatile object. A destructor shall not be declared const, 10413 // volatile or const volatile (9.3.2). 10414 if (SC == SC_Static) { 10415 if (!D.isInvalidType()) 10416 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10417 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10418 << SourceRange(D.getIdentifierLoc()) 10419 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10420 10421 SC = SC_None; 10422 } 10423 if (!D.isInvalidType()) { 10424 // Destructors don't have return types, but the parser will 10425 // happily parse something like: 10426 // 10427 // class X { 10428 // float ~X(); 10429 // }; 10430 // 10431 // The return type will be eliminated later. 10432 if (D.getDeclSpec().hasTypeSpecifier()) 10433 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10434 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10435 << SourceRange(D.getIdentifierLoc()); 10436 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10437 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10438 SourceLocation(), 10439 D.getDeclSpec().getConstSpecLoc(), 10440 D.getDeclSpec().getVolatileSpecLoc(), 10441 D.getDeclSpec().getRestrictSpecLoc(), 10442 D.getDeclSpec().getAtomicSpecLoc()); 10443 D.setInvalidType(); 10444 } 10445 } 10446 10447 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10448 10449 // C++0x [class.dtor]p2: 10450 // A destructor shall not be declared with a ref-qualifier. 10451 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10452 if (FTI.hasRefQualifier()) { 10453 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10454 << FTI.RefQualifierIsLValueRef 10455 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10456 D.setInvalidType(); 10457 } 10458 10459 // Make sure we don't have any parameters. 10460 if (FTIHasNonVoidParameters(FTI)) { 10461 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10462 10463 // Delete the parameters. 10464 FTI.freeParams(); 10465 D.setInvalidType(); 10466 } 10467 10468 // Make sure the destructor isn't variadic. 10469 if (FTI.isVariadic) { 10470 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10471 D.setInvalidType(); 10472 } 10473 10474 // Rebuild the function type "R" without any type qualifiers or 10475 // parameters (in case any of the errors above fired) and with 10476 // "void" as the return type, since destructors don't have return 10477 // types. 10478 if (!D.isInvalidType()) 10479 return R; 10480 10481 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10482 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10483 EPI.Variadic = false; 10484 EPI.TypeQuals = Qualifiers(); 10485 EPI.RefQualifier = RQ_None; 10486 return Context.getFunctionType(Context.VoidTy, None, EPI); 10487 } 10488 10489 static void extendLeft(SourceRange &R, SourceRange Before) { 10490 if (Before.isInvalid()) 10491 return; 10492 R.setBegin(Before.getBegin()); 10493 if (R.getEnd().isInvalid()) 10494 R.setEnd(Before.getEnd()); 10495 } 10496 10497 static void extendRight(SourceRange &R, SourceRange After) { 10498 if (After.isInvalid()) 10499 return; 10500 if (R.getBegin().isInvalid()) 10501 R.setBegin(After.getBegin()); 10502 R.setEnd(After.getEnd()); 10503 } 10504 10505 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10506 /// well-formednes of the conversion function declarator @p D with 10507 /// type @p R. If there are any errors in the declarator, this routine 10508 /// will emit diagnostics and return true. Otherwise, it will return 10509 /// false. Either way, the type @p R will be updated to reflect a 10510 /// well-formed type for the conversion operator. 10511 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10512 StorageClass& SC) { 10513 // C++ [class.conv.fct]p1: 10514 // Neither parameter types nor return type can be specified. The 10515 // type of a conversion function (8.3.5) is "function taking no 10516 // parameter returning conversion-type-id." 10517 if (SC == SC_Static) { 10518 if (!D.isInvalidType()) 10519 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10520 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10521 << D.getName().getSourceRange(); 10522 D.setInvalidType(); 10523 SC = SC_None; 10524 } 10525 10526 TypeSourceInfo *ConvTSI = nullptr; 10527 QualType ConvType = 10528 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10529 10530 const DeclSpec &DS = D.getDeclSpec(); 10531 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10532 // Conversion functions don't have return types, but the parser will 10533 // happily parse something like: 10534 // 10535 // class X { 10536 // float operator bool(); 10537 // }; 10538 // 10539 // The return type will be changed later anyway. 10540 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10541 << SourceRange(DS.getTypeSpecTypeLoc()) 10542 << SourceRange(D.getIdentifierLoc()); 10543 D.setInvalidType(); 10544 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10545 // It's also plausible that the user writes type qualifiers in the wrong 10546 // place, such as: 10547 // struct S { const operator int(); }; 10548 // FIXME: we could provide a fixit to move the qualifiers onto the 10549 // conversion type. 10550 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10551 << SourceRange(D.getIdentifierLoc()) << 0; 10552 D.setInvalidType(); 10553 } 10554 10555 const auto *Proto = R->castAs<FunctionProtoType>(); 10556 10557 // Make sure we don't have any parameters. 10558 if (Proto->getNumParams() > 0) { 10559 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10560 10561 // Delete the parameters. 10562 D.getFunctionTypeInfo().freeParams(); 10563 D.setInvalidType(); 10564 } else if (Proto->isVariadic()) { 10565 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10566 D.setInvalidType(); 10567 } 10568 10569 // Diagnose "&operator bool()" and other such nonsense. This 10570 // is actually a gcc extension which we don't support. 10571 if (Proto->getReturnType() != ConvType) { 10572 bool NeedsTypedef = false; 10573 SourceRange Before, After; 10574 10575 // Walk the chunks and extract information on them for our diagnostic. 10576 bool PastFunctionChunk = false; 10577 for (auto &Chunk : D.type_objects()) { 10578 switch (Chunk.Kind) { 10579 case DeclaratorChunk::Function: 10580 if (!PastFunctionChunk) { 10581 if (Chunk.Fun.HasTrailingReturnType) { 10582 TypeSourceInfo *TRT = nullptr; 10583 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10584 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10585 } 10586 PastFunctionChunk = true; 10587 break; 10588 } 10589 LLVM_FALLTHROUGH; 10590 case DeclaratorChunk::Array: 10591 NeedsTypedef = true; 10592 extendRight(After, Chunk.getSourceRange()); 10593 break; 10594 10595 case DeclaratorChunk::Pointer: 10596 case DeclaratorChunk::BlockPointer: 10597 case DeclaratorChunk::Reference: 10598 case DeclaratorChunk::MemberPointer: 10599 case DeclaratorChunk::Pipe: 10600 extendLeft(Before, Chunk.getSourceRange()); 10601 break; 10602 10603 case DeclaratorChunk::Paren: 10604 extendLeft(Before, Chunk.Loc); 10605 extendRight(After, Chunk.EndLoc); 10606 break; 10607 } 10608 } 10609 10610 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10611 After.isValid() ? After.getBegin() : 10612 D.getIdentifierLoc(); 10613 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10614 DB << Before << After; 10615 10616 if (!NeedsTypedef) { 10617 DB << /*don't need a typedef*/0; 10618 10619 // If we can provide a correct fix-it hint, do so. 10620 if (After.isInvalid() && ConvTSI) { 10621 SourceLocation InsertLoc = 10622 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10623 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10624 << FixItHint::CreateInsertionFromRange( 10625 InsertLoc, CharSourceRange::getTokenRange(Before)) 10626 << FixItHint::CreateRemoval(Before); 10627 } 10628 } else if (!Proto->getReturnType()->isDependentType()) { 10629 DB << /*typedef*/1 << Proto->getReturnType(); 10630 } else if (getLangOpts().CPlusPlus11) { 10631 DB << /*alias template*/2 << Proto->getReturnType(); 10632 } else { 10633 DB << /*might not be fixable*/3; 10634 } 10635 10636 // Recover by incorporating the other type chunks into the result type. 10637 // Note, this does *not* change the name of the function. This is compatible 10638 // with the GCC extension: 10639 // struct S { &operator int(); } s; 10640 // int &r = s.operator int(); // ok in GCC 10641 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10642 ConvType = Proto->getReturnType(); 10643 } 10644 10645 // C++ [class.conv.fct]p4: 10646 // The conversion-type-id shall not represent a function type nor 10647 // an array type. 10648 if (ConvType->isArrayType()) { 10649 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10650 ConvType = Context.getPointerType(ConvType); 10651 D.setInvalidType(); 10652 } else if (ConvType->isFunctionType()) { 10653 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10654 ConvType = Context.getPointerType(ConvType); 10655 D.setInvalidType(); 10656 } 10657 10658 // Rebuild the function type "R" without any parameters (in case any 10659 // of the errors above fired) and with the conversion type as the 10660 // return type. 10661 if (D.isInvalidType()) 10662 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10663 10664 // C++0x explicit conversion operators. 10665 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10666 Diag(DS.getExplicitSpecLoc(), 10667 getLangOpts().CPlusPlus11 10668 ? diag::warn_cxx98_compat_explicit_conversion_functions 10669 : diag::ext_explicit_conversion_functions) 10670 << SourceRange(DS.getExplicitSpecRange()); 10671 } 10672 10673 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10674 /// the declaration of the given C++ conversion function. This routine 10675 /// is responsible for recording the conversion function in the C++ 10676 /// class, if possible. 10677 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10678 assert(Conversion && "Expected to receive a conversion function declaration"); 10679 10680 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10681 10682 // Make sure we aren't redeclaring the conversion function. 10683 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10684 // C++ [class.conv.fct]p1: 10685 // [...] A conversion function is never used to convert a 10686 // (possibly cv-qualified) object to the (possibly cv-qualified) 10687 // same object type (or a reference to it), to a (possibly 10688 // cv-qualified) base class of that type (or a reference to it), 10689 // or to (possibly cv-qualified) void. 10690 QualType ClassType 10691 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10692 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10693 ConvType = ConvTypeRef->getPointeeType(); 10694 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10695 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10696 /* Suppress diagnostics for instantiations. */; 10697 else if (Conversion->size_overridden_methods() != 0) 10698 /* Suppress diagnostics for overriding virtual function in a base class. */; 10699 else if (ConvType->isRecordType()) { 10700 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10701 if (ConvType == ClassType) 10702 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10703 << ClassType; 10704 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10705 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10706 << ClassType << ConvType; 10707 } else if (ConvType->isVoidType()) { 10708 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10709 << ClassType << ConvType; 10710 } 10711 10712 if (FunctionTemplateDecl *ConversionTemplate 10713 = Conversion->getDescribedFunctionTemplate()) 10714 return ConversionTemplate; 10715 10716 return Conversion; 10717 } 10718 10719 namespace { 10720 /// Utility class to accumulate and print a diagnostic listing the invalid 10721 /// specifier(s) on a declaration. 10722 struct BadSpecifierDiagnoser { 10723 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10724 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10725 ~BadSpecifierDiagnoser() { 10726 Diagnostic << Specifiers; 10727 } 10728 10729 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10730 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10731 } 10732 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10733 return check(SpecLoc, 10734 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10735 } 10736 void check(SourceLocation SpecLoc, const char *Spec) { 10737 if (SpecLoc.isInvalid()) return; 10738 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10739 if (!Specifiers.empty()) Specifiers += " "; 10740 Specifiers += Spec; 10741 } 10742 10743 Sema &S; 10744 Sema::SemaDiagnosticBuilder Diagnostic; 10745 std::string Specifiers; 10746 }; 10747 } 10748 10749 /// Check the validity of a declarator that we parsed for a deduction-guide. 10750 /// These aren't actually declarators in the grammar, so we need to check that 10751 /// the user didn't specify any pieces that are not part of the deduction-guide 10752 /// grammar. 10753 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10754 StorageClass &SC) { 10755 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10756 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10757 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10758 10759 // C++ [temp.deduct.guide]p3: 10760 // A deduction-gide shall be declared in the same scope as the 10761 // corresponding class template. 10762 if (!CurContext->getRedeclContext()->Equals( 10763 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10764 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10765 << GuidedTemplateDecl; 10766 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10767 } 10768 10769 auto &DS = D.getMutableDeclSpec(); 10770 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10771 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10772 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10773 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10774 BadSpecifierDiagnoser Diagnoser( 10775 *this, D.getIdentifierLoc(), 10776 diag::err_deduction_guide_invalid_specifier); 10777 10778 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10779 DS.ClearStorageClassSpecs(); 10780 SC = SC_None; 10781 10782 // 'explicit' is permitted. 10783 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10784 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10785 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10786 DS.ClearConstexprSpec(); 10787 10788 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10789 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10790 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10791 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10792 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10793 DS.ClearTypeQualifiers(); 10794 10795 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10796 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10797 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10798 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10799 DS.ClearTypeSpecType(); 10800 } 10801 10802 if (D.isInvalidType()) 10803 return; 10804 10805 // Check the declarator is simple enough. 10806 bool FoundFunction = false; 10807 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10808 if (Chunk.Kind == DeclaratorChunk::Paren) 10809 continue; 10810 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10811 Diag(D.getDeclSpec().getBeginLoc(), 10812 diag::err_deduction_guide_with_complex_decl) 10813 << D.getSourceRange(); 10814 break; 10815 } 10816 if (!Chunk.Fun.hasTrailingReturnType()) { 10817 Diag(D.getName().getBeginLoc(), 10818 diag::err_deduction_guide_no_trailing_return_type); 10819 break; 10820 } 10821 10822 // Check that the return type is written as a specialization of 10823 // the template specified as the deduction-guide's name. 10824 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10825 TypeSourceInfo *TSI = nullptr; 10826 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10827 assert(TSI && "deduction guide has valid type but invalid return type?"); 10828 bool AcceptableReturnType = false; 10829 bool MightInstantiateToSpecialization = false; 10830 if (auto RetTST = 10831 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10832 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10833 bool TemplateMatches = 10834 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10835 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10836 AcceptableReturnType = true; 10837 else { 10838 // This could still instantiate to the right type, unless we know it 10839 // names the wrong class template. 10840 auto *TD = SpecifiedName.getAsTemplateDecl(); 10841 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10842 !TemplateMatches); 10843 } 10844 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10845 MightInstantiateToSpecialization = true; 10846 } 10847 10848 if (!AcceptableReturnType) { 10849 Diag(TSI->getTypeLoc().getBeginLoc(), 10850 diag::err_deduction_guide_bad_trailing_return_type) 10851 << GuidedTemplate << TSI->getType() 10852 << MightInstantiateToSpecialization 10853 << TSI->getTypeLoc().getSourceRange(); 10854 } 10855 10856 // Keep going to check that we don't have any inner declarator pieces (we 10857 // could still have a function returning a pointer to a function). 10858 FoundFunction = true; 10859 } 10860 10861 if (D.isFunctionDefinition()) 10862 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10863 } 10864 10865 //===----------------------------------------------------------------------===// 10866 // Namespace Handling 10867 //===----------------------------------------------------------------------===// 10868 10869 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10870 /// reopened. 10871 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10872 SourceLocation Loc, 10873 IdentifierInfo *II, bool *IsInline, 10874 NamespaceDecl *PrevNS) { 10875 assert(*IsInline != PrevNS->isInline()); 10876 10877 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10878 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10879 // inline namespaces, with the intention of bringing names into namespace std. 10880 // 10881 // We support this just well enough to get that case working; this is not 10882 // sufficient to support reopening namespaces as inline in general. 10883 if (*IsInline && II && II->getName().startswith("__atomic") && 10884 S.getSourceManager().isInSystemHeader(Loc)) { 10885 // Mark all prior declarations of the namespace as inline. 10886 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10887 NS = NS->getPreviousDecl()) 10888 NS->setInline(*IsInline); 10889 // Patch up the lookup table for the containing namespace. This isn't really 10890 // correct, but it's good enough for this particular case. 10891 for (auto *I : PrevNS->decls()) 10892 if (auto *ND = dyn_cast<NamedDecl>(I)) 10893 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10894 return; 10895 } 10896 10897 if (PrevNS->isInline()) 10898 // The user probably just forgot the 'inline', so suggest that it 10899 // be added back. 10900 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10901 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10902 else 10903 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10904 10905 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10906 *IsInline = PrevNS->isInline(); 10907 } 10908 10909 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10910 /// definition. 10911 Decl *Sema::ActOnStartNamespaceDef( 10912 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10913 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10914 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10915 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10916 // For anonymous namespace, take the location of the left brace. 10917 SourceLocation Loc = II ? IdentLoc : LBrace; 10918 bool IsInline = InlineLoc.isValid(); 10919 bool IsInvalid = false; 10920 bool IsStd = false; 10921 bool AddToKnown = false; 10922 Scope *DeclRegionScope = NamespcScope->getParent(); 10923 10924 NamespaceDecl *PrevNS = nullptr; 10925 if (II) { 10926 // C++ [namespace.def]p2: 10927 // The identifier in an original-namespace-definition shall not 10928 // have been previously defined in the declarative region in 10929 // which the original-namespace-definition appears. The 10930 // identifier in an original-namespace-definition is the name of 10931 // the namespace. Subsequently in that declarative region, it is 10932 // treated as an original-namespace-name. 10933 // 10934 // Since namespace names are unique in their scope, and we don't 10935 // look through using directives, just look for any ordinary names 10936 // as if by qualified name lookup. 10937 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10938 ForExternalRedeclaration); 10939 LookupQualifiedName(R, CurContext->getRedeclContext()); 10940 NamedDecl *PrevDecl = 10941 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10942 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10943 10944 if (PrevNS) { 10945 // This is an extended namespace definition. 10946 if (IsInline != PrevNS->isInline()) 10947 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10948 &IsInline, PrevNS); 10949 } else if (PrevDecl) { 10950 // This is an invalid name redefinition. 10951 Diag(Loc, diag::err_redefinition_different_kind) 10952 << II; 10953 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10954 IsInvalid = true; 10955 // Continue on to push Namespc as current DeclContext and return it. 10956 } else if (II->isStr("std") && 10957 CurContext->getRedeclContext()->isTranslationUnit()) { 10958 // This is the first "real" definition of the namespace "std", so update 10959 // our cache of the "std" namespace to point at this definition. 10960 PrevNS = getStdNamespace(); 10961 IsStd = true; 10962 AddToKnown = !IsInline; 10963 } else { 10964 // We've seen this namespace for the first time. 10965 AddToKnown = !IsInline; 10966 } 10967 } else { 10968 // Anonymous namespaces. 10969 10970 // Determine whether the parent already has an anonymous namespace. 10971 DeclContext *Parent = CurContext->getRedeclContext(); 10972 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10973 PrevNS = TU->getAnonymousNamespace(); 10974 } else { 10975 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10976 PrevNS = ND->getAnonymousNamespace(); 10977 } 10978 10979 if (PrevNS && IsInline != PrevNS->isInline()) 10980 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10981 &IsInline, PrevNS); 10982 } 10983 10984 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10985 StartLoc, Loc, II, PrevNS); 10986 if (IsInvalid) 10987 Namespc->setInvalidDecl(); 10988 10989 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10990 AddPragmaAttributes(DeclRegionScope, Namespc); 10991 10992 // FIXME: Should we be merging attributes? 10993 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10994 PushNamespaceVisibilityAttr(Attr, Loc); 10995 10996 if (IsStd) 10997 StdNamespace = Namespc; 10998 if (AddToKnown) 10999 KnownNamespaces[Namespc] = false; 11000 11001 if (II) { 11002 PushOnScopeChains(Namespc, DeclRegionScope); 11003 } else { 11004 // Link the anonymous namespace into its parent. 11005 DeclContext *Parent = CurContext->getRedeclContext(); 11006 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11007 TU->setAnonymousNamespace(Namespc); 11008 } else { 11009 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11010 } 11011 11012 CurContext->addDecl(Namespc); 11013 11014 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11015 // behaves as if it were replaced by 11016 // namespace unique { /* empty body */ } 11017 // using namespace unique; 11018 // namespace unique { namespace-body } 11019 // where all occurrences of 'unique' in a translation unit are 11020 // replaced by the same identifier and this identifier differs 11021 // from all other identifiers in the entire program. 11022 11023 // We just create the namespace with an empty name and then add an 11024 // implicit using declaration, just like the standard suggests. 11025 // 11026 // CodeGen enforces the "universally unique" aspect by giving all 11027 // declarations semantically contained within an anonymous 11028 // namespace internal linkage. 11029 11030 if (!PrevNS) { 11031 UD = UsingDirectiveDecl::Create(Context, Parent, 11032 /* 'using' */ LBrace, 11033 /* 'namespace' */ SourceLocation(), 11034 /* qualifier */ NestedNameSpecifierLoc(), 11035 /* identifier */ SourceLocation(), 11036 Namespc, 11037 /* Ancestor */ Parent); 11038 UD->setImplicit(); 11039 Parent->addDecl(UD); 11040 } 11041 } 11042 11043 ActOnDocumentableDecl(Namespc); 11044 11045 // Although we could have an invalid decl (i.e. the namespace name is a 11046 // redefinition), push it as current DeclContext and try to continue parsing. 11047 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11048 // for the namespace has the declarations that showed up in that particular 11049 // namespace definition. 11050 PushDeclContext(NamespcScope, Namespc); 11051 return Namespc; 11052 } 11053 11054 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11055 /// is a namespace alias, returns the namespace it points to. 11056 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11057 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11058 return AD->getNamespace(); 11059 return dyn_cast_or_null<NamespaceDecl>(D); 11060 } 11061 11062 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11063 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11064 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11065 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11066 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11067 Namespc->setRBraceLoc(RBrace); 11068 PopDeclContext(); 11069 if (Namespc->hasAttr<VisibilityAttr>()) 11070 PopPragmaVisibility(true, RBrace); 11071 // If this namespace contains an export-declaration, export it now. 11072 if (DeferredExportedNamespaces.erase(Namespc)) 11073 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11074 } 11075 11076 CXXRecordDecl *Sema::getStdBadAlloc() const { 11077 return cast_or_null<CXXRecordDecl>( 11078 StdBadAlloc.get(Context.getExternalSource())); 11079 } 11080 11081 EnumDecl *Sema::getStdAlignValT() const { 11082 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11083 } 11084 11085 NamespaceDecl *Sema::getStdNamespace() const { 11086 return cast_or_null<NamespaceDecl>( 11087 StdNamespace.get(Context.getExternalSource())); 11088 } 11089 11090 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11091 if (!StdExperimentalNamespaceCache) { 11092 if (auto Std = getStdNamespace()) { 11093 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11094 SourceLocation(), LookupNamespaceName); 11095 if (!LookupQualifiedName(Result, Std) || 11096 !(StdExperimentalNamespaceCache = 11097 Result.getAsSingle<NamespaceDecl>())) 11098 Result.suppressDiagnostics(); 11099 } 11100 } 11101 return StdExperimentalNamespaceCache; 11102 } 11103 11104 namespace { 11105 11106 enum UnsupportedSTLSelect { 11107 USS_InvalidMember, 11108 USS_MissingMember, 11109 USS_NonTrivial, 11110 USS_Other 11111 }; 11112 11113 struct InvalidSTLDiagnoser { 11114 Sema &S; 11115 SourceLocation Loc; 11116 QualType TyForDiags; 11117 11118 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11119 const VarDecl *VD = nullptr) { 11120 { 11121 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11122 << TyForDiags << ((int)Sel); 11123 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11124 assert(!Name.empty()); 11125 D << Name; 11126 } 11127 } 11128 if (Sel == USS_InvalidMember) { 11129 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11130 << VD << VD->getSourceRange(); 11131 } 11132 return QualType(); 11133 } 11134 }; 11135 } // namespace 11136 11137 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11138 SourceLocation Loc, 11139 ComparisonCategoryUsage Usage) { 11140 assert(getLangOpts().CPlusPlus && 11141 "Looking for comparison category type outside of C++."); 11142 11143 // Use an elaborated type for diagnostics which has a name containing the 11144 // prepended 'std' namespace but not any inline namespace names. 11145 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11146 auto *NNS = 11147 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11148 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11149 }; 11150 11151 // Check if we've already successfully checked the comparison category type 11152 // before. If so, skip checking it again. 11153 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11154 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11155 // The only thing we need to check is that the type has a reachable 11156 // definition in the current context. 11157 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11158 return QualType(); 11159 11160 return Info->getType(); 11161 } 11162 11163 // If lookup failed 11164 if (!Info) { 11165 std::string NameForDiags = "std::"; 11166 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11167 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11168 << NameForDiags << (int)Usage; 11169 return QualType(); 11170 } 11171 11172 assert(Info->Kind == Kind); 11173 assert(Info->Record); 11174 11175 // Update the Record decl in case we encountered a forward declaration on our 11176 // first pass. FIXME: This is a bit of a hack. 11177 if (Info->Record->hasDefinition()) 11178 Info->Record = Info->Record->getDefinition(); 11179 11180 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11181 return QualType(); 11182 11183 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11184 11185 if (!Info->Record->isTriviallyCopyable()) 11186 return UnsupportedSTLError(USS_NonTrivial); 11187 11188 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11189 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11190 // Tolerate empty base classes. 11191 if (Base->isEmpty()) 11192 continue; 11193 // Reject STL implementations which have at least one non-empty base. 11194 return UnsupportedSTLError(); 11195 } 11196 11197 // Check that the STL has implemented the types using a single integer field. 11198 // This expectation allows better codegen for builtin operators. We require: 11199 // (1) The class has exactly one field. 11200 // (2) The field is an integral or enumeration type. 11201 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11202 if (std::distance(FIt, FEnd) != 1 || 11203 !FIt->getType()->isIntegralOrEnumerationType()) { 11204 return UnsupportedSTLError(); 11205 } 11206 11207 // Build each of the require values and store them in Info. 11208 for (ComparisonCategoryResult CCR : 11209 ComparisonCategories::getPossibleResultsForType(Kind)) { 11210 StringRef MemName = ComparisonCategories::getResultString(CCR); 11211 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11212 11213 if (!ValInfo) 11214 return UnsupportedSTLError(USS_MissingMember, MemName); 11215 11216 VarDecl *VD = ValInfo->VD; 11217 assert(VD && "should not be null!"); 11218 11219 // Attempt to diagnose reasons why the STL definition of this type 11220 // might be foobar, including it failing to be a constant expression. 11221 // TODO Handle more ways the lookup or result can be invalid. 11222 if (!VD->isStaticDataMember() || 11223 !VD->isUsableInConstantExpressions(Context)) 11224 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11225 11226 // Attempt to evaluate the var decl as a constant expression and extract 11227 // the value of its first field as a ICE. If this fails, the STL 11228 // implementation is not supported. 11229 if (!ValInfo->hasValidIntValue()) 11230 return UnsupportedSTLError(); 11231 11232 MarkVariableReferenced(Loc, VD); 11233 } 11234 11235 // We've successfully built the required types and expressions. Update 11236 // the cache and return the newly cached value. 11237 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11238 return Info->getType(); 11239 } 11240 11241 /// Retrieve the special "std" namespace, which may require us to 11242 /// implicitly define the namespace. 11243 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11244 if (!StdNamespace) { 11245 // The "std" namespace has not yet been defined, so build one implicitly. 11246 StdNamespace = NamespaceDecl::Create(Context, 11247 Context.getTranslationUnitDecl(), 11248 /*Inline=*/false, 11249 SourceLocation(), SourceLocation(), 11250 &PP.getIdentifierTable().get("std"), 11251 /*PrevDecl=*/nullptr); 11252 getStdNamespace()->setImplicit(true); 11253 } 11254 11255 return getStdNamespace(); 11256 } 11257 11258 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11259 assert(getLangOpts().CPlusPlus && 11260 "Looking for std::initializer_list outside of C++."); 11261 11262 // We're looking for implicit instantiations of 11263 // template <typename E> class std::initializer_list. 11264 11265 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11266 return false; 11267 11268 ClassTemplateDecl *Template = nullptr; 11269 const TemplateArgument *Arguments = nullptr; 11270 11271 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11272 11273 ClassTemplateSpecializationDecl *Specialization = 11274 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11275 if (!Specialization) 11276 return false; 11277 11278 Template = Specialization->getSpecializedTemplate(); 11279 Arguments = Specialization->getTemplateArgs().data(); 11280 } else if (const TemplateSpecializationType *TST = 11281 Ty->getAs<TemplateSpecializationType>()) { 11282 Template = dyn_cast_or_null<ClassTemplateDecl>( 11283 TST->getTemplateName().getAsTemplateDecl()); 11284 Arguments = TST->getArgs(); 11285 } 11286 if (!Template) 11287 return false; 11288 11289 if (!StdInitializerList) { 11290 // Haven't recognized std::initializer_list yet, maybe this is it. 11291 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11292 if (TemplateClass->getIdentifier() != 11293 &PP.getIdentifierTable().get("initializer_list") || 11294 !getStdNamespace()->InEnclosingNamespaceSetOf( 11295 TemplateClass->getDeclContext())) 11296 return false; 11297 // This is a template called std::initializer_list, but is it the right 11298 // template? 11299 TemplateParameterList *Params = Template->getTemplateParameters(); 11300 if (Params->getMinRequiredArguments() != 1) 11301 return false; 11302 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11303 return false; 11304 11305 // It's the right template. 11306 StdInitializerList = Template; 11307 } 11308 11309 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11310 return false; 11311 11312 // This is an instance of std::initializer_list. Find the argument type. 11313 if (Element) 11314 *Element = Arguments[0].getAsType(); 11315 return true; 11316 } 11317 11318 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11319 NamespaceDecl *Std = S.getStdNamespace(); 11320 if (!Std) { 11321 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11322 return nullptr; 11323 } 11324 11325 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11326 Loc, Sema::LookupOrdinaryName); 11327 if (!S.LookupQualifiedName(Result, Std)) { 11328 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11329 return nullptr; 11330 } 11331 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11332 if (!Template) { 11333 Result.suppressDiagnostics(); 11334 // We found something weird. Complain about the first thing we found. 11335 NamedDecl *Found = *Result.begin(); 11336 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11337 return nullptr; 11338 } 11339 11340 // We found some template called std::initializer_list. Now verify that it's 11341 // correct. 11342 TemplateParameterList *Params = Template->getTemplateParameters(); 11343 if (Params->getMinRequiredArguments() != 1 || 11344 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11345 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11346 return nullptr; 11347 } 11348 11349 return Template; 11350 } 11351 11352 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11353 if (!StdInitializerList) { 11354 StdInitializerList = LookupStdInitializerList(*this, Loc); 11355 if (!StdInitializerList) 11356 return QualType(); 11357 } 11358 11359 TemplateArgumentListInfo Args(Loc, Loc); 11360 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11361 Context.getTrivialTypeSourceInfo(Element, 11362 Loc))); 11363 return Context.getCanonicalType( 11364 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11365 } 11366 11367 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11368 // C++ [dcl.init.list]p2: 11369 // A constructor is an initializer-list constructor if its first parameter 11370 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11371 // std::initializer_list<E> for some type E, and either there are no other 11372 // parameters or else all other parameters have default arguments. 11373 if (!Ctor->hasOneParamOrDefaultArgs()) 11374 return false; 11375 11376 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11377 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11378 ArgType = RT->getPointeeType().getUnqualifiedType(); 11379 11380 return isStdInitializerList(ArgType, nullptr); 11381 } 11382 11383 /// Determine whether a using statement is in a context where it will be 11384 /// apply in all contexts. 11385 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11386 switch (CurContext->getDeclKind()) { 11387 case Decl::TranslationUnit: 11388 return true; 11389 case Decl::LinkageSpec: 11390 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11391 default: 11392 return false; 11393 } 11394 } 11395 11396 namespace { 11397 11398 // Callback to only accept typo corrections that are namespaces. 11399 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11400 public: 11401 bool ValidateCandidate(const TypoCorrection &candidate) override { 11402 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11403 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11404 return false; 11405 } 11406 11407 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11408 return std::make_unique<NamespaceValidatorCCC>(*this); 11409 } 11410 }; 11411 11412 } 11413 11414 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11415 CXXScopeSpec &SS, 11416 SourceLocation IdentLoc, 11417 IdentifierInfo *Ident) { 11418 R.clear(); 11419 NamespaceValidatorCCC CCC{}; 11420 if (TypoCorrection Corrected = 11421 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11422 Sema::CTK_ErrorRecovery)) { 11423 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11424 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11425 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11426 Ident->getName().equals(CorrectedStr); 11427 S.diagnoseTypo(Corrected, 11428 S.PDiag(diag::err_using_directive_member_suggest) 11429 << Ident << DC << DroppedSpecifier << SS.getRange(), 11430 S.PDiag(diag::note_namespace_defined_here)); 11431 } else { 11432 S.diagnoseTypo(Corrected, 11433 S.PDiag(diag::err_using_directive_suggest) << Ident, 11434 S.PDiag(diag::note_namespace_defined_here)); 11435 } 11436 R.addDecl(Corrected.getFoundDecl()); 11437 return true; 11438 } 11439 return false; 11440 } 11441 11442 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11443 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11444 SourceLocation IdentLoc, 11445 IdentifierInfo *NamespcName, 11446 const ParsedAttributesView &AttrList) { 11447 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11448 assert(NamespcName && "Invalid NamespcName."); 11449 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11450 11451 // This can only happen along a recovery path. 11452 while (S->isTemplateParamScope()) 11453 S = S->getParent(); 11454 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11455 11456 UsingDirectiveDecl *UDir = nullptr; 11457 NestedNameSpecifier *Qualifier = nullptr; 11458 if (SS.isSet()) 11459 Qualifier = SS.getScopeRep(); 11460 11461 // Lookup namespace name. 11462 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11463 LookupParsedName(R, S, &SS); 11464 if (R.isAmbiguous()) 11465 return nullptr; 11466 11467 if (R.empty()) { 11468 R.clear(); 11469 // Allow "using namespace std;" or "using namespace ::std;" even if 11470 // "std" hasn't been defined yet, for GCC compatibility. 11471 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11472 NamespcName->isStr("std")) { 11473 Diag(IdentLoc, diag::ext_using_undefined_std); 11474 R.addDecl(getOrCreateStdNamespace()); 11475 R.resolveKind(); 11476 } 11477 // Otherwise, attempt typo correction. 11478 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11479 } 11480 11481 if (!R.empty()) { 11482 NamedDecl *Named = R.getRepresentativeDecl(); 11483 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11484 assert(NS && "expected namespace decl"); 11485 11486 // The use of a nested name specifier may trigger deprecation warnings. 11487 DiagnoseUseOfDecl(Named, IdentLoc); 11488 11489 // C++ [namespace.udir]p1: 11490 // A using-directive specifies that the names in the nominated 11491 // namespace can be used in the scope in which the 11492 // using-directive appears after the using-directive. During 11493 // unqualified name lookup (3.4.1), the names appear as if they 11494 // were declared in the nearest enclosing namespace which 11495 // contains both the using-directive and the nominated 11496 // namespace. [Note: in this context, "contains" means "contains 11497 // directly or indirectly". ] 11498 11499 // Find enclosing context containing both using-directive and 11500 // nominated namespace. 11501 DeclContext *CommonAncestor = NS; 11502 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11503 CommonAncestor = CommonAncestor->getParent(); 11504 11505 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11506 SS.getWithLocInContext(Context), 11507 IdentLoc, Named, CommonAncestor); 11508 11509 if (IsUsingDirectiveInToplevelContext(CurContext) && 11510 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11511 Diag(IdentLoc, diag::warn_using_directive_in_header); 11512 } 11513 11514 PushUsingDirective(S, UDir); 11515 } else { 11516 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11517 } 11518 11519 if (UDir) 11520 ProcessDeclAttributeList(S, UDir, AttrList); 11521 11522 return UDir; 11523 } 11524 11525 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11526 // If the scope has an associated entity and the using directive is at 11527 // namespace or translation unit scope, add the UsingDirectiveDecl into 11528 // its lookup structure so qualified name lookup can find it. 11529 DeclContext *Ctx = S->getEntity(); 11530 if (Ctx && !Ctx->isFunctionOrMethod()) 11531 Ctx->addDecl(UDir); 11532 else 11533 // Otherwise, it is at block scope. The using-directives will affect lookup 11534 // only to the end of the scope. 11535 S->PushUsingDirective(UDir); 11536 } 11537 11538 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11539 SourceLocation UsingLoc, 11540 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11541 UnqualifiedId &Name, 11542 SourceLocation EllipsisLoc, 11543 const ParsedAttributesView &AttrList) { 11544 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11545 11546 if (SS.isEmpty()) { 11547 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11548 return nullptr; 11549 } 11550 11551 switch (Name.getKind()) { 11552 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11553 case UnqualifiedIdKind::IK_Identifier: 11554 case UnqualifiedIdKind::IK_OperatorFunctionId: 11555 case UnqualifiedIdKind::IK_LiteralOperatorId: 11556 case UnqualifiedIdKind::IK_ConversionFunctionId: 11557 break; 11558 11559 case UnqualifiedIdKind::IK_ConstructorName: 11560 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11561 // C++11 inheriting constructors. 11562 Diag(Name.getBeginLoc(), 11563 getLangOpts().CPlusPlus11 11564 ? diag::warn_cxx98_compat_using_decl_constructor 11565 : diag::err_using_decl_constructor) 11566 << SS.getRange(); 11567 11568 if (getLangOpts().CPlusPlus11) break; 11569 11570 return nullptr; 11571 11572 case UnqualifiedIdKind::IK_DestructorName: 11573 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11574 return nullptr; 11575 11576 case UnqualifiedIdKind::IK_TemplateId: 11577 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11578 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11579 return nullptr; 11580 11581 case UnqualifiedIdKind::IK_DeductionGuideName: 11582 llvm_unreachable("cannot parse qualified deduction guide name"); 11583 } 11584 11585 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11586 DeclarationName TargetName = TargetNameInfo.getName(); 11587 if (!TargetName) 11588 return nullptr; 11589 11590 // Warn about access declarations. 11591 if (UsingLoc.isInvalid()) { 11592 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11593 ? diag::err_access_decl 11594 : diag::warn_access_decl_deprecated) 11595 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11596 } 11597 11598 if (EllipsisLoc.isInvalid()) { 11599 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11600 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11601 return nullptr; 11602 } else { 11603 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11604 !TargetNameInfo.containsUnexpandedParameterPack()) { 11605 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11606 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11607 EllipsisLoc = SourceLocation(); 11608 } 11609 } 11610 11611 NamedDecl *UD = 11612 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11613 SS, TargetNameInfo, EllipsisLoc, AttrList, 11614 /*IsInstantiation*/false); 11615 if (UD) 11616 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11617 11618 return UD; 11619 } 11620 11621 /// Determine whether a using declaration considers the given 11622 /// declarations as "equivalent", e.g., if they are redeclarations of 11623 /// the same entity or are both typedefs of the same type. 11624 static bool 11625 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11626 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11627 return true; 11628 11629 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11630 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11631 return Context.hasSameType(TD1->getUnderlyingType(), 11632 TD2->getUnderlyingType()); 11633 11634 return false; 11635 } 11636 11637 11638 /// Determines whether to create a using shadow decl for a particular 11639 /// decl, given the set of decls existing prior to this using lookup. 11640 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11641 const LookupResult &Previous, 11642 UsingShadowDecl *&PrevShadow) { 11643 // Diagnose finding a decl which is not from a base class of the 11644 // current class. We do this now because there are cases where this 11645 // function will silently decide not to build a shadow decl, which 11646 // will pre-empt further diagnostics. 11647 // 11648 // We don't need to do this in C++11 because we do the check once on 11649 // the qualifier. 11650 // 11651 // FIXME: diagnose the following if we care enough: 11652 // struct A { int foo; }; 11653 // struct B : A { using A::foo; }; 11654 // template <class T> struct C : A {}; 11655 // template <class T> struct D : C<T> { using B::foo; } // <--- 11656 // This is invalid (during instantiation) in C++03 because B::foo 11657 // resolves to the using decl in B, which is not a base class of D<T>. 11658 // We can't diagnose it immediately because C<T> is an unknown 11659 // specialization. The UsingShadowDecl in D<T> then points directly 11660 // to A::foo, which will look well-formed when we instantiate. 11661 // The right solution is to not collapse the shadow-decl chain. 11662 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11663 DeclContext *OrigDC = Orig->getDeclContext(); 11664 11665 // Handle enums and anonymous structs. 11666 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11667 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11668 while (OrigRec->isAnonymousStructOrUnion()) 11669 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11670 11671 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11672 if (OrigDC == CurContext) { 11673 Diag(Using->getLocation(), 11674 diag::err_using_decl_nested_name_specifier_is_current_class) 11675 << Using->getQualifierLoc().getSourceRange(); 11676 Diag(Orig->getLocation(), diag::note_using_decl_target); 11677 Using->setInvalidDecl(); 11678 return true; 11679 } 11680 11681 Diag(Using->getQualifierLoc().getBeginLoc(), 11682 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11683 << Using->getQualifier() 11684 << cast<CXXRecordDecl>(CurContext) 11685 << Using->getQualifierLoc().getSourceRange(); 11686 Diag(Orig->getLocation(), diag::note_using_decl_target); 11687 Using->setInvalidDecl(); 11688 return true; 11689 } 11690 } 11691 11692 if (Previous.empty()) return false; 11693 11694 NamedDecl *Target = Orig; 11695 if (isa<UsingShadowDecl>(Target)) 11696 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11697 11698 // If the target happens to be one of the previous declarations, we 11699 // don't have a conflict. 11700 // 11701 // FIXME: but we might be increasing its access, in which case we 11702 // should redeclare it. 11703 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11704 bool FoundEquivalentDecl = false; 11705 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11706 I != E; ++I) { 11707 NamedDecl *D = (*I)->getUnderlyingDecl(); 11708 // We can have UsingDecls in our Previous results because we use the same 11709 // LookupResult for checking whether the UsingDecl itself is a valid 11710 // redeclaration. 11711 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11712 continue; 11713 11714 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11715 // C++ [class.mem]p19: 11716 // If T is the name of a class, then [every named member other than 11717 // a non-static data member] shall have a name different from T 11718 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11719 !isa<IndirectFieldDecl>(Target) && 11720 !isa<UnresolvedUsingValueDecl>(Target) && 11721 DiagnoseClassNameShadow( 11722 CurContext, 11723 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11724 return true; 11725 } 11726 11727 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11728 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11729 PrevShadow = Shadow; 11730 FoundEquivalentDecl = true; 11731 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11732 // We don't conflict with an existing using shadow decl of an equivalent 11733 // declaration, but we're not a redeclaration of it. 11734 FoundEquivalentDecl = true; 11735 } 11736 11737 if (isVisible(D)) 11738 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11739 } 11740 11741 if (FoundEquivalentDecl) 11742 return false; 11743 11744 if (FunctionDecl *FD = Target->getAsFunction()) { 11745 NamedDecl *OldDecl = nullptr; 11746 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11747 /*IsForUsingDecl*/ true)) { 11748 case Ovl_Overload: 11749 return false; 11750 11751 case Ovl_NonFunction: 11752 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11753 break; 11754 11755 // We found a decl with the exact signature. 11756 case Ovl_Match: 11757 // If we're in a record, we want to hide the target, so we 11758 // return true (without a diagnostic) to tell the caller not to 11759 // build a shadow decl. 11760 if (CurContext->isRecord()) 11761 return true; 11762 11763 // If we're not in a record, this is an error. 11764 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11765 break; 11766 } 11767 11768 Diag(Target->getLocation(), diag::note_using_decl_target); 11769 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11770 Using->setInvalidDecl(); 11771 return true; 11772 } 11773 11774 // Target is not a function. 11775 11776 if (isa<TagDecl>(Target)) { 11777 // No conflict between a tag and a non-tag. 11778 if (!Tag) return false; 11779 11780 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11781 Diag(Target->getLocation(), diag::note_using_decl_target); 11782 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11783 Using->setInvalidDecl(); 11784 return true; 11785 } 11786 11787 // No conflict between a tag and a non-tag. 11788 if (!NonTag) return false; 11789 11790 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11791 Diag(Target->getLocation(), diag::note_using_decl_target); 11792 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11793 Using->setInvalidDecl(); 11794 return true; 11795 } 11796 11797 /// Determine whether a direct base class is a virtual base class. 11798 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11799 if (!Derived->getNumVBases()) 11800 return false; 11801 for (auto &B : Derived->bases()) 11802 if (B.getType()->getAsCXXRecordDecl() == Base) 11803 return B.isVirtual(); 11804 llvm_unreachable("not a direct base class"); 11805 } 11806 11807 /// Builds a shadow declaration corresponding to a 'using' declaration. 11808 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11809 UsingDecl *UD, 11810 NamedDecl *Orig, 11811 UsingShadowDecl *PrevDecl) { 11812 // If we resolved to another shadow declaration, just coalesce them. 11813 NamedDecl *Target = Orig; 11814 if (isa<UsingShadowDecl>(Target)) { 11815 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11816 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11817 } 11818 11819 NamedDecl *NonTemplateTarget = Target; 11820 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11821 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11822 11823 UsingShadowDecl *Shadow; 11824 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11825 bool IsVirtualBase = 11826 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11827 UD->getQualifier()->getAsRecordDecl()); 11828 Shadow = ConstructorUsingShadowDecl::Create( 11829 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11830 } else { 11831 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11832 Target); 11833 } 11834 UD->addShadowDecl(Shadow); 11835 11836 Shadow->setAccess(UD->getAccess()); 11837 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11838 Shadow->setInvalidDecl(); 11839 11840 Shadow->setPreviousDecl(PrevDecl); 11841 11842 if (S) 11843 PushOnScopeChains(Shadow, S); 11844 else 11845 CurContext->addDecl(Shadow); 11846 11847 11848 return Shadow; 11849 } 11850 11851 /// Hides a using shadow declaration. This is required by the current 11852 /// using-decl implementation when a resolvable using declaration in a 11853 /// class is followed by a declaration which would hide or override 11854 /// one or more of the using decl's targets; for example: 11855 /// 11856 /// struct Base { void foo(int); }; 11857 /// struct Derived : Base { 11858 /// using Base::foo; 11859 /// void foo(int); 11860 /// }; 11861 /// 11862 /// The governing language is C++03 [namespace.udecl]p12: 11863 /// 11864 /// When a using-declaration brings names from a base class into a 11865 /// derived class scope, member functions in the derived class 11866 /// override and/or hide member functions with the same name and 11867 /// parameter types in a base class (rather than conflicting). 11868 /// 11869 /// There are two ways to implement this: 11870 /// (1) optimistically create shadow decls when they're not hidden 11871 /// by existing declarations, or 11872 /// (2) don't create any shadow decls (or at least don't make them 11873 /// visible) until we've fully parsed/instantiated the class. 11874 /// The problem with (1) is that we might have to retroactively remove 11875 /// a shadow decl, which requires several O(n) operations because the 11876 /// decl structures are (very reasonably) not designed for removal. 11877 /// (2) avoids this but is very fiddly and phase-dependent. 11878 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11879 if (Shadow->getDeclName().getNameKind() == 11880 DeclarationName::CXXConversionFunctionName) 11881 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11882 11883 // Remove it from the DeclContext... 11884 Shadow->getDeclContext()->removeDecl(Shadow); 11885 11886 // ...and the scope, if applicable... 11887 if (S) { 11888 S->RemoveDecl(Shadow); 11889 IdResolver.RemoveDecl(Shadow); 11890 } 11891 11892 // ...and the using decl. 11893 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11894 11895 // TODO: complain somehow if Shadow was used. It shouldn't 11896 // be possible for this to happen, because...? 11897 } 11898 11899 /// Find the base specifier for a base class with the given type. 11900 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11901 QualType DesiredBase, 11902 bool &AnyDependentBases) { 11903 // Check whether the named type is a direct base class. 11904 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11905 .getUnqualifiedType(); 11906 for (auto &Base : Derived->bases()) { 11907 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11908 if (CanonicalDesiredBase == BaseType) 11909 return &Base; 11910 if (BaseType->isDependentType()) 11911 AnyDependentBases = true; 11912 } 11913 return nullptr; 11914 } 11915 11916 namespace { 11917 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11918 public: 11919 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11920 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11921 : HasTypenameKeyword(HasTypenameKeyword), 11922 IsInstantiation(IsInstantiation), OldNNS(NNS), 11923 RequireMemberOf(RequireMemberOf) {} 11924 11925 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11926 NamedDecl *ND = Candidate.getCorrectionDecl(); 11927 11928 // Keywords are not valid here. 11929 if (!ND || isa<NamespaceDecl>(ND)) 11930 return false; 11931 11932 // Completely unqualified names are invalid for a 'using' declaration. 11933 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11934 return false; 11935 11936 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11937 // reject. 11938 11939 if (RequireMemberOf) { 11940 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11941 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11942 // No-one ever wants a using-declaration to name an injected-class-name 11943 // of a base class, unless they're declaring an inheriting constructor. 11944 ASTContext &Ctx = ND->getASTContext(); 11945 if (!Ctx.getLangOpts().CPlusPlus11) 11946 return false; 11947 QualType FoundType = Ctx.getRecordType(FoundRecord); 11948 11949 // Check that the injected-class-name is named as a member of its own 11950 // type; we don't want to suggest 'using Derived::Base;', since that 11951 // means something else. 11952 NestedNameSpecifier *Specifier = 11953 Candidate.WillReplaceSpecifier() 11954 ? Candidate.getCorrectionSpecifier() 11955 : OldNNS; 11956 if (!Specifier->getAsType() || 11957 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11958 return false; 11959 11960 // Check that this inheriting constructor declaration actually names a 11961 // direct base class of the current class. 11962 bool AnyDependentBases = false; 11963 if (!findDirectBaseWithType(RequireMemberOf, 11964 Ctx.getRecordType(FoundRecord), 11965 AnyDependentBases) && 11966 !AnyDependentBases) 11967 return false; 11968 } else { 11969 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11970 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11971 return false; 11972 11973 // FIXME: Check that the base class member is accessible? 11974 } 11975 } else { 11976 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11977 if (FoundRecord && FoundRecord->isInjectedClassName()) 11978 return false; 11979 } 11980 11981 if (isa<TypeDecl>(ND)) 11982 return HasTypenameKeyword || !IsInstantiation; 11983 11984 return !HasTypenameKeyword; 11985 } 11986 11987 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11988 return std::make_unique<UsingValidatorCCC>(*this); 11989 } 11990 11991 private: 11992 bool HasTypenameKeyword; 11993 bool IsInstantiation; 11994 NestedNameSpecifier *OldNNS; 11995 CXXRecordDecl *RequireMemberOf; 11996 }; 11997 } // end anonymous namespace 11998 11999 /// Builds a using declaration. 12000 /// 12001 /// \param IsInstantiation - Whether this call arises from an 12002 /// instantiation of an unresolved using declaration. We treat 12003 /// the lookup differently for these declarations. 12004 NamedDecl *Sema::BuildUsingDeclaration( 12005 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12006 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12007 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12008 const ParsedAttributesView &AttrList, bool IsInstantiation) { 12009 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12010 SourceLocation IdentLoc = NameInfo.getLoc(); 12011 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12012 12013 // FIXME: We ignore attributes for now. 12014 12015 // For an inheriting constructor declaration, the name of the using 12016 // declaration is the name of a constructor in this class, not in the 12017 // base class. 12018 DeclarationNameInfo UsingName = NameInfo; 12019 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12020 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12021 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12022 Context.getCanonicalType(Context.getRecordType(RD)))); 12023 12024 // Do the redeclaration lookup in the current scope. 12025 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12026 ForVisibleRedeclaration); 12027 Previous.setHideTags(false); 12028 if (S) { 12029 LookupName(Previous, S); 12030 12031 // It is really dumb that we have to do this. 12032 LookupResult::Filter F = Previous.makeFilter(); 12033 while (F.hasNext()) { 12034 NamedDecl *D = F.next(); 12035 if (!isDeclInScope(D, CurContext, S)) 12036 F.erase(); 12037 // If we found a local extern declaration that's not ordinarily visible, 12038 // and this declaration is being added to a non-block scope, ignore it. 12039 // We're only checking for scope conflicts here, not also for violations 12040 // of the linkage rules. 12041 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12042 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12043 F.erase(); 12044 } 12045 F.done(); 12046 } else { 12047 assert(IsInstantiation && "no scope in non-instantiation"); 12048 if (CurContext->isRecord()) 12049 LookupQualifiedName(Previous, CurContext); 12050 else { 12051 // No redeclaration check is needed here; in non-member contexts we 12052 // diagnosed all possible conflicts with other using-declarations when 12053 // building the template: 12054 // 12055 // For a dependent non-type using declaration, the only valid case is 12056 // if we instantiate to a single enumerator. We check for conflicts 12057 // between shadow declarations we introduce, and we check in the template 12058 // definition for conflicts between a non-type using declaration and any 12059 // other declaration, which together covers all cases. 12060 // 12061 // A dependent typename using declaration will never successfully 12062 // instantiate, since it will always name a class member, so we reject 12063 // that in the template definition. 12064 } 12065 } 12066 12067 // Check for invalid redeclarations. 12068 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12069 SS, IdentLoc, Previous)) 12070 return nullptr; 12071 12072 // Check for bad qualifiers. 12073 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12074 IdentLoc)) 12075 return nullptr; 12076 12077 DeclContext *LookupContext = computeDeclContext(SS); 12078 NamedDecl *D; 12079 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12080 if (!LookupContext || EllipsisLoc.isValid()) { 12081 if (HasTypenameKeyword) { 12082 // FIXME: not all declaration name kinds are legal here 12083 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12084 UsingLoc, TypenameLoc, 12085 QualifierLoc, 12086 IdentLoc, NameInfo.getName(), 12087 EllipsisLoc); 12088 } else { 12089 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12090 QualifierLoc, NameInfo, EllipsisLoc); 12091 } 12092 D->setAccess(AS); 12093 CurContext->addDecl(D); 12094 return D; 12095 } 12096 12097 auto Build = [&](bool Invalid) { 12098 UsingDecl *UD = 12099 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12100 UsingName, HasTypenameKeyword); 12101 UD->setAccess(AS); 12102 CurContext->addDecl(UD); 12103 UD->setInvalidDecl(Invalid); 12104 return UD; 12105 }; 12106 auto BuildInvalid = [&]{ return Build(true); }; 12107 auto BuildValid = [&]{ return Build(false); }; 12108 12109 if (RequireCompleteDeclContext(SS, LookupContext)) 12110 return BuildInvalid(); 12111 12112 // Look up the target name. 12113 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12114 12115 // Unlike most lookups, we don't always want to hide tag 12116 // declarations: tag names are visible through the using declaration 12117 // even if hidden by ordinary names, *except* in a dependent context 12118 // where it's important for the sanity of two-phase lookup. 12119 if (!IsInstantiation) 12120 R.setHideTags(false); 12121 12122 // For the purposes of this lookup, we have a base object type 12123 // equal to that of the current context. 12124 if (CurContext->isRecord()) { 12125 R.setBaseObjectType( 12126 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12127 } 12128 12129 LookupQualifiedName(R, LookupContext); 12130 12131 // Try to correct typos if possible. If constructor name lookup finds no 12132 // results, that means the named class has no explicit constructors, and we 12133 // suppressed declaring implicit ones (probably because it's dependent or 12134 // invalid). 12135 if (R.empty() && 12136 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12137 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12138 // it will believe that glibc provides a ::gets in cases where it does not, 12139 // and will try to pull it into namespace std with a using-declaration. 12140 // Just ignore the using-declaration in that case. 12141 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12142 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12143 CurContext->isStdNamespace() && 12144 isa<TranslationUnitDecl>(LookupContext) && 12145 getSourceManager().isInSystemHeader(UsingLoc)) 12146 return nullptr; 12147 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12148 dyn_cast<CXXRecordDecl>(CurContext)); 12149 if (TypoCorrection Corrected = 12150 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12151 CTK_ErrorRecovery)) { 12152 // We reject candidates where DroppedSpecifier == true, hence the 12153 // literal '0' below. 12154 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12155 << NameInfo.getName() << LookupContext << 0 12156 << SS.getRange()); 12157 12158 // If we picked a correction with no attached Decl we can't do anything 12159 // useful with it, bail out. 12160 NamedDecl *ND = Corrected.getCorrectionDecl(); 12161 if (!ND) 12162 return BuildInvalid(); 12163 12164 // If we corrected to an inheriting constructor, handle it as one. 12165 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12166 if (RD && RD->isInjectedClassName()) { 12167 // The parent of the injected class name is the class itself. 12168 RD = cast<CXXRecordDecl>(RD->getParent()); 12169 12170 // Fix up the information we'll use to build the using declaration. 12171 if (Corrected.WillReplaceSpecifier()) { 12172 NestedNameSpecifierLocBuilder Builder; 12173 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12174 QualifierLoc.getSourceRange()); 12175 QualifierLoc = Builder.getWithLocInContext(Context); 12176 } 12177 12178 // In this case, the name we introduce is the name of a derived class 12179 // constructor. 12180 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12181 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12182 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12183 UsingName.setNamedTypeInfo(nullptr); 12184 for (auto *Ctor : LookupConstructors(RD)) 12185 R.addDecl(Ctor); 12186 R.resolveKind(); 12187 } else { 12188 // FIXME: Pick up all the declarations if we found an overloaded 12189 // function. 12190 UsingName.setName(ND->getDeclName()); 12191 R.addDecl(ND); 12192 } 12193 } else { 12194 Diag(IdentLoc, diag::err_no_member) 12195 << NameInfo.getName() << LookupContext << SS.getRange(); 12196 return BuildInvalid(); 12197 } 12198 } 12199 12200 if (R.isAmbiguous()) 12201 return BuildInvalid(); 12202 12203 if (HasTypenameKeyword) { 12204 // If we asked for a typename and got a non-type decl, error out. 12205 if (!R.getAsSingle<TypeDecl>()) { 12206 Diag(IdentLoc, diag::err_using_typename_non_type); 12207 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12208 Diag((*I)->getUnderlyingDecl()->getLocation(), 12209 diag::note_using_decl_target); 12210 return BuildInvalid(); 12211 } 12212 } else { 12213 // If we asked for a non-typename and we got a type, error out, 12214 // but only if this is an instantiation of an unresolved using 12215 // decl. Otherwise just silently find the type name. 12216 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12217 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12218 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12219 return BuildInvalid(); 12220 } 12221 } 12222 12223 // C++14 [namespace.udecl]p6: 12224 // A using-declaration shall not name a namespace. 12225 if (R.getAsSingle<NamespaceDecl>()) { 12226 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12227 << SS.getRange(); 12228 return BuildInvalid(); 12229 } 12230 12231 // C++14 [namespace.udecl]p7: 12232 // A using-declaration shall not name a scoped enumerator. 12233 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12234 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12235 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12236 << SS.getRange(); 12237 return BuildInvalid(); 12238 } 12239 } 12240 12241 UsingDecl *UD = BuildValid(); 12242 12243 // Some additional rules apply to inheriting constructors. 12244 if (UsingName.getName().getNameKind() == 12245 DeclarationName::CXXConstructorName) { 12246 // Suppress access diagnostics; the access check is instead performed at the 12247 // point of use for an inheriting constructor. 12248 R.suppressDiagnostics(); 12249 if (CheckInheritingConstructorUsingDecl(UD)) 12250 return UD; 12251 } 12252 12253 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12254 UsingShadowDecl *PrevDecl = nullptr; 12255 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12256 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12257 } 12258 12259 return UD; 12260 } 12261 12262 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12263 ArrayRef<NamedDecl *> Expansions) { 12264 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12265 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12266 isa<UsingPackDecl>(InstantiatedFrom)); 12267 12268 auto *UPD = 12269 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12270 UPD->setAccess(InstantiatedFrom->getAccess()); 12271 CurContext->addDecl(UPD); 12272 return UPD; 12273 } 12274 12275 /// Additional checks for a using declaration referring to a constructor name. 12276 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12277 assert(!UD->hasTypename() && "expecting a constructor name"); 12278 12279 const Type *SourceType = UD->getQualifier()->getAsType(); 12280 assert(SourceType && 12281 "Using decl naming constructor doesn't have type in scope spec."); 12282 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12283 12284 // Check whether the named type is a direct base class. 12285 bool AnyDependentBases = false; 12286 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12287 AnyDependentBases); 12288 if (!Base && !AnyDependentBases) { 12289 Diag(UD->getUsingLoc(), 12290 diag::err_using_decl_constructor_not_in_direct_base) 12291 << UD->getNameInfo().getSourceRange() 12292 << QualType(SourceType, 0) << TargetClass; 12293 UD->setInvalidDecl(); 12294 return true; 12295 } 12296 12297 if (Base) 12298 Base->setInheritConstructors(); 12299 12300 return false; 12301 } 12302 12303 /// Checks that the given using declaration is not an invalid 12304 /// redeclaration. Note that this is checking only for the using decl 12305 /// itself, not for any ill-formedness among the UsingShadowDecls. 12306 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12307 bool HasTypenameKeyword, 12308 const CXXScopeSpec &SS, 12309 SourceLocation NameLoc, 12310 const LookupResult &Prev) { 12311 NestedNameSpecifier *Qual = SS.getScopeRep(); 12312 12313 // C++03 [namespace.udecl]p8: 12314 // C++0x [namespace.udecl]p10: 12315 // A using-declaration is a declaration and can therefore be used 12316 // repeatedly where (and only where) multiple declarations are 12317 // allowed. 12318 // 12319 // That's in non-member contexts. 12320 if (!CurContext->getRedeclContext()->isRecord()) { 12321 // A dependent qualifier outside a class can only ever resolve to an 12322 // enumeration type. Therefore it conflicts with any other non-type 12323 // declaration in the same scope. 12324 // FIXME: How should we check for dependent type-type conflicts at block 12325 // scope? 12326 if (Qual->isDependent() && !HasTypenameKeyword) { 12327 for (auto *D : Prev) { 12328 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12329 bool OldCouldBeEnumerator = 12330 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12331 Diag(NameLoc, 12332 OldCouldBeEnumerator ? diag::err_redefinition 12333 : diag::err_redefinition_different_kind) 12334 << Prev.getLookupName(); 12335 Diag(D->getLocation(), diag::note_previous_definition); 12336 return true; 12337 } 12338 } 12339 } 12340 return false; 12341 } 12342 12343 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12344 NamedDecl *D = *I; 12345 12346 bool DTypename; 12347 NestedNameSpecifier *DQual; 12348 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12349 DTypename = UD->hasTypename(); 12350 DQual = UD->getQualifier(); 12351 } else if (UnresolvedUsingValueDecl *UD 12352 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12353 DTypename = false; 12354 DQual = UD->getQualifier(); 12355 } else if (UnresolvedUsingTypenameDecl *UD 12356 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12357 DTypename = true; 12358 DQual = UD->getQualifier(); 12359 } else continue; 12360 12361 // using decls differ if one says 'typename' and the other doesn't. 12362 // FIXME: non-dependent using decls? 12363 if (HasTypenameKeyword != DTypename) continue; 12364 12365 // using decls differ if they name different scopes (but note that 12366 // template instantiation can cause this check to trigger when it 12367 // didn't before instantiation). 12368 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12369 Context.getCanonicalNestedNameSpecifier(DQual)) 12370 continue; 12371 12372 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12373 Diag(D->getLocation(), diag::note_using_decl) << 1; 12374 return true; 12375 } 12376 12377 return false; 12378 } 12379 12380 12381 /// Checks that the given nested-name qualifier used in a using decl 12382 /// in the current context is appropriately related to the current 12383 /// scope. If an error is found, diagnoses it and returns true. 12384 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12385 bool HasTypename, 12386 const CXXScopeSpec &SS, 12387 const DeclarationNameInfo &NameInfo, 12388 SourceLocation NameLoc) { 12389 DeclContext *NamedContext = computeDeclContext(SS); 12390 12391 if (!CurContext->isRecord()) { 12392 // C++03 [namespace.udecl]p3: 12393 // C++0x [namespace.udecl]p8: 12394 // A using-declaration for a class member shall be a member-declaration. 12395 12396 // If we weren't able to compute a valid scope, it might validly be a 12397 // dependent class scope or a dependent enumeration unscoped scope. If 12398 // we have a 'typename' keyword, the scope must resolve to a class type. 12399 if ((HasTypename && !NamedContext) || 12400 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12401 auto *RD = NamedContext 12402 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12403 : nullptr; 12404 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12405 RD = nullptr; 12406 12407 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12408 << SS.getRange(); 12409 12410 // If we have a complete, non-dependent source type, try to suggest a 12411 // way to get the same effect. 12412 if (!RD) 12413 return true; 12414 12415 // Find what this using-declaration was referring to. 12416 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12417 R.setHideTags(false); 12418 R.suppressDiagnostics(); 12419 LookupQualifiedName(R, RD); 12420 12421 if (R.getAsSingle<TypeDecl>()) { 12422 if (getLangOpts().CPlusPlus11) { 12423 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12424 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12425 << 0 // alias declaration 12426 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12427 NameInfo.getName().getAsString() + 12428 " = "); 12429 } else { 12430 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12431 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12432 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12433 << 1 // typedef declaration 12434 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12435 << FixItHint::CreateInsertion( 12436 InsertLoc, " " + NameInfo.getName().getAsString()); 12437 } 12438 } else if (R.getAsSingle<VarDecl>()) { 12439 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12440 // repeating the type of the static data member here. 12441 FixItHint FixIt; 12442 if (getLangOpts().CPlusPlus11) { 12443 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12444 FixIt = FixItHint::CreateReplacement( 12445 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12446 } 12447 12448 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12449 << 2 // reference declaration 12450 << FixIt; 12451 } else if (R.getAsSingle<EnumConstantDecl>()) { 12452 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12453 // repeating the type of the enumeration here, and we can't do so if 12454 // the type is anonymous. 12455 FixItHint FixIt; 12456 if (getLangOpts().CPlusPlus11) { 12457 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12458 FixIt = FixItHint::CreateReplacement( 12459 UsingLoc, 12460 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12461 } 12462 12463 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12464 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12465 << FixIt; 12466 } 12467 return true; 12468 } 12469 12470 // Otherwise, this might be valid. 12471 return false; 12472 } 12473 12474 // The current scope is a record. 12475 12476 // If the named context is dependent, we can't decide much. 12477 if (!NamedContext) { 12478 // FIXME: in C++0x, we can diagnose if we can prove that the 12479 // nested-name-specifier does not refer to a base class, which is 12480 // still possible in some cases. 12481 12482 // Otherwise we have to conservatively report that things might be 12483 // okay. 12484 return false; 12485 } 12486 12487 if (!NamedContext->isRecord()) { 12488 // Ideally this would point at the last name in the specifier, 12489 // but we don't have that level of source info. 12490 Diag(SS.getRange().getBegin(), 12491 diag::err_using_decl_nested_name_specifier_is_not_class) 12492 << SS.getScopeRep() << SS.getRange(); 12493 return true; 12494 } 12495 12496 if (!NamedContext->isDependentContext() && 12497 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12498 return true; 12499 12500 if (getLangOpts().CPlusPlus11) { 12501 // C++11 [namespace.udecl]p3: 12502 // In a using-declaration used as a member-declaration, the 12503 // nested-name-specifier shall name a base class of the class 12504 // being defined. 12505 12506 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12507 cast<CXXRecordDecl>(NamedContext))) { 12508 if (CurContext == NamedContext) { 12509 Diag(NameLoc, 12510 diag::err_using_decl_nested_name_specifier_is_current_class) 12511 << SS.getRange(); 12512 return true; 12513 } 12514 12515 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12516 Diag(SS.getRange().getBegin(), 12517 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12518 << SS.getScopeRep() 12519 << cast<CXXRecordDecl>(CurContext) 12520 << SS.getRange(); 12521 } 12522 return true; 12523 } 12524 12525 return false; 12526 } 12527 12528 // C++03 [namespace.udecl]p4: 12529 // A using-declaration used as a member-declaration shall refer 12530 // to a member of a base class of the class being defined [etc.]. 12531 12532 // Salient point: SS doesn't have to name a base class as long as 12533 // lookup only finds members from base classes. Therefore we can 12534 // diagnose here only if we can prove that that can't happen, 12535 // i.e. if the class hierarchies provably don't intersect. 12536 12537 // TODO: it would be nice if "definitely valid" results were cached 12538 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12539 // need to be repeated. 12540 12541 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12542 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12543 Bases.insert(Base); 12544 return true; 12545 }; 12546 12547 // Collect all bases. Return false if we find a dependent base. 12548 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12549 return false; 12550 12551 // Returns true if the base is dependent or is one of the accumulated base 12552 // classes. 12553 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12554 return !Bases.count(Base); 12555 }; 12556 12557 // Return false if the class has a dependent base or if it or one 12558 // of its bases is present in the base set of the current context. 12559 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12560 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12561 return false; 12562 12563 Diag(SS.getRange().getBegin(), 12564 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12565 << SS.getScopeRep() 12566 << cast<CXXRecordDecl>(CurContext) 12567 << SS.getRange(); 12568 12569 return true; 12570 } 12571 12572 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12573 MultiTemplateParamsArg TemplateParamLists, 12574 SourceLocation UsingLoc, UnqualifiedId &Name, 12575 const ParsedAttributesView &AttrList, 12576 TypeResult Type, Decl *DeclFromDeclSpec) { 12577 // Skip up to the relevant declaration scope. 12578 while (S->isTemplateParamScope()) 12579 S = S->getParent(); 12580 assert((S->getFlags() & Scope::DeclScope) && 12581 "got alias-declaration outside of declaration scope"); 12582 12583 if (Type.isInvalid()) 12584 return nullptr; 12585 12586 bool Invalid = false; 12587 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12588 TypeSourceInfo *TInfo = nullptr; 12589 GetTypeFromParser(Type.get(), &TInfo); 12590 12591 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12592 return nullptr; 12593 12594 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12595 UPPC_DeclarationType)) { 12596 Invalid = true; 12597 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12598 TInfo->getTypeLoc().getBeginLoc()); 12599 } 12600 12601 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12602 TemplateParamLists.size() 12603 ? forRedeclarationInCurContext() 12604 : ForVisibleRedeclaration); 12605 LookupName(Previous, S); 12606 12607 // Warn about shadowing the name of a template parameter. 12608 if (Previous.isSingleResult() && 12609 Previous.getFoundDecl()->isTemplateParameter()) { 12610 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12611 Previous.clear(); 12612 } 12613 12614 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12615 "name in alias declaration must be an identifier"); 12616 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12617 Name.StartLocation, 12618 Name.Identifier, TInfo); 12619 12620 NewTD->setAccess(AS); 12621 12622 if (Invalid) 12623 NewTD->setInvalidDecl(); 12624 12625 ProcessDeclAttributeList(S, NewTD, AttrList); 12626 AddPragmaAttributes(S, NewTD); 12627 12628 CheckTypedefForVariablyModifiedType(S, NewTD); 12629 Invalid |= NewTD->isInvalidDecl(); 12630 12631 bool Redeclaration = false; 12632 12633 NamedDecl *NewND; 12634 if (TemplateParamLists.size()) { 12635 TypeAliasTemplateDecl *OldDecl = nullptr; 12636 TemplateParameterList *OldTemplateParams = nullptr; 12637 12638 if (TemplateParamLists.size() != 1) { 12639 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12640 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12641 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12642 } 12643 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12644 12645 // Check that we can declare a template here. 12646 if (CheckTemplateDeclScope(S, TemplateParams)) 12647 return nullptr; 12648 12649 // Only consider previous declarations in the same scope. 12650 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12651 /*ExplicitInstantiationOrSpecialization*/false); 12652 if (!Previous.empty()) { 12653 Redeclaration = true; 12654 12655 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12656 if (!OldDecl && !Invalid) { 12657 Diag(UsingLoc, diag::err_redefinition_different_kind) 12658 << Name.Identifier; 12659 12660 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12661 if (OldD->getLocation().isValid()) 12662 Diag(OldD->getLocation(), diag::note_previous_definition); 12663 12664 Invalid = true; 12665 } 12666 12667 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12668 if (TemplateParameterListsAreEqual(TemplateParams, 12669 OldDecl->getTemplateParameters(), 12670 /*Complain=*/true, 12671 TPL_TemplateMatch)) 12672 OldTemplateParams = 12673 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12674 else 12675 Invalid = true; 12676 12677 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12678 if (!Invalid && 12679 !Context.hasSameType(OldTD->getUnderlyingType(), 12680 NewTD->getUnderlyingType())) { 12681 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12682 // but we can't reasonably accept it. 12683 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12684 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12685 if (OldTD->getLocation().isValid()) 12686 Diag(OldTD->getLocation(), diag::note_previous_definition); 12687 Invalid = true; 12688 } 12689 } 12690 } 12691 12692 // Merge any previous default template arguments into our parameters, 12693 // and check the parameter list. 12694 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12695 TPC_TypeAliasTemplate)) 12696 return nullptr; 12697 12698 TypeAliasTemplateDecl *NewDecl = 12699 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12700 Name.Identifier, TemplateParams, 12701 NewTD); 12702 NewTD->setDescribedAliasTemplate(NewDecl); 12703 12704 NewDecl->setAccess(AS); 12705 12706 if (Invalid) 12707 NewDecl->setInvalidDecl(); 12708 else if (OldDecl) { 12709 NewDecl->setPreviousDecl(OldDecl); 12710 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12711 } 12712 12713 NewND = NewDecl; 12714 } else { 12715 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12716 setTagNameForLinkagePurposes(TD, NewTD); 12717 handleTagNumbering(TD, S); 12718 } 12719 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12720 NewND = NewTD; 12721 } 12722 12723 PushOnScopeChains(NewND, S); 12724 ActOnDocumentableDecl(NewND); 12725 return NewND; 12726 } 12727 12728 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12729 SourceLocation AliasLoc, 12730 IdentifierInfo *Alias, CXXScopeSpec &SS, 12731 SourceLocation IdentLoc, 12732 IdentifierInfo *Ident) { 12733 12734 // Lookup the namespace name. 12735 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12736 LookupParsedName(R, S, &SS); 12737 12738 if (R.isAmbiguous()) 12739 return nullptr; 12740 12741 if (R.empty()) { 12742 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12743 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12744 return nullptr; 12745 } 12746 } 12747 assert(!R.isAmbiguous() && !R.empty()); 12748 NamedDecl *ND = R.getRepresentativeDecl(); 12749 12750 // Check if we have a previous declaration with the same name. 12751 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12752 ForVisibleRedeclaration); 12753 LookupName(PrevR, S); 12754 12755 // Check we're not shadowing a template parameter. 12756 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12757 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12758 PrevR.clear(); 12759 } 12760 12761 // Filter out any other lookup result from an enclosing scope. 12762 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12763 /*AllowInlineNamespace*/false); 12764 12765 // Find the previous declaration and check that we can redeclare it. 12766 NamespaceAliasDecl *Prev = nullptr; 12767 if (PrevR.isSingleResult()) { 12768 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12769 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12770 // We already have an alias with the same name that points to the same 12771 // namespace; check that it matches. 12772 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12773 Prev = AD; 12774 } else if (isVisible(PrevDecl)) { 12775 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12776 << Alias; 12777 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12778 << AD->getNamespace(); 12779 return nullptr; 12780 } 12781 } else if (isVisible(PrevDecl)) { 12782 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12783 ? diag::err_redefinition 12784 : diag::err_redefinition_different_kind; 12785 Diag(AliasLoc, DiagID) << Alias; 12786 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12787 return nullptr; 12788 } 12789 } 12790 12791 // The use of a nested name specifier may trigger deprecation warnings. 12792 DiagnoseUseOfDecl(ND, IdentLoc); 12793 12794 NamespaceAliasDecl *AliasDecl = 12795 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12796 Alias, SS.getWithLocInContext(Context), 12797 IdentLoc, ND); 12798 if (Prev) 12799 AliasDecl->setPreviousDecl(Prev); 12800 12801 PushOnScopeChains(AliasDecl, S); 12802 return AliasDecl; 12803 } 12804 12805 namespace { 12806 struct SpecialMemberExceptionSpecInfo 12807 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12808 SourceLocation Loc; 12809 Sema::ImplicitExceptionSpecification ExceptSpec; 12810 12811 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12812 Sema::CXXSpecialMember CSM, 12813 Sema::InheritedConstructorInfo *ICI, 12814 SourceLocation Loc) 12815 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12816 12817 bool visitBase(CXXBaseSpecifier *Base); 12818 bool visitField(FieldDecl *FD); 12819 12820 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12821 unsigned Quals); 12822 12823 void visitSubobjectCall(Subobject Subobj, 12824 Sema::SpecialMemberOverloadResult SMOR); 12825 }; 12826 } 12827 12828 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12829 auto *RT = Base->getType()->getAs<RecordType>(); 12830 if (!RT) 12831 return false; 12832 12833 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12834 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12835 if (auto *BaseCtor = SMOR.getMethod()) { 12836 visitSubobjectCall(Base, BaseCtor); 12837 return false; 12838 } 12839 12840 visitClassSubobject(BaseClass, Base, 0); 12841 return false; 12842 } 12843 12844 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12845 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12846 Expr *E = FD->getInClassInitializer(); 12847 if (!E) 12848 // FIXME: It's a little wasteful to build and throw away a 12849 // CXXDefaultInitExpr here. 12850 // FIXME: We should have a single context note pointing at Loc, and 12851 // this location should be MD->getLocation() instead, since that's 12852 // the location where we actually use the default init expression. 12853 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12854 if (E) 12855 ExceptSpec.CalledExpr(E); 12856 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12857 ->getAs<RecordType>()) { 12858 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12859 FD->getType().getCVRQualifiers()); 12860 } 12861 return false; 12862 } 12863 12864 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12865 Subobject Subobj, 12866 unsigned Quals) { 12867 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12868 bool IsMutable = Field && Field->isMutable(); 12869 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12870 } 12871 12872 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12873 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12874 // Note, if lookup fails, it doesn't matter what exception specification we 12875 // choose because the special member will be deleted. 12876 if (CXXMethodDecl *MD = SMOR.getMethod()) 12877 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12878 } 12879 12880 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12881 llvm::APSInt Result; 12882 ExprResult Converted = CheckConvertedConstantExpression( 12883 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12884 ExplicitSpec.setExpr(Converted.get()); 12885 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12886 ExplicitSpec.setKind(Result.getBoolValue() 12887 ? ExplicitSpecKind::ResolvedTrue 12888 : ExplicitSpecKind::ResolvedFalse); 12889 return true; 12890 } 12891 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12892 return false; 12893 } 12894 12895 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12896 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12897 if (!ExplicitExpr->isTypeDependent()) 12898 tryResolveExplicitSpecifier(ES); 12899 return ES; 12900 } 12901 12902 static Sema::ImplicitExceptionSpecification 12903 ComputeDefaultedSpecialMemberExceptionSpec( 12904 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12905 Sema::InheritedConstructorInfo *ICI) { 12906 ComputingExceptionSpec CES(S, MD, Loc); 12907 12908 CXXRecordDecl *ClassDecl = MD->getParent(); 12909 12910 // C++ [except.spec]p14: 12911 // An implicitly declared special member function (Clause 12) shall have an 12912 // exception-specification. [...] 12913 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12914 if (ClassDecl->isInvalidDecl()) 12915 return Info.ExceptSpec; 12916 12917 // FIXME: If this diagnostic fires, we're probably missing a check for 12918 // attempting to resolve an exception specification before it's known 12919 // at a higher level. 12920 if (S.RequireCompleteType(MD->getLocation(), 12921 S.Context.getRecordType(ClassDecl), 12922 diag::err_exception_spec_incomplete_type)) 12923 return Info.ExceptSpec; 12924 12925 // C++1z [except.spec]p7: 12926 // [Look for exceptions thrown by] a constructor selected [...] to 12927 // initialize a potentially constructed subobject, 12928 // C++1z [except.spec]p8: 12929 // The exception specification for an implicitly-declared destructor, or a 12930 // destructor without a noexcept-specifier, is potentially-throwing if and 12931 // only if any of the destructors for any of its potentially constructed 12932 // subojects is potentially throwing. 12933 // FIXME: We respect the first rule but ignore the "potentially constructed" 12934 // in the second rule to resolve a core issue (no number yet) that would have 12935 // us reject: 12936 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12937 // struct B : A {}; 12938 // struct C : B { void f(); }; 12939 // ... due to giving B::~B() a non-throwing exception specification. 12940 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12941 : Info.VisitAllBases); 12942 12943 return Info.ExceptSpec; 12944 } 12945 12946 namespace { 12947 /// RAII object to register a special member as being currently declared. 12948 struct DeclaringSpecialMember { 12949 Sema &S; 12950 Sema::SpecialMemberDecl D; 12951 Sema::ContextRAII SavedContext; 12952 bool WasAlreadyBeingDeclared; 12953 12954 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12955 : S(S), D(RD, CSM), SavedContext(S, RD) { 12956 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12957 if (WasAlreadyBeingDeclared) 12958 // This almost never happens, but if it does, ensure that our cache 12959 // doesn't contain a stale result. 12960 S.SpecialMemberCache.clear(); 12961 else { 12962 // Register a note to be produced if we encounter an error while 12963 // declaring the special member. 12964 Sema::CodeSynthesisContext Ctx; 12965 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12966 // FIXME: We don't have a location to use here. Using the class's 12967 // location maintains the fiction that we declare all special members 12968 // with the class, but (1) it's not clear that lying about that helps our 12969 // users understand what's going on, and (2) there may be outer contexts 12970 // on the stack (some of which are relevant) and printing them exposes 12971 // our lies. 12972 Ctx.PointOfInstantiation = RD->getLocation(); 12973 Ctx.Entity = RD; 12974 Ctx.SpecialMember = CSM; 12975 S.pushCodeSynthesisContext(Ctx); 12976 } 12977 } 12978 ~DeclaringSpecialMember() { 12979 if (!WasAlreadyBeingDeclared) { 12980 S.SpecialMembersBeingDeclared.erase(D); 12981 S.popCodeSynthesisContext(); 12982 } 12983 } 12984 12985 /// Are we already trying to declare this special member? 12986 bool isAlreadyBeingDeclared() const { 12987 return WasAlreadyBeingDeclared; 12988 } 12989 }; 12990 } 12991 12992 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12993 // Look up any existing declarations, but don't trigger declaration of all 12994 // implicit special members with this name. 12995 DeclarationName Name = FD->getDeclName(); 12996 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12997 ForExternalRedeclaration); 12998 for (auto *D : FD->getParent()->lookup(Name)) 12999 if (auto *Acceptable = R.getAcceptableDecl(D)) 13000 R.addDecl(Acceptable); 13001 R.resolveKind(); 13002 R.suppressDiagnostics(); 13003 13004 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13005 } 13006 13007 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13008 QualType ResultTy, 13009 ArrayRef<QualType> Args) { 13010 // Build an exception specification pointing back at this constructor. 13011 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13012 13013 LangAS AS = getDefaultCXXMethodAddrSpace(); 13014 if (AS != LangAS::Default) { 13015 EPI.TypeQuals.addAddressSpace(AS); 13016 } 13017 13018 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13019 SpecialMem->setType(QT); 13020 } 13021 13022 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13023 CXXRecordDecl *ClassDecl) { 13024 // C++ [class.ctor]p5: 13025 // A default constructor for a class X is a constructor of class X 13026 // that can be called without an argument. If there is no 13027 // user-declared constructor for class X, a default constructor is 13028 // implicitly declared. An implicitly-declared default constructor 13029 // is an inline public member of its class. 13030 assert(ClassDecl->needsImplicitDefaultConstructor() && 13031 "Should not build implicit default constructor!"); 13032 13033 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13034 if (DSM.isAlreadyBeingDeclared()) 13035 return nullptr; 13036 13037 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13038 CXXDefaultConstructor, 13039 false); 13040 13041 // Create the actual constructor declaration. 13042 CanQualType ClassType 13043 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13044 SourceLocation ClassLoc = ClassDecl->getLocation(); 13045 DeclarationName Name 13046 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13047 DeclarationNameInfo NameInfo(Name, ClassLoc); 13048 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13049 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13050 /*TInfo=*/nullptr, ExplicitSpecifier(), 13051 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13052 Constexpr ? ConstexprSpecKind::Constexpr 13053 : ConstexprSpecKind::Unspecified); 13054 DefaultCon->setAccess(AS_public); 13055 DefaultCon->setDefaulted(); 13056 13057 if (getLangOpts().CUDA) { 13058 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13059 DefaultCon, 13060 /* ConstRHS */ false, 13061 /* Diagnose */ false); 13062 } 13063 13064 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13065 13066 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13067 // constructors is easy to compute. 13068 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13069 13070 // Note that we have declared this constructor. 13071 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13072 13073 Scope *S = getScopeForContext(ClassDecl); 13074 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13075 13076 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13077 SetDeclDeleted(DefaultCon, ClassLoc); 13078 13079 if (S) 13080 PushOnScopeChains(DefaultCon, S, false); 13081 ClassDecl->addDecl(DefaultCon); 13082 13083 return DefaultCon; 13084 } 13085 13086 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13087 CXXConstructorDecl *Constructor) { 13088 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13089 !Constructor->doesThisDeclarationHaveABody() && 13090 !Constructor->isDeleted()) && 13091 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13092 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13093 return; 13094 13095 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13096 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13097 13098 SynthesizedFunctionScope Scope(*this, Constructor); 13099 13100 // The exception specification is needed because we are defining the 13101 // function. 13102 ResolveExceptionSpec(CurrentLocation, 13103 Constructor->getType()->castAs<FunctionProtoType>()); 13104 MarkVTableUsed(CurrentLocation, ClassDecl); 13105 13106 // Add a context note for diagnostics produced after this point. 13107 Scope.addContextNote(CurrentLocation); 13108 13109 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13110 Constructor->setInvalidDecl(); 13111 return; 13112 } 13113 13114 SourceLocation Loc = Constructor->getEndLoc().isValid() 13115 ? Constructor->getEndLoc() 13116 : Constructor->getLocation(); 13117 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13118 Constructor->markUsed(Context); 13119 13120 if (ASTMutationListener *L = getASTMutationListener()) { 13121 L->CompletedImplicitDefinition(Constructor); 13122 } 13123 13124 DiagnoseUninitializedFields(*this, Constructor); 13125 } 13126 13127 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13128 // Perform any delayed checks on exception specifications. 13129 CheckDelayedMemberExceptionSpecs(); 13130 } 13131 13132 /// Find or create the fake constructor we synthesize to model constructing an 13133 /// object of a derived class via a constructor of a base class. 13134 CXXConstructorDecl * 13135 Sema::findInheritingConstructor(SourceLocation Loc, 13136 CXXConstructorDecl *BaseCtor, 13137 ConstructorUsingShadowDecl *Shadow) { 13138 CXXRecordDecl *Derived = Shadow->getParent(); 13139 SourceLocation UsingLoc = Shadow->getLocation(); 13140 13141 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13142 // For now we use the name of the base class constructor as a member of the 13143 // derived class to indicate a (fake) inherited constructor name. 13144 DeclarationName Name = BaseCtor->getDeclName(); 13145 13146 // Check to see if we already have a fake constructor for this inherited 13147 // constructor call. 13148 for (NamedDecl *Ctor : Derived->lookup(Name)) 13149 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13150 ->getInheritedConstructor() 13151 .getConstructor(), 13152 BaseCtor)) 13153 return cast<CXXConstructorDecl>(Ctor); 13154 13155 DeclarationNameInfo NameInfo(Name, UsingLoc); 13156 TypeSourceInfo *TInfo = 13157 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13158 FunctionProtoTypeLoc ProtoLoc = 13159 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13160 13161 // Check the inherited constructor is valid and find the list of base classes 13162 // from which it was inherited. 13163 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13164 13165 bool Constexpr = 13166 BaseCtor->isConstexpr() && 13167 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13168 false, BaseCtor, &ICI); 13169 13170 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13171 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13172 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13173 /*isImplicitlyDeclared=*/true, 13174 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13175 InheritedConstructor(Shadow, BaseCtor), 13176 BaseCtor->getTrailingRequiresClause()); 13177 if (Shadow->isInvalidDecl()) 13178 DerivedCtor->setInvalidDecl(); 13179 13180 // Build an unevaluated exception specification for this fake constructor. 13181 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13182 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13183 EPI.ExceptionSpec.Type = EST_Unevaluated; 13184 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13185 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13186 FPT->getParamTypes(), EPI)); 13187 13188 // Build the parameter declarations. 13189 SmallVector<ParmVarDecl *, 16> ParamDecls; 13190 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13191 TypeSourceInfo *TInfo = 13192 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13193 ParmVarDecl *PD = ParmVarDecl::Create( 13194 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13195 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13196 PD->setScopeInfo(0, I); 13197 PD->setImplicit(); 13198 // Ensure attributes are propagated onto parameters (this matters for 13199 // format, pass_object_size, ...). 13200 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13201 ParamDecls.push_back(PD); 13202 ProtoLoc.setParam(I, PD); 13203 } 13204 13205 // Set up the new constructor. 13206 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13207 DerivedCtor->setAccess(BaseCtor->getAccess()); 13208 DerivedCtor->setParams(ParamDecls); 13209 Derived->addDecl(DerivedCtor); 13210 13211 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13212 SetDeclDeleted(DerivedCtor, UsingLoc); 13213 13214 return DerivedCtor; 13215 } 13216 13217 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13218 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13219 Ctor->getInheritedConstructor().getShadowDecl()); 13220 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13221 /*Diagnose*/true); 13222 } 13223 13224 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13225 CXXConstructorDecl *Constructor) { 13226 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13227 assert(Constructor->getInheritedConstructor() && 13228 !Constructor->doesThisDeclarationHaveABody() && 13229 !Constructor->isDeleted()); 13230 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13231 return; 13232 13233 // Initializations are performed "as if by a defaulted default constructor", 13234 // so enter the appropriate scope. 13235 SynthesizedFunctionScope Scope(*this, Constructor); 13236 13237 // The exception specification is needed because we are defining the 13238 // function. 13239 ResolveExceptionSpec(CurrentLocation, 13240 Constructor->getType()->castAs<FunctionProtoType>()); 13241 MarkVTableUsed(CurrentLocation, ClassDecl); 13242 13243 // Add a context note for diagnostics produced after this point. 13244 Scope.addContextNote(CurrentLocation); 13245 13246 ConstructorUsingShadowDecl *Shadow = 13247 Constructor->getInheritedConstructor().getShadowDecl(); 13248 CXXConstructorDecl *InheritedCtor = 13249 Constructor->getInheritedConstructor().getConstructor(); 13250 13251 // [class.inhctor.init]p1: 13252 // initialization proceeds as if a defaulted default constructor is used to 13253 // initialize the D object and each base class subobject from which the 13254 // constructor was inherited 13255 13256 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13257 CXXRecordDecl *RD = Shadow->getParent(); 13258 SourceLocation InitLoc = Shadow->getLocation(); 13259 13260 // Build explicit initializers for all base classes from which the 13261 // constructor was inherited. 13262 SmallVector<CXXCtorInitializer*, 8> Inits; 13263 for (bool VBase : {false, true}) { 13264 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13265 if (B.isVirtual() != VBase) 13266 continue; 13267 13268 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13269 if (!BaseRD) 13270 continue; 13271 13272 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13273 if (!BaseCtor.first) 13274 continue; 13275 13276 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13277 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13278 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13279 13280 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13281 Inits.push_back(new (Context) CXXCtorInitializer( 13282 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13283 SourceLocation())); 13284 } 13285 } 13286 13287 // We now proceed as if for a defaulted default constructor, with the relevant 13288 // initializers replaced. 13289 13290 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13291 Constructor->setInvalidDecl(); 13292 return; 13293 } 13294 13295 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13296 Constructor->markUsed(Context); 13297 13298 if (ASTMutationListener *L = getASTMutationListener()) { 13299 L->CompletedImplicitDefinition(Constructor); 13300 } 13301 13302 DiagnoseUninitializedFields(*this, Constructor); 13303 } 13304 13305 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13306 // C++ [class.dtor]p2: 13307 // If a class has no user-declared destructor, a destructor is 13308 // declared implicitly. An implicitly-declared destructor is an 13309 // inline public member of its class. 13310 assert(ClassDecl->needsImplicitDestructor()); 13311 13312 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13313 if (DSM.isAlreadyBeingDeclared()) 13314 return nullptr; 13315 13316 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13317 CXXDestructor, 13318 false); 13319 13320 // Create the actual destructor declaration. 13321 CanQualType ClassType 13322 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13323 SourceLocation ClassLoc = ClassDecl->getLocation(); 13324 DeclarationName Name 13325 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13326 DeclarationNameInfo NameInfo(Name, ClassLoc); 13327 CXXDestructorDecl *Destructor = 13328 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13329 QualType(), nullptr, /*isInline=*/true, 13330 /*isImplicitlyDeclared=*/true, 13331 Constexpr ? ConstexprSpecKind::Constexpr 13332 : ConstexprSpecKind::Unspecified); 13333 Destructor->setAccess(AS_public); 13334 Destructor->setDefaulted(); 13335 13336 if (getLangOpts().CUDA) { 13337 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13338 Destructor, 13339 /* ConstRHS */ false, 13340 /* Diagnose */ false); 13341 } 13342 13343 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13344 13345 // We don't need to use SpecialMemberIsTrivial here; triviality for 13346 // destructors is easy to compute. 13347 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13348 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13349 ClassDecl->hasTrivialDestructorForCall()); 13350 13351 // Note that we have declared this destructor. 13352 ++getASTContext().NumImplicitDestructorsDeclared; 13353 13354 Scope *S = getScopeForContext(ClassDecl); 13355 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13356 13357 // We can't check whether an implicit destructor is deleted before we complete 13358 // the definition of the class, because its validity depends on the alignment 13359 // of the class. We'll check this from ActOnFields once the class is complete. 13360 if (ClassDecl->isCompleteDefinition() && 13361 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13362 SetDeclDeleted(Destructor, ClassLoc); 13363 13364 // Introduce this destructor into its scope. 13365 if (S) 13366 PushOnScopeChains(Destructor, S, false); 13367 ClassDecl->addDecl(Destructor); 13368 13369 return Destructor; 13370 } 13371 13372 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13373 CXXDestructorDecl *Destructor) { 13374 assert((Destructor->isDefaulted() && 13375 !Destructor->doesThisDeclarationHaveABody() && 13376 !Destructor->isDeleted()) && 13377 "DefineImplicitDestructor - call it for implicit default dtor"); 13378 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13379 return; 13380 13381 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13382 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13383 13384 SynthesizedFunctionScope Scope(*this, Destructor); 13385 13386 // The exception specification is needed because we are defining the 13387 // function. 13388 ResolveExceptionSpec(CurrentLocation, 13389 Destructor->getType()->castAs<FunctionProtoType>()); 13390 MarkVTableUsed(CurrentLocation, ClassDecl); 13391 13392 // Add a context note for diagnostics produced after this point. 13393 Scope.addContextNote(CurrentLocation); 13394 13395 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13396 Destructor->getParent()); 13397 13398 if (CheckDestructor(Destructor)) { 13399 Destructor->setInvalidDecl(); 13400 return; 13401 } 13402 13403 SourceLocation Loc = Destructor->getEndLoc().isValid() 13404 ? Destructor->getEndLoc() 13405 : Destructor->getLocation(); 13406 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13407 Destructor->markUsed(Context); 13408 13409 if (ASTMutationListener *L = getASTMutationListener()) { 13410 L->CompletedImplicitDefinition(Destructor); 13411 } 13412 } 13413 13414 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13415 CXXDestructorDecl *Destructor) { 13416 if (Destructor->isInvalidDecl()) 13417 return; 13418 13419 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13420 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13421 "implicit complete dtors unneeded outside MS ABI"); 13422 assert(ClassDecl->getNumVBases() > 0 && 13423 "complete dtor only exists for classes with vbases"); 13424 13425 SynthesizedFunctionScope Scope(*this, Destructor); 13426 13427 // Add a context note for diagnostics produced after this point. 13428 Scope.addContextNote(CurrentLocation); 13429 13430 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13431 } 13432 13433 /// Perform any semantic analysis which needs to be delayed until all 13434 /// pending class member declarations have been parsed. 13435 void Sema::ActOnFinishCXXMemberDecls() { 13436 // If the context is an invalid C++ class, just suppress these checks. 13437 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13438 if (Record->isInvalidDecl()) { 13439 DelayedOverridingExceptionSpecChecks.clear(); 13440 DelayedEquivalentExceptionSpecChecks.clear(); 13441 return; 13442 } 13443 checkForMultipleExportedDefaultConstructors(*this, Record); 13444 } 13445 } 13446 13447 void Sema::ActOnFinishCXXNonNestedClass() { 13448 referenceDLLExportedClassMethods(); 13449 13450 if (!DelayedDllExportMemberFunctions.empty()) { 13451 SmallVector<CXXMethodDecl*, 4> WorkList; 13452 std::swap(DelayedDllExportMemberFunctions, WorkList); 13453 for (CXXMethodDecl *M : WorkList) { 13454 DefineDefaultedFunction(*this, M, M->getLocation()); 13455 13456 // Pass the method to the consumer to get emitted. This is not necessary 13457 // for explicit instantiation definitions, as they will get emitted 13458 // anyway. 13459 if (M->getParent()->getTemplateSpecializationKind() != 13460 TSK_ExplicitInstantiationDefinition) 13461 ActOnFinishInlineFunctionDef(M); 13462 } 13463 } 13464 } 13465 13466 void Sema::referenceDLLExportedClassMethods() { 13467 if (!DelayedDllExportClasses.empty()) { 13468 // Calling ReferenceDllExportedMembers might cause the current function to 13469 // be called again, so use a local copy of DelayedDllExportClasses. 13470 SmallVector<CXXRecordDecl *, 4> WorkList; 13471 std::swap(DelayedDllExportClasses, WorkList); 13472 for (CXXRecordDecl *Class : WorkList) 13473 ReferenceDllExportedMembers(*this, Class); 13474 } 13475 } 13476 13477 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13478 assert(getLangOpts().CPlusPlus11 && 13479 "adjusting dtor exception specs was introduced in c++11"); 13480 13481 if (Destructor->isDependentContext()) 13482 return; 13483 13484 // C++11 [class.dtor]p3: 13485 // A declaration of a destructor that does not have an exception- 13486 // specification is implicitly considered to have the same exception- 13487 // specification as an implicit declaration. 13488 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13489 if (DtorType->hasExceptionSpec()) 13490 return; 13491 13492 // Replace the destructor's type, building off the existing one. Fortunately, 13493 // the only thing of interest in the destructor type is its extended info. 13494 // The return and arguments are fixed. 13495 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13496 EPI.ExceptionSpec.Type = EST_Unevaluated; 13497 EPI.ExceptionSpec.SourceDecl = Destructor; 13498 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13499 13500 // FIXME: If the destructor has a body that could throw, and the newly created 13501 // spec doesn't allow exceptions, we should emit a warning, because this 13502 // change in behavior can break conforming C++03 programs at runtime. 13503 // However, we don't have a body or an exception specification yet, so it 13504 // needs to be done somewhere else. 13505 } 13506 13507 namespace { 13508 /// An abstract base class for all helper classes used in building the 13509 // copy/move operators. These classes serve as factory functions and help us 13510 // avoid using the same Expr* in the AST twice. 13511 class ExprBuilder { 13512 ExprBuilder(const ExprBuilder&) = delete; 13513 ExprBuilder &operator=(const ExprBuilder&) = delete; 13514 13515 protected: 13516 static Expr *assertNotNull(Expr *E) { 13517 assert(E && "Expression construction must not fail."); 13518 return E; 13519 } 13520 13521 public: 13522 ExprBuilder() {} 13523 virtual ~ExprBuilder() {} 13524 13525 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13526 }; 13527 13528 class RefBuilder: public ExprBuilder { 13529 VarDecl *Var; 13530 QualType VarType; 13531 13532 public: 13533 Expr *build(Sema &S, SourceLocation Loc) const override { 13534 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13535 } 13536 13537 RefBuilder(VarDecl *Var, QualType VarType) 13538 : Var(Var), VarType(VarType) {} 13539 }; 13540 13541 class ThisBuilder: public ExprBuilder { 13542 public: 13543 Expr *build(Sema &S, SourceLocation Loc) const override { 13544 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13545 } 13546 }; 13547 13548 class CastBuilder: public ExprBuilder { 13549 const ExprBuilder &Builder; 13550 QualType Type; 13551 ExprValueKind Kind; 13552 const CXXCastPath &Path; 13553 13554 public: 13555 Expr *build(Sema &S, SourceLocation Loc) const override { 13556 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13557 CK_UncheckedDerivedToBase, Kind, 13558 &Path).get()); 13559 } 13560 13561 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13562 const CXXCastPath &Path) 13563 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13564 }; 13565 13566 class DerefBuilder: public ExprBuilder { 13567 const ExprBuilder &Builder; 13568 13569 public: 13570 Expr *build(Sema &S, SourceLocation Loc) const override { 13571 return assertNotNull( 13572 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13573 } 13574 13575 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13576 }; 13577 13578 class MemberBuilder: public ExprBuilder { 13579 const ExprBuilder &Builder; 13580 QualType Type; 13581 CXXScopeSpec SS; 13582 bool IsArrow; 13583 LookupResult &MemberLookup; 13584 13585 public: 13586 Expr *build(Sema &S, SourceLocation Loc) const override { 13587 return assertNotNull(S.BuildMemberReferenceExpr( 13588 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13589 nullptr, MemberLookup, nullptr, nullptr).get()); 13590 } 13591 13592 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13593 LookupResult &MemberLookup) 13594 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13595 MemberLookup(MemberLookup) {} 13596 }; 13597 13598 class MoveCastBuilder: public ExprBuilder { 13599 const ExprBuilder &Builder; 13600 13601 public: 13602 Expr *build(Sema &S, SourceLocation Loc) const override { 13603 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13604 } 13605 13606 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13607 }; 13608 13609 class LvalueConvBuilder: public ExprBuilder { 13610 const ExprBuilder &Builder; 13611 13612 public: 13613 Expr *build(Sema &S, SourceLocation Loc) const override { 13614 return assertNotNull( 13615 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13616 } 13617 13618 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13619 }; 13620 13621 class SubscriptBuilder: public ExprBuilder { 13622 const ExprBuilder &Base; 13623 const ExprBuilder &Index; 13624 13625 public: 13626 Expr *build(Sema &S, SourceLocation Loc) const override { 13627 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13628 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13629 } 13630 13631 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13632 : Base(Base), Index(Index) {} 13633 }; 13634 13635 } // end anonymous namespace 13636 13637 /// When generating a defaulted copy or move assignment operator, if a field 13638 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13639 /// do so. This optimization only applies for arrays of scalars, and for arrays 13640 /// of class type where the selected copy/move-assignment operator is trivial. 13641 static StmtResult 13642 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13643 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13644 // Compute the size of the memory buffer to be copied. 13645 QualType SizeType = S.Context.getSizeType(); 13646 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13647 S.Context.getTypeSizeInChars(T).getQuantity()); 13648 13649 // Take the address of the field references for "from" and "to". We 13650 // directly construct UnaryOperators here because semantic analysis 13651 // does not permit us to take the address of an xvalue. 13652 Expr *From = FromB.build(S, Loc); 13653 From = UnaryOperator::Create( 13654 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13655 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13656 Expr *To = ToB.build(S, Loc); 13657 To = UnaryOperator::Create( 13658 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13659 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13660 13661 const Type *E = T->getBaseElementTypeUnsafe(); 13662 bool NeedsCollectableMemCpy = 13663 E->isRecordType() && 13664 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13665 13666 // Create a reference to the __builtin_objc_memmove_collectable function 13667 StringRef MemCpyName = NeedsCollectableMemCpy ? 13668 "__builtin_objc_memmove_collectable" : 13669 "__builtin_memcpy"; 13670 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13671 Sema::LookupOrdinaryName); 13672 S.LookupName(R, S.TUScope, true); 13673 13674 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13675 if (!MemCpy) 13676 // Something went horribly wrong earlier, and we will have complained 13677 // about it. 13678 return StmtError(); 13679 13680 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13681 VK_RValue, Loc, nullptr); 13682 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13683 13684 Expr *CallArgs[] = { 13685 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13686 }; 13687 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13688 Loc, CallArgs, Loc); 13689 13690 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13691 return Call.getAs<Stmt>(); 13692 } 13693 13694 /// Builds a statement that copies/moves the given entity from \p From to 13695 /// \c To. 13696 /// 13697 /// This routine is used to copy/move the members of a class with an 13698 /// implicitly-declared copy/move assignment operator. When the entities being 13699 /// copied are arrays, this routine builds for loops to copy them. 13700 /// 13701 /// \param S The Sema object used for type-checking. 13702 /// 13703 /// \param Loc The location where the implicit copy/move is being generated. 13704 /// 13705 /// \param T The type of the expressions being copied/moved. Both expressions 13706 /// must have this type. 13707 /// 13708 /// \param To The expression we are copying/moving to. 13709 /// 13710 /// \param From The expression we are copying/moving from. 13711 /// 13712 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13713 /// Otherwise, it's a non-static member subobject. 13714 /// 13715 /// \param Copying Whether we're copying or moving. 13716 /// 13717 /// \param Depth Internal parameter recording the depth of the recursion. 13718 /// 13719 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13720 /// if a memcpy should be used instead. 13721 static StmtResult 13722 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13723 const ExprBuilder &To, const ExprBuilder &From, 13724 bool CopyingBaseSubobject, bool Copying, 13725 unsigned Depth = 0) { 13726 // C++11 [class.copy]p28: 13727 // Each subobject is assigned in the manner appropriate to its type: 13728 // 13729 // - if the subobject is of class type, as if by a call to operator= with 13730 // the subobject as the object expression and the corresponding 13731 // subobject of x as a single function argument (as if by explicit 13732 // qualification; that is, ignoring any possible virtual overriding 13733 // functions in more derived classes); 13734 // 13735 // C++03 [class.copy]p13: 13736 // - if the subobject is of class type, the copy assignment operator for 13737 // the class is used (as if by explicit qualification; that is, 13738 // ignoring any possible virtual overriding functions in more derived 13739 // classes); 13740 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13741 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13742 13743 // Look for operator=. 13744 DeclarationName Name 13745 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13746 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13747 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13748 13749 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13750 // operator. 13751 if (!S.getLangOpts().CPlusPlus11) { 13752 LookupResult::Filter F = OpLookup.makeFilter(); 13753 while (F.hasNext()) { 13754 NamedDecl *D = F.next(); 13755 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13756 if (Method->isCopyAssignmentOperator() || 13757 (!Copying && Method->isMoveAssignmentOperator())) 13758 continue; 13759 13760 F.erase(); 13761 } 13762 F.done(); 13763 } 13764 13765 // Suppress the protected check (C++ [class.protected]) for each of the 13766 // assignment operators we found. This strange dance is required when 13767 // we're assigning via a base classes's copy-assignment operator. To 13768 // ensure that we're getting the right base class subobject (without 13769 // ambiguities), we need to cast "this" to that subobject type; to 13770 // ensure that we don't go through the virtual call mechanism, we need 13771 // to qualify the operator= name with the base class (see below). However, 13772 // this means that if the base class has a protected copy assignment 13773 // operator, the protected member access check will fail. So, we 13774 // rewrite "protected" access to "public" access in this case, since we 13775 // know by construction that we're calling from a derived class. 13776 if (CopyingBaseSubobject) { 13777 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13778 L != LEnd; ++L) { 13779 if (L.getAccess() == AS_protected) 13780 L.setAccess(AS_public); 13781 } 13782 } 13783 13784 // Create the nested-name-specifier that will be used to qualify the 13785 // reference to operator=; this is required to suppress the virtual 13786 // call mechanism. 13787 CXXScopeSpec SS; 13788 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13789 SS.MakeTrivial(S.Context, 13790 NestedNameSpecifier::Create(S.Context, nullptr, false, 13791 CanonicalT), 13792 Loc); 13793 13794 // Create the reference to operator=. 13795 ExprResult OpEqualRef 13796 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13797 SS, /*TemplateKWLoc=*/SourceLocation(), 13798 /*FirstQualifierInScope=*/nullptr, 13799 OpLookup, 13800 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13801 /*SuppressQualifierCheck=*/true); 13802 if (OpEqualRef.isInvalid()) 13803 return StmtError(); 13804 13805 // Build the call to the assignment operator. 13806 13807 Expr *FromInst = From.build(S, Loc); 13808 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13809 OpEqualRef.getAs<Expr>(), 13810 Loc, FromInst, Loc); 13811 if (Call.isInvalid()) 13812 return StmtError(); 13813 13814 // If we built a call to a trivial 'operator=' while copying an array, 13815 // bail out. We'll replace the whole shebang with a memcpy. 13816 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13817 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13818 return StmtResult((Stmt*)nullptr); 13819 13820 // Convert to an expression-statement, and clean up any produced 13821 // temporaries. 13822 return S.ActOnExprStmt(Call); 13823 } 13824 13825 // - if the subobject is of scalar type, the built-in assignment 13826 // operator is used. 13827 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13828 if (!ArrayTy) { 13829 ExprResult Assignment = S.CreateBuiltinBinOp( 13830 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13831 if (Assignment.isInvalid()) 13832 return StmtError(); 13833 return S.ActOnExprStmt(Assignment); 13834 } 13835 13836 // - if the subobject is an array, each element is assigned, in the 13837 // manner appropriate to the element type; 13838 13839 // Construct a loop over the array bounds, e.g., 13840 // 13841 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13842 // 13843 // that will copy each of the array elements. 13844 QualType SizeType = S.Context.getSizeType(); 13845 13846 // Create the iteration variable. 13847 IdentifierInfo *IterationVarName = nullptr; 13848 { 13849 SmallString<8> Str; 13850 llvm::raw_svector_ostream OS(Str); 13851 OS << "__i" << Depth; 13852 IterationVarName = &S.Context.Idents.get(OS.str()); 13853 } 13854 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13855 IterationVarName, SizeType, 13856 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13857 SC_None); 13858 13859 // Initialize the iteration variable to zero. 13860 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13861 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13862 13863 // Creates a reference to the iteration variable. 13864 RefBuilder IterationVarRef(IterationVar, SizeType); 13865 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13866 13867 // Create the DeclStmt that holds the iteration variable. 13868 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13869 13870 // Subscript the "from" and "to" expressions with the iteration variable. 13871 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13872 MoveCastBuilder FromIndexMove(FromIndexCopy); 13873 const ExprBuilder *FromIndex; 13874 if (Copying) 13875 FromIndex = &FromIndexCopy; 13876 else 13877 FromIndex = &FromIndexMove; 13878 13879 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13880 13881 // Build the copy/move for an individual element of the array. 13882 StmtResult Copy = 13883 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13884 ToIndex, *FromIndex, CopyingBaseSubobject, 13885 Copying, Depth + 1); 13886 // Bail out if copying fails or if we determined that we should use memcpy. 13887 if (Copy.isInvalid() || !Copy.get()) 13888 return Copy; 13889 13890 // Create the comparison against the array bound. 13891 llvm::APInt Upper 13892 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13893 Expr *Comparison = BinaryOperator::Create( 13894 S.Context, IterationVarRefRVal.build(S, Loc), 13895 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13896 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13897 13898 // Create the pre-increment of the iteration variable. We can determine 13899 // whether the increment will overflow based on the value of the array 13900 // bound. 13901 Expr *Increment = UnaryOperator::Create( 13902 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13903 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13904 13905 // Construct the loop that copies all elements of this array. 13906 return S.ActOnForStmt( 13907 Loc, Loc, InitStmt, 13908 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13909 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13910 } 13911 13912 static StmtResult 13913 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13914 const ExprBuilder &To, const ExprBuilder &From, 13915 bool CopyingBaseSubobject, bool Copying) { 13916 // Maybe we should use a memcpy? 13917 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13918 T.isTriviallyCopyableType(S.Context)) 13919 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13920 13921 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13922 CopyingBaseSubobject, 13923 Copying, 0)); 13924 13925 // If we ended up picking a trivial assignment operator for an array of a 13926 // non-trivially-copyable class type, just emit a memcpy. 13927 if (!Result.isInvalid() && !Result.get()) 13928 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13929 13930 return Result; 13931 } 13932 13933 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13934 // Note: The following rules are largely analoguous to the copy 13935 // constructor rules. Note that virtual bases are not taken into account 13936 // for determining the argument type of the operator. Note also that 13937 // operators taking an object instead of a reference are allowed. 13938 assert(ClassDecl->needsImplicitCopyAssignment()); 13939 13940 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13941 if (DSM.isAlreadyBeingDeclared()) 13942 return nullptr; 13943 13944 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13945 LangAS AS = getDefaultCXXMethodAddrSpace(); 13946 if (AS != LangAS::Default) 13947 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13948 QualType RetType = Context.getLValueReferenceType(ArgType); 13949 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13950 if (Const) 13951 ArgType = ArgType.withConst(); 13952 13953 ArgType = Context.getLValueReferenceType(ArgType); 13954 13955 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13956 CXXCopyAssignment, 13957 Const); 13958 13959 // An implicitly-declared copy assignment operator is an inline public 13960 // member of its class. 13961 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13962 SourceLocation ClassLoc = ClassDecl->getLocation(); 13963 DeclarationNameInfo NameInfo(Name, ClassLoc); 13964 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13965 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13966 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13967 /*isInline=*/true, 13968 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 13969 SourceLocation()); 13970 CopyAssignment->setAccess(AS_public); 13971 CopyAssignment->setDefaulted(); 13972 CopyAssignment->setImplicit(); 13973 13974 if (getLangOpts().CUDA) { 13975 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13976 CopyAssignment, 13977 /* ConstRHS */ Const, 13978 /* Diagnose */ false); 13979 } 13980 13981 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13982 13983 // Add the parameter to the operator. 13984 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13985 ClassLoc, ClassLoc, 13986 /*Id=*/nullptr, ArgType, 13987 /*TInfo=*/nullptr, SC_None, 13988 nullptr); 13989 CopyAssignment->setParams(FromParam); 13990 13991 CopyAssignment->setTrivial( 13992 ClassDecl->needsOverloadResolutionForCopyAssignment() 13993 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13994 : ClassDecl->hasTrivialCopyAssignment()); 13995 13996 // Note that we have added this copy-assignment operator. 13997 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13998 13999 Scope *S = getScopeForContext(ClassDecl); 14000 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14001 14002 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14003 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14004 SetDeclDeleted(CopyAssignment, ClassLoc); 14005 } 14006 14007 if (S) 14008 PushOnScopeChains(CopyAssignment, S, false); 14009 ClassDecl->addDecl(CopyAssignment); 14010 14011 return CopyAssignment; 14012 } 14013 14014 /// Diagnose an implicit copy operation for a class which is odr-used, but 14015 /// which is deprecated because the class has a user-declared copy constructor, 14016 /// copy assignment operator, or destructor. 14017 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14018 assert(CopyOp->isImplicit()); 14019 14020 CXXRecordDecl *RD = CopyOp->getParent(); 14021 CXXMethodDecl *UserDeclaredOperation = nullptr; 14022 14023 // In Microsoft mode, assignment operations don't affect constructors and 14024 // vice versa. 14025 if (RD->hasUserDeclaredDestructor()) { 14026 UserDeclaredOperation = RD->getDestructor(); 14027 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14028 RD->hasUserDeclaredCopyConstructor() && 14029 !S.getLangOpts().MSVCCompat) { 14030 // Find any user-declared copy constructor. 14031 for (auto *I : RD->ctors()) { 14032 if (I->isCopyConstructor()) { 14033 UserDeclaredOperation = I; 14034 break; 14035 } 14036 } 14037 assert(UserDeclaredOperation); 14038 } else if (isa<CXXConstructorDecl>(CopyOp) && 14039 RD->hasUserDeclaredCopyAssignment() && 14040 !S.getLangOpts().MSVCCompat) { 14041 // Find any user-declared move assignment operator. 14042 for (auto *I : RD->methods()) { 14043 if (I->isCopyAssignmentOperator()) { 14044 UserDeclaredOperation = I; 14045 break; 14046 } 14047 } 14048 assert(UserDeclaredOperation); 14049 } 14050 14051 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 14052 S.Diag(UserDeclaredOperation->getLocation(), 14053 isa<CXXDestructorDecl>(UserDeclaredOperation) 14054 ? diag::warn_deprecated_copy_dtor_operation 14055 : diag::warn_deprecated_copy_operation) 14056 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 14057 } 14058 } 14059 14060 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14061 CXXMethodDecl *CopyAssignOperator) { 14062 assert((CopyAssignOperator->isDefaulted() && 14063 CopyAssignOperator->isOverloadedOperator() && 14064 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14065 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14066 !CopyAssignOperator->isDeleted()) && 14067 "DefineImplicitCopyAssignment called for wrong function"); 14068 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14069 return; 14070 14071 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14072 if (ClassDecl->isInvalidDecl()) { 14073 CopyAssignOperator->setInvalidDecl(); 14074 return; 14075 } 14076 14077 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14078 14079 // The exception specification is needed because we are defining the 14080 // function. 14081 ResolveExceptionSpec(CurrentLocation, 14082 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14083 14084 // Add a context note for diagnostics produced after this point. 14085 Scope.addContextNote(CurrentLocation); 14086 14087 // C++11 [class.copy]p18: 14088 // The [definition of an implicitly declared copy assignment operator] is 14089 // deprecated if the class has a user-declared copy constructor or a 14090 // user-declared destructor. 14091 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14092 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14093 14094 // C++0x [class.copy]p30: 14095 // The implicitly-defined or explicitly-defaulted copy assignment operator 14096 // for a non-union class X performs memberwise copy assignment of its 14097 // subobjects. The direct base classes of X are assigned first, in the 14098 // order of their declaration in the base-specifier-list, and then the 14099 // immediate non-static data members of X are assigned, in the order in 14100 // which they were declared in the class definition. 14101 14102 // The statements that form the synthesized function body. 14103 SmallVector<Stmt*, 8> Statements; 14104 14105 // The parameter for the "other" object, which we are copying from. 14106 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14107 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14108 QualType OtherRefType = Other->getType(); 14109 if (const LValueReferenceType *OtherRef 14110 = OtherRefType->getAs<LValueReferenceType>()) { 14111 OtherRefType = OtherRef->getPointeeType(); 14112 OtherQuals = OtherRefType.getQualifiers(); 14113 } 14114 14115 // Our location for everything implicitly-generated. 14116 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14117 ? CopyAssignOperator->getEndLoc() 14118 : CopyAssignOperator->getLocation(); 14119 14120 // Builds a DeclRefExpr for the "other" object. 14121 RefBuilder OtherRef(Other, OtherRefType); 14122 14123 // Builds the "this" pointer. 14124 ThisBuilder This; 14125 14126 // Assign base classes. 14127 bool Invalid = false; 14128 for (auto &Base : ClassDecl->bases()) { 14129 // Form the assignment: 14130 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14131 QualType BaseType = Base.getType().getUnqualifiedType(); 14132 if (!BaseType->isRecordType()) { 14133 Invalid = true; 14134 continue; 14135 } 14136 14137 CXXCastPath BasePath; 14138 BasePath.push_back(&Base); 14139 14140 // Construct the "from" expression, which is an implicit cast to the 14141 // appropriately-qualified base type. 14142 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14143 VK_LValue, BasePath); 14144 14145 // Dereference "this". 14146 DerefBuilder DerefThis(This); 14147 CastBuilder To(DerefThis, 14148 Context.getQualifiedType( 14149 BaseType, CopyAssignOperator->getMethodQualifiers()), 14150 VK_LValue, BasePath); 14151 14152 // Build the copy. 14153 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14154 To, From, 14155 /*CopyingBaseSubobject=*/true, 14156 /*Copying=*/true); 14157 if (Copy.isInvalid()) { 14158 CopyAssignOperator->setInvalidDecl(); 14159 return; 14160 } 14161 14162 // Success! Record the copy. 14163 Statements.push_back(Copy.getAs<Expr>()); 14164 } 14165 14166 // Assign non-static members. 14167 for (auto *Field : ClassDecl->fields()) { 14168 // FIXME: We should form some kind of AST representation for the implied 14169 // memcpy in a union copy operation. 14170 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14171 continue; 14172 14173 if (Field->isInvalidDecl()) { 14174 Invalid = true; 14175 continue; 14176 } 14177 14178 // Check for members of reference type; we can't copy those. 14179 if (Field->getType()->isReferenceType()) { 14180 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14181 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14182 Diag(Field->getLocation(), diag::note_declared_at); 14183 Invalid = true; 14184 continue; 14185 } 14186 14187 // Check for members of const-qualified, non-class type. 14188 QualType BaseType = Context.getBaseElementType(Field->getType()); 14189 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14190 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14191 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14192 Diag(Field->getLocation(), diag::note_declared_at); 14193 Invalid = true; 14194 continue; 14195 } 14196 14197 // Suppress assigning zero-width bitfields. 14198 if (Field->isZeroLengthBitField(Context)) 14199 continue; 14200 14201 QualType FieldType = Field->getType().getNonReferenceType(); 14202 if (FieldType->isIncompleteArrayType()) { 14203 assert(ClassDecl->hasFlexibleArrayMember() && 14204 "Incomplete array type is not valid"); 14205 continue; 14206 } 14207 14208 // Build references to the field in the object we're copying from and to. 14209 CXXScopeSpec SS; // Intentionally empty 14210 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14211 LookupMemberName); 14212 MemberLookup.addDecl(Field); 14213 MemberLookup.resolveKind(); 14214 14215 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14216 14217 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14218 14219 // Build the copy of this field. 14220 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14221 To, From, 14222 /*CopyingBaseSubobject=*/false, 14223 /*Copying=*/true); 14224 if (Copy.isInvalid()) { 14225 CopyAssignOperator->setInvalidDecl(); 14226 return; 14227 } 14228 14229 // Success! Record the copy. 14230 Statements.push_back(Copy.getAs<Stmt>()); 14231 } 14232 14233 if (!Invalid) { 14234 // Add a "return *this;" 14235 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14236 14237 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14238 if (Return.isInvalid()) 14239 Invalid = true; 14240 else 14241 Statements.push_back(Return.getAs<Stmt>()); 14242 } 14243 14244 if (Invalid) { 14245 CopyAssignOperator->setInvalidDecl(); 14246 return; 14247 } 14248 14249 StmtResult Body; 14250 { 14251 CompoundScopeRAII CompoundScope(*this); 14252 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14253 /*isStmtExpr=*/false); 14254 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14255 } 14256 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14257 CopyAssignOperator->markUsed(Context); 14258 14259 if (ASTMutationListener *L = getASTMutationListener()) { 14260 L->CompletedImplicitDefinition(CopyAssignOperator); 14261 } 14262 } 14263 14264 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14265 assert(ClassDecl->needsImplicitMoveAssignment()); 14266 14267 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14268 if (DSM.isAlreadyBeingDeclared()) 14269 return nullptr; 14270 14271 // Note: The following rules are largely analoguous to the move 14272 // constructor rules. 14273 14274 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14275 LangAS AS = getDefaultCXXMethodAddrSpace(); 14276 if (AS != LangAS::Default) 14277 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14278 QualType RetType = Context.getLValueReferenceType(ArgType); 14279 ArgType = Context.getRValueReferenceType(ArgType); 14280 14281 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14282 CXXMoveAssignment, 14283 false); 14284 14285 // An implicitly-declared move assignment operator is an inline public 14286 // member of its class. 14287 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14288 SourceLocation ClassLoc = ClassDecl->getLocation(); 14289 DeclarationNameInfo NameInfo(Name, ClassLoc); 14290 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14291 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14292 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14293 /*isInline=*/true, 14294 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14295 SourceLocation()); 14296 MoveAssignment->setAccess(AS_public); 14297 MoveAssignment->setDefaulted(); 14298 MoveAssignment->setImplicit(); 14299 14300 if (getLangOpts().CUDA) { 14301 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14302 MoveAssignment, 14303 /* ConstRHS */ false, 14304 /* Diagnose */ false); 14305 } 14306 14307 // Build an exception specification pointing back at this member. 14308 FunctionProtoType::ExtProtoInfo EPI = 14309 getImplicitMethodEPI(*this, MoveAssignment); 14310 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14311 14312 // Add the parameter to the operator. 14313 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14314 ClassLoc, ClassLoc, 14315 /*Id=*/nullptr, ArgType, 14316 /*TInfo=*/nullptr, SC_None, 14317 nullptr); 14318 MoveAssignment->setParams(FromParam); 14319 14320 MoveAssignment->setTrivial( 14321 ClassDecl->needsOverloadResolutionForMoveAssignment() 14322 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14323 : ClassDecl->hasTrivialMoveAssignment()); 14324 14325 // Note that we have added this copy-assignment operator. 14326 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14327 14328 Scope *S = getScopeForContext(ClassDecl); 14329 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14330 14331 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14332 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14333 SetDeclDeleted(MoveAssignment, ClassLoc); 14334 } 14335 14336 if (S) 14337 PushOnScopeChains(MoveAssignment, S, false); 14338 ClassDecl->addDecl(MoveAssignment); 14339 14340 return MoveAssignment; 14341 } 14342 14343 /// Check if we're implicitly defining a move assignment operator for a class 14344 /// with virtual bases. Such a move assignment might move-assign the virtual 14345 /// base multiple times. 14346 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14347 SourceLocation CurrentLocation) { 14348 assert(!Class->isDependentContext() && "should not define dependent move"); 14349 14350 // Only a virtual base could get implicitly move-assigned multiple times. 14351 // Only a non-trivial move assignment can observe this. We only want to 14352 // diagnose if we implicitly define an assignment operator that assigns 14353 // two base classes, both of which move-assign the same virtual base. 14354 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14355 Class->getNumBases() < 2) 14356 return; 14357 14358 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14359 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14360 VBaseMap VBases; 14361 14362 for (auto &BI : Class->bases()) { 14363 Worklist.push_back(&BI); 14364 while (!Worklist.empty()) { 14365 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14366 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14367 14368 // If the base has no non-trivial move assignment operators, 14369 // we don't care about moves from it. 14370 if (!Base->hasNonTrivialMoveAssignment()) 14371 continue; 14372 14373 // If there's nothing virtual here, skip it. 14374 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14375 continue; 14376 14377 // If we're not actually going to call a move assignment for this base, 14378 // or the selected move assignment is trivial, skip it. 14379 Sema::SpecialMemberOverloadResult SMOR = 14380 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14381 /*ConstArg*/false, /*VolatileArg*/false, 14382 /*RValueThis*/true, /*ConstThis*/false, 14383 /*VolatileThis*/false); 14384 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14385 !SMOR.getMethod()->isMoveAssignmentOperator()) 14386 continue; 14387 14388 if (BaseSpec->isVirtual()) { 14389 // We're going to move-assign this virtual base, and its move 14390 // assignment operator is not trivial. If this can happen for 14391 // multiple distinct direct bases of Class, diagnose it. (If it 14392 // only happens in one base, we'll diagnose it when synthesizing 14393 // that base class's move assignment operator.) 14394 CXXBaseSpecifier *&Existing = 14395 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14396 .first->second; 14397 if (Existing && Existing != &BI) { 14398 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14399 << Class << Base; 14400 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14401 << (Base->getCanonicalDecl() == 14402 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14403 << Base << Existing->getType() << Existing->getSourceRange(); 14404 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14405 << (Base->getCanonicalDecl() == 14406 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14407 << Base << BI.getType() << BaseSpec->getSourceRange(); 14408 14409 // Only diagnose each vbase once. 14410 Existing = nullptr; 14411 } 14412 } else { 14413 // Only walk over bases that have defaulted move assignment operators. 14414 // We assume that any user-provided move assignment operator handles 14415 // the multiple-moves-of-vbase case itself somehow. 14416 if (!SMOR.getMethod()->isDefaulted()) 14417 continue; 14418 14419 // We're going to move the base classes of Base. Add them to the list. 14420 for (auto &BI : Base->bases()) 14421 Worklist.push_back(&BI); 14422 } 14423 } 14424 } 14425 } 14426 14427 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14428 CXXMethodDecl *MoveAssignOperator) { 14429 assert((MoveAssignOperator->isDefaulted() && 14430 MoveAssignOperator->isOverloadedOperator() && 14431 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14432 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14433 !MoveAssignOperator->isDeleted()) && 14434 "DefineImplicitMoveAssignment called for wrong function"); 14435 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14436 return; 14437 14438 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14439 if (ClassDecl->isInvalidDecl()) { 14440 MoveAssignOperator->setInvalidDecl(); 14441 return; 14442 } 14443 14444 // C++0x [class.copy]p28: 14445 // The implicitly-defined or move assignment operator for a non-union class 14446 // X performs memberwise move assignment of its subobjects. The direct base 14447 // classes of X are assigned first, in the order of their declaration in the 14448 // base-specifier-list, and then the immediate non-static data members of X 14449 // are assigned, in the order in which they were declared in the class 14450 // definition. 14451 14452 // Issue a warning if our implicit move assignment operator will move 14453 // from a virtual base more than once. 14454 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14455 14456 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14457 14458 // The exception specification is needed because we are defining the 14459 // function. 14460 ResolveExceptionSpec(CurrentLocation, 14461 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14462 14463 // Add a context note for diagnostics produced after this point. 14464 Scope.addContextNote(CurrentLocation); 14465 14466 // The statements that form the synthesized function body. 14467 SmallVector<Stmt*, 8> Statements; 14468 14469 // The parameter for the "other" object, which we are move from. 14470 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14471 QualType OtherRefType = 14472 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14473 14474 // Our location for everything implicitly-generated. 14475 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14476 ? MoveAssignOperator->getEndLoc() 14477 : MoveAssignOperator->getLocation(); 14478 14479 // Builds a reference to the "other" object. 14480 RefBuilder OtherRef(Other, OtherRefType); 14481 // Cast to rvalue. 14482 MoveCastBuilder MoveOther(OtherRef); 14483 14484 // Builds the "this" pointer. 14485 ThisBuilder This; 14486 14487 // Assign base classes. 14488 bool Invalid = false; 14489 for (auto &Base : ClassDecl->bases()) { 14490 // C++11 [class.copy]p28: 14491 // It is unspecified whether subobjects representing virtual base classes 14492 // are assigned more than once by the implicitly-defined copy assignment 14493 // operator. 14494 // FIXME: Do not assign to a vbase that will be assigned by some other base 14495 // class. For a move-assignment, this can result in the vbase being moved 14496 // multiple times. 14497 14498 // Form the assignment: 14499 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14500 QualType BaseType = Base.getType().getUnqualifiedType(); 14501 if (!BaseType->isRecordType()) { 14502 Invalid = true; 14503 continue; 14504 } 14505 14506 CXXCastPath BasePath; 14507 BasePath.push_back(&Base); 14508 14509 // Construct the "from" expression, which is an implicit cast to the 14510 // appropriately-qualified base type. 14511 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14512 14513 // Dereference "this". 14514 DerefBuilder DerefThis(This); 14515 14516 // Implicitly cast "this" to the appropriately-qualified base type. 14517 CastBuilder To(DerefThis, 14518 Context.getQualifiedType( 14519 BaseType, MoveAssignOperator->getMethodQualifiers()), 14520 VK_LValue, BasePath); 14521 14522 // Build the move. 14523 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14524 To, From, 14525 /*CopyingBaseSubobject=*/true, 14526 /*Copying=*/false); 14527 if (Move.isInvalid()) { 14528 MoveAssignOperator->setInvalidDecl(); 14529 return; 14530 } 14531 14532 // Success! Record the move. 14533 Statements.push_back(Move.getAs<Expr>()); 14534 } 14535 14536 // Assign non-static members. 14537 for (auto *Field : ClassDecl->fields()) { 14538 // FIXME: We should form some kind of AST representation for the implied 14539 // memcpy in a union copy operation. 14540 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14541 continue; 14542 14543 if (Field->isInvalidDecl()) { 14544 Invalid = true; 14545 continue; 14546 } 14547 14548 // Check for members of reference type; we can't move those. 14549 if (Field->getType()->isReferenceType()) { 14550 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14551 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14552 Diag(Field->getLocation(), diag::note_declared_at); 14553 Invalid = true; 14554 continue; 14555 } 14556 14557 // Check for members of const-qualified, non-class type. 14558 QualType BaseType = Context.getBaseElementType(Field->getType()); 14559 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14560 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14561 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14562 Diag(Field->getLocation(), diag::note_declared_at); 14563 Invalid = true; 14564 continue; 14565 } 14566 14567 // Suppress assigning zero-width bitfields. 14568 if (Field->isZeroLengthBitField(Context)) 14569 continue; 14570 14571 QualType FieldType = Field->getType().getNonReferenceType(); 14572 if (FieldType->isIncompleteArrayType()) { 14573 assert(ClassDecl->hasFlexibleArrayMember() && 14574 "Incomplete array type is not valid"); 14575 continue; 14576 } 14577 14578 // Build references to the field in the object we're copying from and to. 14579 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14580 LookupMemberName); 14581 MemberLookup.addDecl(Field); 14582 MemberLookup.resolveKind(); 14583 MemberBuilder From(MoveOther, OtherRefType, 14584 /*IsArrow=*/false, MemberLookup); 14585 MemberBuilder To(This, getCurrentThisType(), 14586 /*IsArrow=*/true, MemberLookup); 14587 14588 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14589 "Member reference with rvalue base must be rvalue except for reference " 14590 "members, which aren't allowed for move assignment."); 14591 14592 // Build the move of this field. 14593 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14594 To, From, 14595 /*CopyingBaseSubobject=*/false, 14596 /*Copying=*/false); 14597 if (Move.isInvalid()) { 14598 MoveAssignOperator->setInvalidDecl(); 14599 return; 14600 } 14601 14602 // Success! Record the copy. 14603 Statements.push_back(Move.getAs<Stmt>()); 14604 } 14605 14606 if (!Invalid) { 14607 // Add a "return *this;" 14608 ExprResult ThisObj = 14609 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14610 14611 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14612 if (Return.isInvalid()) 14613 Invalid = true; 14614 else 14615 Statements.push_back(Return.getAs<Stmt>()); 14616 } 14617 14618 if (Invalid) { 14619 MoveAssignOperator->setInvalidDecl(); 14620 return; 14621 } 14622 14623 StmtResult Body; 14624 { 14625 CompoundScopeRAII CompoundScope(*this); 14626 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14627 /*isStmtExpr=*/false); 14628 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14629 } 14630 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14631 MoveAssignOperator->markUsed(Context); 14632 14633 if (ASTMutationListener *L = getASTMutationListener()) { 14634 L->CompletedImplicitDefinition(MoveAssignOperator); 14635 } 14636 } 14637 14638 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14639 CXXRecordDecl *ClassDecl) { 14640 // C++ [class.copy]p4: 14641 // If the class definition does not explicitly declare a copy 14642 // constructor, one is declared implicitly. 14643 assert(ClassDecl->needsImplicitCopyConstructor()); 14644 14645 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14646 if (DSM.isAlreadyBeingDeclared()) 14647 return nullptr; 14648 14649 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14650 QualType ArgType = ClassType; 14651 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14652 if (Const) 14653 ArgType = ArgType.withConst(); 14654 14655 LangAS AS = getDefaultCXXMethodAddrSpace(); 14656 if (AS != LangAS::Default) 14657 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14658 14659 ArgType = Context.getLValueReferenceType(ArgType); 14660 14661 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14662 CXXCopyConstructor, 14663 Const); 14664 14665 DeclarationName Name 14666 = Context.DeclarationNames.getCXXConstructorName( 14667 Context.getCanonicalType(ClassType)); 14668 SourceLocation ClassLoc = ClassDecl->getLocation(); 14669 DeclarationNameInfo NameInfo(Name, ClassLoc); 14670 14671 // An implicitly-declared copy constructor is an inline public 14672 // member of its class. 14673 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14674 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14675 ExplicitSpecifier(), 14676 /*isInline=*/true, 14677 /*isImplicitlyDeclared=*/true, 14678 Constexpr ? ConstexprSpecKind::Constexpr 14679 : ConstexprSpecKind::Unspecified); 14680 CopyConstructor->setAccess(AS_public); 14681 CopyConstructor->setDefaulted(); 14682 14683 if (getLangOpts().CUDA) { 14684 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14685 CopyConstructor, 14686 /* ConstRHS */ Const, 14687 /* Diagnose */ false); 14688 } 14689 14690 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14691 14692 // Add the parameter to the constructor. 14693 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14694 ClassLoc, ClassLoc, 14695 /*IdentifierInfo=*/nullptr, 14696 ArgType, /*TInfo=*/nullptr, 14697 SC_None, nullptr); 14698 CopyConstructor->setParams(FromParam); 14699 14700 CopyConstructor->setTrivial( 14701 ClassDecl->needsOverloadResolutionForCopyConstructor() 14702 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14703 : ClassDecl->hasTrivialCopyConstructor()); 14704 14705 CopyConstructor->setTrivialForCall( 14706 ClassDecl->hasAttr<TrivialABIAttr>() || 14707 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14708 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14709 TAH_ConsiderTrivialABI) 14710 : ClassDecl->hasTrivialCopyConstructorForCall())); 14711 14712 // Note that we have declared this constructor. 14713 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14714 14715 Scope *S = getScopeForContext(ClassDecl); 14716 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14717 14718 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14719 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14720 SetDeclDeleted(CopyConstructor, ClassLoc); 14721 } 14722 14723 if (S) 14724 PushOnScopeChains(CopyConstructor, S, false); 14725 ClassDecl->addDecl(CopyConstructor); 14726 14727 return CopyConstructor; 14728 } 14729 14730 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14731 CXXConstructorDecl *CopyConstructor) { 14732 assert((CopyConstructor->isDefaulted() && 14733 CopyConstructor->isCopyConstructor() && 14734 !CopyConstructor->doesThisDeclarationHaveABody() && 14735 !CopyConstructor->isDeleted()) && 14736 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14737 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14738 return; 14739 14740 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14741 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14742 14743 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14744 14745 // The exception specification is needed because we are defining the 14746 // function. 14747 ResolveExceptionSpec(CurrentLocation, 14748 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14749 MarkVTableUsed(CurrentLocation, ClassDecl); 14750 14751 // Add a context note for diagnostics produced after this point. 14752 Scope.addContextNote(CurrentLocation); 14753 14754 // C++11 [class.copy]p7: 14755 // The [definition of an implicitly declared copy constructor] is 14756 // deprecated if the class has a user-declared copy assignment operator 14757 // or a user-declared destructor. 14758 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14759 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14760 14761 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14762 CopyConstructor->setInvalidDecl(); 14763 } else { 14764 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14765 ? CopyConstructor->getEndLoc() 14766 : CopyConstructor->getLocation(); 14767 Sema::CompoundScopeRAII CompoundScope(*this); 14768 CopyConstructor->setBody( 14769 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14770 CopyConstructor->markUsed(Context); 14771 } 14772 14773 if (ASTMutationListener *L = getASTMutationListener()) { 14774 L->CompletedImplicitDefinition(CopyConstructor); 14775 } 14776 } 14777 14778 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14779 CXXRecordDecl *ClassDecl) { 14780 assert(ClassDecl->needsImplicitMoveConstructor()); 14781 14782 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14783 if (DSM.isAlreadyBeingDeclared()) 14784 return nullptr; 14785 14786 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14787 14788 QualType ArgType = ClassType; 14789 LangAS AS = getDefaultCXXMethodAddrSpace(); 14790 if (AS != LangAS::Default) 14791 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14792 ArgType = Context.getRValueReferenceType(ArgType); 14793 14794 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14795 CXXMoveConstructor, 14796 false); 14797 14798 DeclarationName Name 14799 = Context.DeclarationNames.getCXXConstructorName( 14800 Context.getCanonicalType(ClassType)); 14801 SourceLocation ClassLoc = ClassDecl->getLocation(); 14802 DeclarationNameInfo NameInfo(Name, ClassLoc); 14803 14804 // C++11 [class.copy]p11: 14805 // An implicitly-declared copy/move constructor is an inline public 14806 // member of its class. 14807 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14808 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14809 ExplicitSpecifier(), 14810 /*isInline=*/true, 14811 /*isImplicitlyDeclared=*/true, 14812 Constexpr ? ConstexprSpecKind::Constexpr 14813 : ConstexprSpecKind::Unspecified); 14814 MoveConstructor->setAccess(AS_public); 14815 MoveConstructor->setDefaulted(); 14816 14817 if (getLangOpts().CUDA) { 14818 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14819 MoveConstructor, 14820 /* ConstRHS */ false, 14821 /* Diagnose */ false); 14822 } 14823 14824 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14825 14826 // Add the parameter to the constructor. 14827 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14828 ClassLoc, ClassLoc, 14829 /*IdentifierInfo=*/nullptr, 14830 ArgType, /*TInfo=*/nullptr, 14831 SC_None, nullptr); 14832 MoveConstructor->setParams(FromParam); 14833 14834 MoveConstructor->setTrivial( 14835 ClassDecl->needsOverloadResolutionForMoveConstructor() 14836 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14837 : ClassDecl->hasTrivialMoveConstructor()); 14838 14839 MoveConstructor->setTrivialForCall( 14840 ClassDecl->hasAttr<TrivialABIAttr>() || 14841 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14842 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14843 TAH_ConsiderTrivialABI) 14844 : ClassDecl->hasTrivialMoveConstructorForCall())); 14845 14846 // Note that we have declared this constructor. 14847 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14848 14849 Scope *S = getScopeForContext(ClassDecl); 14850 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14851 14852 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14853 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14854 SetDeclDeleted(MoveConstructor, ClassLoc); 14855 } 14856 14857 if (S) 14858 PushOnScopeChains(MoveConstructor, S, false); 14859 ClassDecl->addDecl(MoveConstructor); 14860 14861 return MoveConstructor; 14862 } 14863 14864 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14865 CXXConstructorDecl *MoveConstructor) { 14866 assert((MoveConstructor->isDefaulted() && 14867 MoveConstructor->isMoveConstructor() && 14868 !MoveConstructor->doesThisDeclarationHaveABody() && 14869 !MoveConstructor->isDeleted()) && 14870 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14871 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14872 return; 14873 14874 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14875 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14876 14877 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14878 14879 // The exception specification is needed because we are defining the 14880 // function. 14881 ResolveExceptionSpec(CurrentLocation, 14882 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14883 MarkVTableUsed(CurrentLocation, ClassDecl); 14884 14885 // Add a context note for diagnostics produced after this point. 14886 Scope.addContextNote(CurrentLocation); 14887 14888 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14889 MoveConstructor->setInvalidDecl(); 14890 } else { 14891 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14892 ? MoveConstructor->getEndLoc() 14893 : MoveConstructor->getLocation(); 14894 Sema::CompoundScopeRAII CompoundScope(*this); 14895 MoveConstructor->setBody(ActOnCompoundStmt( 14896 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14897 MoveConstructor->markUsed(Context); 14898 } 14899 14900 if (ASTMutationListener *L = getASTMutationListener()) { 14901 L->CompletedImplicitDefinition(MoveConstructor); 14902 } 14903 } 14904 14905 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14906 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14907 } 14908 14909 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14910 SourceLocation CurrentLocation, 14911 CXXConversionDecl *Conv) { 14912 SynthesizedFunctionScope Scope(*this, Conv); 14913 assert(!Conv->getReturnType()->isUndeducedType()); 14914 14915 QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType(); 14916 CallingConv CC = 14917 ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv(); 14918 14919 CXXRecordDecl *Lambda = Conv->getParent(); 14920 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14921 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 14922 14923 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14924 CallOp = InstantiateFunctionDeclaration( 14925 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14926 if (!CallOp) 14927 return; 14928 14929 Invoker = InstantiateFunctionDeclaration( 14930 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14931 if (!Invoker) 14932 return; 14933 } 14934 14935 if (CallOp->isInvalidDecl()) 14936 return; 14937 14938 // Mark the call operator referenced (and add to pending instantiations 14939 // if necessary). 14940 // For both the conversion and static-invoker template specializations 14941 // we construct their body's in this function, so no need to add them 14942 // to the PendingInstantiations. 14943 MarkFunctionReferenced(CurrentLocation, CallOp); 14944 14945 // Fill in the __invoke function with a dummy implementation. IR generation 14946 // will fill in the actual details. Update its type in case it contained 14947 // an 'auto'. 14948 Invoker->markUsed(Context); 14949 Invoker->setReferenced(); 14950 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14951 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14952 14953 // Construct the body of the conversion function { return __invoke; }. 14954 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14955 VK_LValue, Conv->getLocation()); 14956 assert(FunctionRef && "Can't refer to __invoke function?"); 14957 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14958 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14959 Conv->getLocation())); 14960 Conv->markUsed(Context); 14961 Conv->setReferenced(); 14962 14963 if (ASTMutationListener *L = getASTMutationListener()) { 14964 L->CompletedImplicitDefinition(Conv); 14965 L->CompletedImplicitDefinition(Invoker); 14966 } 14967 } 14968 14969 14970 14971 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14972 SourceLocation CurrentLocation, 14973 CXXConversionDecl *Conv) 14974 { 14975 assert(!Conv->getParent()->isGenericLambda()); 14976 14977 SynthesizedFunctionScope Scope(*this, Conv); 14978 14979 // Copy-initialize the lambda object as needed to capture it. 14980 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14981 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14982 14983 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14984 Conv->getLocation(), 14985 Conv, DerefThis); 14986 14987 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14988 // behavior. Note that only the general conversion function does this 14989 // (since it's unusable otherwise); in the case where we inline the 14990 // block literal, it has block literal lifetime semantics. 14991 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14992 BuildBlock = ImplicitCastExpr::Create( 14993 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14994 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14995 14996 if (BuildBlock.isInvalid()) { 14997 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14998 Conv->setInvalidDecl(); 14999 return; 15000 } 15001 15002 // Create the return statement that returns the block from the conversion 15003 // function. 15004 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15005 if (Return.isInvalid()) { 15006 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15007 Conv->setInvalidDecl(); 15008 return; 15009 } 15010 15011 // Set the body of the conversion function. 15012 Stmt *ReturnS = Return.get(); 15013 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15014 Conv->getLocation())); 15015 Conv->markUsed(Context); 15016 15017 // We're done; notify the mutation listener, if any. 15018 if (ASTMutationListener *L = getASTMutationListener()) { 15019 L->CompletedImplicitDefinition(Conv); 15020 } 15021 } 15022 15023 /// Determine whether the given list arguments contains exactly one 15024 /// "real" (non-default) argument. 15025 static bool hasOneRealArgument(MultiExprArg Args) { 15026 switch (Args.size()) { 15027 case 0: 15028 return false; 15029 15030 default: 15031 if (!Args[1]->isDefaultArgument()) 15032 return false; 15033 15034 LLVM_FALLTHROUGH; 15035 case 1: 15036 return !Args[0]->isDefaultArgument(); 15037 } 15038 15039 return false; 15040 } 15041 15042 ExprResult 15043 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15044 NamedDecl *FoundDecl, 15045 CXXConstructorDecl *Constructor, 15046 MultiExprArg ExprArgs, 15047 bool HadMultipleCandidates, 15048 bool IsListInitialization, 15049 bool IsStdInitListInitialization, 15050 bool RequiresZeroInit, 15051 unsigned ConstructKind, 15052 SourceRange ParenRange) { 15053 bool Elidable = false; 15054 15055 // C++0x [class.copy]p34: 15056 // When certain criteria are met, an implementation is allowed to 15057 // omit the copy/move construction of a class object, even if the 15058 // copy/move constructor and/or destructor for the object have 15059 // side effects. [...] 15060 // - when a temporary class object that has not been bound to a 15061 // reference (12.2) would be copied/moved to a class object 15062 // with the same cv-unqualified type, the copy/move operation 15063 // can be omitted by constructing the temporary object 15064 // directly into the target of the omitted copy/move 15065 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15066 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15067 Expr *SubExpr = ExprArgs[0]; 15068 Elidable = SubExpr->isTemporaryObject( 15069 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15070 } 15071 15072 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15073 FoundDecl, Constructor, 15074 Elidable, ExprArgs, HadMultipleCandidates, 15075 IsListInitialization, 15076 IsStdInitListInitialization, RequiresZeroInit, 15077 ConstructKind, ParenRange); 15078 } 15079 15080 ExprResult 15081 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15082 NamedDecl *FoundDecl, 15083 CXXConstructorDecl *Constructor, 15084 bool Elidable, 15085 MultiExprArg ExprArgs, 15086 bool HadMultipleCandidates, 15087 bool IsListInitialization, 15088 bool IsStdInitListInitialization, 15089 bool RequiresZeroInit, 15090 unsigned ConstructKind, 15091 SourceRange ParenRange) { 15092 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15093 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15094 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15095 return ExprError(); 15096 } 15097 15098 return BuildCXXConstructExpr( 15099 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15100 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15101 RequiresZeroInit, ConstructKind, ParenRange); 15102 } 15103 15104 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15105 /// including handling of its default argument expressions. 15106 ExprResult 15107 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15108 CXXConstructorDecl *Constructor, 15109 bool Elidable, 15110 MultiExprArg ExprArgs, 15111 bool HadMultipleCandidates, 15112 bool IsListInitialization, 15113 bool IsStdInitListInitialization, 15114 bool RequiresZeroInit, 15115 unsigned ConstructKind, 15116 SourceRange ParenRange) { 15117 assert(declaresSameEntity( 15118 Constructor->getParent(), 15119 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15120 "given constructor for wrong type"); 15121 MarkFunctionReferenced(ConstructLoc, Constructor); 15122 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15123 return ExprError(); 15124 if (getLangOpts().SYCLIsDevice && 15125 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15126 return ExprError(); 15127 15128 return CheckForImmediateInvocation( 15129 CXXConstructExpr::Create( 15130 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15131 HadMultipleCandidates, IsListInitialization, 15132 IsStdInitListInitialization, RequiresZeroInit, 15133 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15134 ParenRange), 15135 Constructor); 15136 } 15137 15138 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15139 assert(Field->hasInClassInitializer()); 15140 15141 // If we already have the in-class initializer nothing needs to be done. 15142 if (Field->getInClassInitializer()) 15143 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15144 15145 // If we might have already tried and failed to instantiate, don't try again. 15146 if (Field->isInvalidDecl()) 15147 return ExprError(); 15148 15149 // Maybe we haven't instantiated the in-class initializer. Go check the 15150 // pattern FieldDecl to see if it has one. 15151 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15152 15153 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15154 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15155 DeclContext::lookup_result Lookup = 15156 ClassPattern->lookup(Field->getDeclName()); 15157 15158 FieldDecl *Pattern = nullptr; 15159 for (auto L : Lookup) { 15160 if (isa<FieldDecl>(L)) { 15161 Pattern = cast<FieldDecl>(L); 15162 break; 15163 } 15164 } 15165 assert(Pattern && "We must have set the Pattern!"); 15166 15167 if (!Pattern->hasInClassInitializer() || 15168 InstantiateInClassInitializer(Loc, Field, Pattern, 15169 getTemplateInstantiationArgs(Field))) { 15170 // Don't diagnose this again. 15171 Field->setInvalidDecl(); 15172 return ExprError(); 15173 } 15174 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15175 } 15176 15177 // DR1351: 15178 // If the brace-or-equal-initializer of a non-static data member 15179 // invokes a defaulted default constructor of its class or of an 15180 // enclosing class in a potentially evaluated subexpression, the 15181 // program is ill-formed. 15182 // 15183 // This resolution is unworkable: the exception specification of the 15184 // default constructor can be needed in an unevaluated context, in 15185 // particular, in the operand of a noexcept-expression, and we can be 15186 // unable to compute an exception specification for an enclosed class. 15187 // 15188 // Any attempt to resolve the exception specification of a defaulted default 15189 // constructor before the initializer is lexically complete will ultimately 15190 // come here at which point we can diagnose it. 15191 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15192 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15193 << OutermostClass << Field; 15194 Diag(Field->getEndLoc(), 15195 diag::note_default_member_initializer_not_yet_parsed); 15196 // Recover by marking the field invalid, unless we're in a SFINAE context. 15197 if (!isSFINAEContext()) 15198 Field->setInvalidDecl(); 15199 return ExprError(); 15200 } 15201 15202 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15203 if (VD->isInvalidDecl()) return; 15204 // If initializing the variable failed, don't also diagnose problems with 15205 // the desctructor, they're likely related. 15206 if (VD->getInit() && VD->getInit()->containsErrors()) 15207 return; 15208 15209 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15210 if (ClassDecl->isInvalidDecl()) return; 15211 if (ClassDecl->hasIrrelevantDestructor()) return; 15212 if (ClassDecl->isDependentContext()) return; 15213 15214 if (VD->isNoDestroy(getASTContext())) 15215 return; 15216 15217 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15218 15219 // If this is an array, we'll require the destructor during initialization, so 15220 // we can skip over this. We still want to emit exit-time destructor warnings 15221 // though. 15222 if (!VD->getType()->isArrayType()) { 15223 MarkFunctionReferenced(VD->getLocation(), Destructor); 15224 CheckDestructorAccess(VD->getLocation(), Destructor, 15225 PDiag(diag::err_access_dtor_var) 15226 << VD->getDeclName() << VD->getType()); 15227 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15228 } 15229 15230 if (Destructor->isTrivial()) return; 15231 15232 // If the destructor is constexpr, check whether the variable has constant 15233 // destruction now. 15234 if (Destructor->isConstexpr()) { 15235 bool HasConstantInit = false; 15236 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15237 HasConstantInit = VD->evaluateValue(); 15238 SmallVector<PartialDiagnosticAt, 8> Notes; 15239 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15240 HasConstantInit) { 15241 Diag(VD->getLocation(), 15242 diag::err_constexpr_var_requires_const_destruction) << VD; 15243 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15244 Diag(Notes[I].first, Notes[I].second); 15245 } 15246 } 15247 15248 if (!VD->hasGlobalStorage()) return; 15249 15250 // Emit warning for non-trivial dtor in global scope (a real global, 15251 // class-static, function-static). 15252 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15253 15254 // TODO: this should be re-enabled for static locals by !CXAAtExit 15255 if (!VD->isStaticLocal()) 15256 Diag(VD->getLocation(), diag::warn_global_destructor); 15257 } 15258 15259 /// Given a constructor and the set of arguments provided for the 15260 /// constructor, convert the arguments and add any required default arguments 15261 /// to form a proper call to this constructor. 15262 /// 15263 /// \returns true if an error occurred, false otherwise. 15264 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15265 QualType DeclInitType, MultiExprArg ArgsPtr, 15266 SourceLocation Loc, 15267 SmallVectorImpl<Expr *> &ConvertedArgs, 15268 bool AllowExplicit, 15269 bool IsListInitialization) { 15270 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15271 unsigned NumArgs = ArgsPtr.size(); 15272 Expr **Args = ArgsPtr.data(); 15273 15274 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15275 unsigned NumParams = Proto->getNumParams(); 15276 15277 // If too few arguments are available, we'll fill in the rest with defaults. 15278 if (NumArgs < NumParams) 15279 ConvertedArgs.reserve(NumParams); 15280 else 15281 ConvertedArgs.reserve(NumArgs); 15282 15283 VariadicCallType CallType = 15284 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15285 SmallVector<Expr *, 8> AllArgs; 15286 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15287 Proto, 0, 15288 llvm::makeArrayRef(Args, NumArgs), 15289 AllArgs, 15290 CallType, AllowExplicit, 15291 IsListInitialization); 15292 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15293 15294 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15295 15296 CheckConstructorCall(Constructor, DeclInitType, 15297 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15298 Proto, Loc); 15299 15300 return Invalid; 15301 } 15302 15303 static inline bool 15304 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15305 const FunctionDecl *FnDecl) { 15306 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15307 if (isa<NamespaceDecl>(DC)) { 15308 return SemaRef.Diag(FnDecl->getLocation(), 15309 diag::err_operator_new_delete_declared_in_namespace) 15310 << FnDecl->getDeclName(); 15311 } 15312 15313 if (isa<TranslationUnitDecl>(DC) && 15314 FnDecl->getStorageClass() == SC_Static) { 15315 return SemaRef.Diag(FnDecl->getLocation(), 15316 diag::err_operator_new_delete_declared_static) 15317 << FnDecl->getDeclName(); 15318 } 15319 15320 return false; 15321 } 15322 15323 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15324 const PointerType *PtrTy) { 15325 auto &Ctx = SemaRef.Context; 15326 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15327 PtrQuals.removeAddressSpace(); 15328 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15329 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15330 } 15331 15332 static inline bool 15333 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15334 CanQualType ExpectedResultType, 15335 CanQualType ExpectedFirstParamType, 15336 unsigned DependentParamTypeDiag, 15337 unsigned InvalidParamTypeDiag) { 15338 QualType ResultType = 15339 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15340 15341 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15342 // The operator is valid on any address space for OpenCL. 15343 // Drop address space from actual and expected result types. 15344 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15345 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15346 15347 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15348 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15349 } 15350 15351 // Check that the result type is what we expect. 15352 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15353 // Reject even if the type is dependent; an operator delete function is 15354 // required to have a non-dependent result type. 15355 return SemaRef.Diag( 15356 FnDecl->getLocation(), 15357 ResultType->isDependentType() 15358 ? diag::err_operator_new_delete_dependent_result_type 15359 : diag::err_operator_new_delete_invalid_result_type) 15360 << FnDecl->getDeclName() << ExpectedResultType; 15361 } 15362 15363 // A function template must have at least 2 parameters. 15364 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15365 return SemaRef.Diag(FnDecl->getLocation(), 15366 diag::err_operator_new_delete_template_too_few_parameters) 15367 << FnDecl->getDeclName(); 15368 15369 // The function decl must have at least 1 parameter. 15370 if (FnDecl->getNumParams() == 0) 15371 return SemaRef.Diag(FnDecl->getLocation(), 15372 diag::err_operator_new_delete_too_few_parameters) 15373 << FnDecl->getDeclName(); 15374 15375 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15376 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15377 // The operator is valid on any address space for OpenCL. 15378 // Drop address space from actual and expected first parameter types. 15379 if (const auto *PtrTy = 15380 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15381 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15382 15383 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15384 ExpectedFirstParamType = 15385 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15386 } 15387 15388 // Check that the first parameter type is what we expect. 15389 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15390 ExpectedFirstParamType) { 15391 // The first parameter type is not allowed to be dependent. As a tentative 15392 // DR resolution, we allow a dependent parameter type if it is the right 15393 // type anyway, to allow destroying operator delete in class templates. 15394 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15395 ? DependentParamTypeDiag 15396 : InvalidParamTypeDiag) 15397 << FnDecl->getDeclName() << ExpectedFirstParamType; 15398 } 15399 15400 return false; 15401 } 15402 15403 static bool 15404 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15405 // C++ [basic.stc.dynamic.allocation]p1: 15406 // A program is ill-formed if an allocation function is declared in a 15407 // namespace scope other than global scope or declared static in global 15408 // scope. 15409 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15410 return true; 15411 15412 CanQualType SizeTy = 15413 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15414 15415 // C++ [basic.stc.dynamic.allocation]p1: 15416 // The return type shall be void*. The first parameter shall have type 15417 // std::size_t. 15418 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15419 SizeTy, 15420 diag::err_operator_new_dependent_param_type, 15421 diag::err_operator_new_param_type)) 15422 return true; 15423 15424 // C++ [basic.stc.dynamic.allocation]p1: 15425 // The first parameter shall not have an associated default argument. 15426 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15427 return SemaRef.Diag(FnDecl->getLocation(), 15428 diag::err_operator_new_default_arg) 15429 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15430 15431 return false; 15432 } 15433 15434 static bool 15435 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15436 // C++ [basic.stc.dynamic.deallocation]p1: 15437 // A program is ill-formed if deallocation functions are declared in a 15438 // namespace scope other than global scope or declared static in global 15439 // scope. 15440 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15441 return true; 15442 15443 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15444 15445 // C++ P0722: 15446 // Within a class C, the first parameter of a destroying operator delete 15447 // shall be of type C *. The first parameter of any other deallocation 15448 // function shall be of type void *. 15449 CanQualType ExpectedFirstParamType = 15450 MD && MD->isDestroyingOperatorDelete() 15451 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15452 SemaRef.Context.getRecordType(MD->getParent()))) 15453 : SemaRef.Context.VoidPtrTy; 15454 15455 // C++ [basic.stc.dynamic.deallocation]p2: 15456 // Each deallocation function shall return void 15457 if (CheckOperatorNewDeleteTypes( 15458 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15459 diag::err_operator_delete_dependent_param_type, 15460 diag::err_operator_delete_param_type)) 15461 return true; 15462 15463 // C++ P0722: 15464 // A destroying operator delete shall be a usual deallocation function. 15465 if (MD && !MD->getParent()->isDependentContext() && 15466 MD->isDestroyingOperatorDelete() && 15467 !SemaRef.isUsualDeallocationFunction(MD)) { 15468 SemaRef.Diag(MD->getLocation(), 15469 diag::err_destroying_operator_delete_not_usual); 15470 return true; 15471 } 15472 15473 return false; 15474 } 15475 15476 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15477 /// of this overloaded operator is well-formed. If so, returns false; 15478 /// otherwise, emits appropriate diagnostics and returns true. 15479 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15480 assert(FnDecl && FnDecl->isOverloadedOperator() && 15481 "Expected an overloaded operator declaration"); 15482 15483 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15484 15485 // C++ [over.oper]p5: 15486 // The allocation and deallocation functions, operator new, 15487 // operator new[], operator delete and operator delete[], are 15488 // described completely in 3.7.3. The attributes and restrictions 15489 // found in the rest of this subclause do not apply to them unless 15490 // explicitly stated in 3.7.3. 15491 if (Op == OO_Delete || Op == OO_Array_Delete) 15492 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15493 15494 if (Op == OO_New || Op == OO_Array_New) 15495 return CheckOperatorNewDeclaration(*this, FnDecl); 15496 15497 // C++ [over.oper]p6: 15498 // An operator function shall either be a non-static member 15499 // function or be a non-member function and have at least one 15500 // parameter whose type is a class, a reference to a class, an 15501 // enumeration, or a reference to an enumeration. 15502 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15503 if (MethodDecl->isStatic()) 15504 return Diag(FnDecl->getLocation(), 15505 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15506 } else { 15507 bool ClassOrEnumParam = false; 15508 for (auto Param : FnDecl->parameters()) { 15509 QualType ParamType = Param->getType().getNonReferenceType(); 15510 if (ParamType->isDependentType() || ParamType->isRecordType() || 15511 ParamType->isEnumeralType()) { 15512 ClassOrEnumParam = true; 15513 break; 15514 } 15515 } 15516 15517 if (!ClassOrEnumParam) 15518 return Diag(FnDecl->getLocation(), 15519 diag::err_operator_overload_needs_class_or_enum) 15520 << FnDecl->getDeclName(); 15521 } 15522 15523 // C++ [over.oper]p8: 15524 // An operator function cannot have default arguments (8.3.6), 15525 // except where explicitly stated below. 15526 // 15527 // Only the function-call operator allows default arguments 15528 // (C++ [over.call]p1). 15529 if (Op != OO_Call) { 15530 for (auto Param : FnDecl->parameters()) { 15531 if (Param->hasDefaultArg()) 15532 return Diag(Param->getLocation(), 15533 diag::err_operator_overload_default_arg) 15534 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15535 } 15536 } 15537 15538 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15539 { false, false, false } 15540 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15541 , { Unary, Binary, MemberOnly } 15542 #include "clang/Basic/OperatorKinds.def" 15543 }; 15544 15545 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15546 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15547 bool MustBeMemberOperator = OperatorUses[Op][2]; 15548 15549 // C++ [over.oper]p8: 15550 // [...] Operator functions cannot have more or fewer parameters 15551 // than the number required for the corresponding operator, as 15552 // described in the rest of this subclause. 15553 unsigned NumParams = FnDecl->getNumParams() 15554 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15555 if (Op != OO_Call && 15556 ((NumParams == 1 && !CanBeUnaryOperator) || 15557 (NumParams == 2 && !CanBeBinaryOperator) || 15558 (NumParams < 1) || (NumParams > 2))) { 15559 // We have the wrong number of parameters. 15560 unsigned ErrorKind; 15561 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15562 ErrorKind = 2; // 2 -> unary or binary. 15563 } else if (CanBeUnaryOperator) { 15564 ErrorKind = 0; // 0 -> unary 15565 } else { 15566 assert(CanBeBinaryOperator && 15567 "All non-call overloaded operators are unary or binary!"); 15568 ErrorKind = 1; // 1 -> binary 15569 } 15570 15571 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15572 << FnDecl->getDeclName() << NumParams << ErrorKind; 15573 } 15574 15575 // Overloaded operators other than operator() cannot be variadic. 15576 if (Op != OO_Call && 15577 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15578 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15579 << FnDecl->getDeclName(); 15580 } 15581 15582 // Some operators must be non-static member functions. 15583 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15584 return Diag(FnDecl->getLocation(), 15585 diag::err_operator_overload_must_be_member) 15586 << FnDecl->getDeclName(); 15587 } 15588 15589 // C++ [over.inc]p1: 15590 // The user-defined function called operator++ implements the 15591 // prefix and postfix ++ operator. If this function is a member 15592 // function with no parameters, or a non-member function with one 15593 // parameter of class or enumeration type, it defines the prefix 15594 // increment operator ++ for objects of that type. If the function 15595 // is a member function with one parameter (which shall be of type 15596 // int) or a non-member function with two parameters (the second 15597 // of which shall be of type int), it defines the postfix 15598 // increment operator ++ for objects of that type. 15599 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15600 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15601 QualType ParamType = LastParam->getType(); 15602 15603 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15604 !ParamType->isDependentType()) 15605 return Diag(LastParam->getLocation(), 15606 diag::err_operator_overload_post_incdec_must_be_int) 15607 << LastParam->getType() << (Op == OO_MinusMinus); 15608 } 15609 15610 return false; 15611 } 15612 15613 static bool 15614 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15615 FunctionTemplateDecl *TpDecl) { 15616 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15617 15618 // Must have one or two template parameters. 15619 if (TemplateParams->size() == 1) { 15620 NonTypeTemplateParmDecl *PmDecl = 15621 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15622 15623 // The template parameter must be a char parameter pack. 15624 if (PmDecl && PmDecl->isTemplateParameterPack() && 15625 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15626 return false; 15627 15628 // C++20 [over.literal]p5: 15629 // A string literal operator template is a literal operator template 15630 // whose template-parameter-list comprises a single non-type 15631 // template-parameter of class type. 15632 // 15633 // As a DR resolution, we also allow placeholders for deduced class 15634 // template specializations. 15635 if (SemaRef.getLangOpts().CPlusPlus20 && 15636 !PmDecl->isTemplateParameterPack() && 15637 (PmDecl->getType()->isRecordType() || 15638 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15639 return false; 15640 } else if (TemplateParams->size() == 2) { 15641 TemplateTypeParmDecl *PmType = 15642 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15643 NonTypeTemplateParmDecl *PmArgs = 15644 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15645 15646 // The second template parameter must be a parameter pack with the 15647 // first template parameter as its type. 15648 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15649 PmArgs->isTemplateParameterPack()) { 15650 const TemplateTypeParmType *TArgs = 15651 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15652 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15653 TArgs->getIndex() == PmType->getIndex()) { 15654 if (!SemaRef.inTemplateInstantiation()) 15655 SemaRef.Diag(TpDecl->getLocation(), 15656 diag::ext_string_literal_operator_template); 15657 return false; 15658 } 15659 } 15660 } 15661 15662 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15663 diag::err_literal_operator_template) 15664 << TpDecl->getTemplateParameters()->getSourceRange(); 15665 return true; 15666 } 15667 15668 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15669 /// of this literal operator function is well-formed. If so, returns 15670 /// false; otherwise, emits appropriate diagnostics and returns true. 15671 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15672 if (isa<CXXMethodDecl>(FnDecl)) { 15673 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15674 << FnDecl->getDeclName(); 15675 return true; 15676 } 15677 15678 if (FnDecl->isExternC()) { 15679 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15680 if (const LinkageSpecDecl *LSD = 15681 FnDecl->getDeclContext()->getExternCContext()) 15682 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15683 return true; 15684 } 15685 15686 // This might be the definition of a literal operator template. 15687 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15688 15689 // This might be a specialization of a literal operator template. 15690 if (!TpDecl) 15691 TpDecl = FnDecl->getPrimaryTemplate(); 15692 15693 // template <char...> type operator "" name() and 15694 // template <class T, T...> type operator "" name() are the only valid 15695 // template signatures, and the only valid signatures with no parameters. 15696 // 15697 // C++20 also allows template <SomeClass T> type operator "" name(). 15698 if (TpDecl) { 15699 if (FnDecl->param_size() != 0) { 15700 Diag(FnDecl->getLocation(), 15701 diag::err_literal_operator_template_with_params); 15702 return true; 15703 } 15704 15705 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15706 return true; 15707 15708 } else if (FnDecl->param_size() == 1) { 15709 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15710 15711 QualType ParamType = Param->getType().getUnqualifiedType(); 15712 15713 // Only unsigned long long int, long double, any character type, and const 15714 // char * are allowed as the only parameters. 15715 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15716 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15717 Context.hasSameType(ParamType, Context.CharTy) || 15718 Context.hasSameType(ParamType, Context.WideCharTy) || 15719 Context.hasSameType(ParamType, Context.Char8Ty) || 15720 Context.hasSameType(ParamType, Context.Char16Ty) || 15721 Context.hasSameType(ParamType, Context.Char32Ty)) { 15722 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15723 QualType InnerType = Ptr->getPointeeType(); 15724 15725 // Pointer parameter must be a const char *. 15726 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15727 Context.CharTy) && 15728 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15729 Diag(Param->getSourceRange().getBegin(), 15730 diag::err_literal_operator_param) 15731 << ParamType << "'const char *'" << Param->getSourceRange(); 15732 return true; 15733 } 15734 15735 } else if (ParamType->isRealFloatingType()) { 15736 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15737 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15738 return true; 15739 15740 } else if (ParamType->isIntegerType()) { 15741 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15742 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15743 return true; 15744 15745 } else { 15746 Diag(Param->getSourceRange().getBegin(), 15747 diag::err_literal_operator_invalid_param) 15748 << ParamType << Param->getSourceRange(); 15749 return true; 15750 } 15751 15752 } else if (FnDecl->param_size() == 2) { 15753 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15754 15755 // First, verify that the first parameter is correct. 15756 15757 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15758 15759 // Two parameter function must have a pointer to const as a 15760 // first parameter; let's strip those qualifiers. 15761 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15762 15763 if (!PT) { 15764 Diag((*Param)->getSourceRange().getBegin(), 15765 diag::err_literal_operator_param) 15766 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15767 return true; 15768 } 15769 15770 QualType PointeeType = PT->getPointeeType(); 15771 // First parameter must be const 15772 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15773 Diag((*Param)->getSourceRange().getBegin(), 15774 diag::err_literal_operator_param) 15775 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15776 return true; 15777 } 15778 15779 QualType InnerType = PointeeType.getUnqualifiedType(); 15780 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15781 // const char32_t* are allowed as the first parameter to a two-parameter 15782 // function 15783 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15784 Context.hasSameType(InnerType, Context.WideCharTy) || 15785 Context.hasSameType(InnerType, Context.Char8Ty) || 15786 Context.hasSameType(InnerType, Context.Char16Ty) || 15787 Context.hasSameType(InnerType, Context.Char32Ty))) { 15788 Diag((*Param)->getSourceRange().getBegin(), 15789 diag::err_literal_operator_param) 15790 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15791 return true; 15792 } 15793 15794 // Move on to the second and final parameter. 15795 ++Param; 15796 15797 // The second parameter must be a std::size_t. 15798 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15799 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15800 Diag((*Param)->getSourceRange().getBegin(), 15801 diag::err_literal_operator_param) 15802 << SecondParamType << Context.getSizeType() 15803 << (*Param)->getSourceRange(); 15804 return true; 15805 } 15806 } else { 15807 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15808 return true; 15809 } 15810 15811 // Parameters are good. 15812 15813 // A parameter-declaration-clause containing a default argument is not 15814 // equivalent to any of the permitted forms. 15815 for (auto Param : FnDecl->parameters()) { 15816 if (Param->hasDefaultArg()) { 15817 Diag(Param->getDefaultArgRange().getBegin(), 15818 diag::err_literal_operator_default_argument) 15819 << Param->getDefaultArgRange(); 15820 break; 15821 } 15822 } 15823 15824 StringRef LiteralName 15825 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15826 if (LiteralName[0] != '_' && 15827 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15828 // C++11 [usrlit.suffix]p1: 15829 // Literal suffix identifiers that do not start with an underscore 15830 // are reserved for future standardization. 15831 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15832 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15833 } 15834 15835 return false; 15836 } 15837 15838 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15839 /// linkage specification, including the language and (if present) 15840 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15841 /// language string literal. LBraceLoc, if valid, provides the location of 15842 /// the '{' brace. Otherwise, this linkage specification does not 15843 /// have any braces. 15844 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15845 Expr *LangStr, 15846 SourceLocation LBraceLoc) { 15847 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15848 if (!Lit->isAscii()) { 15849 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15850 << LangStr->getSourceRange(); 15851 return nullptr; 15852 } 15853 15854 StringRef Lang = Lit->getString(); 15855 LinkageSpecDecl::LanguageIDs Language; 15856 if (Lang == "C") 15857 Language = LinkageSpecDecl::lang_c; 15858 else if (Lang == "C++") 15859 Language = LinkageSpecDecl::lang_cxx; 15860 else { 15861 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15862 << LangStr->getSourceRange(); 15863 return nullptr; 15864 } 15865 15866 // FIXME: Add all the various semantics of linkage specifications 15867 15868 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15869 LangStr->getExprLoc(), Language, 15870 LBraceLoc.isValid()); 15871 CurContext->addDecl(D); 15872 PushDeclContext(S, D); 15873 return D; 15874 } 15875 15876 /// ActOnFinishLinkageSpecification - Complete the definition of 15877 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15878 /// valid, it's the position of the closing '}' brace in a linkage 15879 /// specification that uses braces. 15880 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15881 Decl *LinkageSpec, 15882 SourceLocation RBraceLoc) { 15883 if (RBraceLoc.isValid()) { 15884 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15885 LSDecl->setRBraceLoc(RBraceLoc); 15886 } 15887 PopDeclContext(); 15888 return LinkageSpec; 15889 } 15890 15891 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15892 const ParsedAttributesView &AttrList, 15893 SourceLocation SemiLoc) { 15894 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15895 // Attribute declarations appertain to empty declaration so we handle 15896 // them here. 15897 ProcessDeclAttributeList(S, ED, AttrList); 15898 15899 CurContext->addDecl(ED); 15900 return ED; 15901 } 15902 15903 /// Perform semantic analysis for the variable declaration that 15904 /// occurs within a C++ catch clause, returning the newly-created 15905 /// variable. 15906 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15907 TypeSourceInfo *TInfo, 15908 SourceLocation StartLoc, 15909 SourceLocation Loc, 15910 IdentifierInfo *Name) { 15911 bool Invalid = false; 15912 QualType ExDeclType = TInfo->getType(); 15913 15914 // Arrays and functions decay. 15915 if (ExDeclType->isArrayType()) 15916 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15917 else if (ExDeclType->isFunctionType()) 15918 ExDeclType = Context.getPointerType(ExDeclType); 15919 15920 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15921 // The exception-declaration shall not denote a pointer or reference to an 15922 // incomplete type, other than [cv] void*. 15923 // N2844 forbids rvalue references. 15924 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15925 Diag(Loc, diag::err_catch_rvalue_ref); 15926 Invalid = true; 15927 } 15928 15929 if (ExDeclType->isVariablyModifiedType()) { 15930 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15931 Invalid = true; 15932 } 15933 15934 QualType BaseType = ExDeclType; 15935 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15936 unsigned DK = diag::err_catch_incomplete; 15937 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15938 BaseType = Ptr->getPointeeType(); 15939 Mode = 1; 15940 DK = diag::err_catch_incomplete_ptr; 15941 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15942 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15943 BaseType = Ref->getPointeeType(); 15944 Mode = 2; 15945 DK = diag::err_catch_incomplete_ref; 15946 } 15947 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15948 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15949 Invalid = true; 15950 15951 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15952 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15953 Invalid = true; 15954 } 15955 15956 if (!Invalid && !ExDeclType->isDependentType() && 15957 RequireNonAbstractType(Loc, ExDeclType, 15958 diag::err_abstract_type_in_decl, 15959 AbstractVariableType)) 15960 Invalid = true; 15961 15962 // Only the non-fragile NeXT runtime currently supports C++ catches 15963 // of ObjC types, and no runtime supports catching ObjC types by value. 15964 if (!Invalid && getLangOpts().ObjC) { 15965 QualType T = ExDeclType; 15966 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15967 T = RT->getPointeeType(); 15968 15969 if (T->isObjCObjectType()) { 15970 Diag(Loc, diag::err_objc_object_catch); 15971 Invalid = true; 15972 } else if (T->isObjCObjectPointerType()) { 15973 // FIXME: should this be a test for macosx-fragile specifically? 15974 if (getLangOpts().ObjCRuntime.isFragile()) 15975 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15976 } 15977 } 15978 15979 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15980 ExDeclType, TInfo, SC_None); 15981 ExDecl->setExceptionVariable(true); 15982 15983 // In ARC, infer 'retaining' for variables of retainable type. 15984 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15985 Invalid = true; 15986 15987 if (!Invalid && !ExDeclType->isDependentType()) { 15988 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15989 // Insulate this from anything else we might currently be parsing. 15990 EnterExpressionEvaluationContext scope( 15991 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15992 15993 // C++ [except.handle]p16: 15994 // The object declared in an exception-declaration or, if the 15995 // exception-declaration does not specify a name, a temporary (12.2) is 15996 // copy-initialized (8.5) from the exception object. [...] 15997 // The object is destroyed when the handler exits, after the destruction 15998 // of any automatic objects initialized within the handler. 15999 // 16000 // We just pretend to initialize the object with itself, then make sure 16001 // it can be destroyed later. 16002 QualType initType = Context.getExceptionObjectType(ExDeclType); 16003 16004 InitializedEntity entity = 16005 InitializedEntity::InitializeVariable(ExDecl); 16006 InitializationKind initKind = 16007 InitializationKind::CreateCopy(Loc, SourceLocation()); 16008 16009 Expr *opaqueValue = 16010 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16011 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16012 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16013 if (result.isInvalid()) 16014 Invalid = true; 16015 else { 16016 // If the constructor used was non-trivial, set this as the 16017 // "initializer". 16018 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16019 if (!construct->getConstructor()->isTrivial()) { 16020 Expr *init = MaybeCreateExprWithCleanups(construct); 16021 ExDecl->setInit(init); 16022 } 16023 16024 // And make sure it's destructable. 16025 FinalizeVarWithDestructor(ExDecl, recordType); 16026 } 16027 } 16028 } 16029 16030 if (Invalid) 16031 ExDecl->setInvalidDecl(); 16032 16033 return ExDecl; 16034 } 16035 16036 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16037 /// handler. 16038 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16039 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16040 bool Invalid = D.isInvalidType(); 16041 16042 // Check for unexpanded parameter packs. 16043 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16044 UPPC_ExceptionType)) { 16045 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16046 D.getIdentifierLoc()); 16047 Invalid = true; 16048 } 16049 16050 IdentifierInfo *II = D.getIdentifier(); 16051 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16052 LookupOrdinaryName, 16053 ForVisibleRedeclaration)) { 16054 // The scope should be freshly made just for us. There is just no way 16055 // it contains any previous declaration, except for function parameters in 16056 // a function-try-block's catch statement. 16057 assert(!S->isDeclScope(PrevDecl)); 16058 if (isDeclInScope(PrevDecl, CurContext, S)) { 16059 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16060 << D.getIdentifier(); 16061 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16062 Invalid = true; 16063 } else if (PrevDecl->isTemplateParameter()) 16064 // Maybe we will complain about the shadowed template parameter. 16065 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16066 } 16067 16068 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16069 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16070 << D.getCXXScopeSpec().getRange(); 16071 Invalid = true; 16072 } 16073 16074 VarDecl *ExDecl = BuildExceptionDeclaration( 16075 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16076 if (Invalid) 16077 ExDecl->setInvalidDecl(); 16078 16079 // Add the exception declaration into this scope. 16080 if (II) 16081 PushOnScopeChains(ExDecl, S); 16082 else 16083 CurContext->addDecl(ExDecl); 16084 16085 ProcessDeclAttributes(S, ExDecl, D); 16086 return ExDecl; 16087 } 16088 16089 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16090 Expr *AssertExpr, 16091 Expr *AssertMessageExpr, 16092 SourceLocation RParenLoc) { 16093 StringLiteral *AssertMessage = 16094 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16095 16096 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16097 return nullptr; 16098 16099 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16100 AssertMessage, RParenLoc, false); 16101 } 16102 16103 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16104 Expr *AssertExpr, 16105 StringLiteral *AssertMessage, 16106 SourceLocation RParenLoc, 16107 bool Failed) { 16108 assert(AssertExpr != nullptr && "Expected non-null condition"); 16109 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16110 !Failed) { 16111 // In a static_assert-declaration, the constant-expression shall be a 16112 // constant expression that can be contextually converted to bool. 16113 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16114 if (Converted.isInvalid()) 16115 Failed = true; 16116 16117 ExprResult FullAssertExpr = 16118 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16119 /*DiscardedValue*/ false, 16120 /*IsConstexpr*/ true); 16121 if (FullAssertExpr.isInvalid()) 16122 Failed = true; 16123 else 16124 AssertExpr = FullAssertExpr.get(); 16125 16126 llvm::APSInt Cond; 16127 if (!Failed && VerifyIntegerConstantExpression( 16128 AssertExpr, &Cond, 16129 diag::err_static_assert_expression_is_not_constant) 16130 .isInvalid()) 16131 Failed = true; 16132 16133 if (!Failed && !Cond) { 16134 SmallString<256> MsgBuffer; 16135 llvm::raw_svector_ostream Msg(MsgBuffer); 16136 if (AssertMessage) 16137 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16138 16139 Expr *InnerCond = nullptr; 16140 std::string InnerCondDescription; 16141 std::tie(InnerCond, InnerCondDescription) = 16142 findFailedBooleanCondition(Converted.get()); 16143 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16144 // Drill down into concept specialization expressions to see why they 16145 // weren't satisfied. 16146 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16147 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16148 ConstraintSatisfaction Satisfaction; 16149 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16150 DiagnoseUnsatisfiedConstraint(Satisfaction); 16151 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16152 && !isa<IntegerLiteral>(InnerCond)) { 16153 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16154 << InnerCondDescription << !AssertMessage 16155 << Msg.str() << InnerCond->getSourceRange(); 16156 } else { 16157 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16158 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16159 } 16160 Failed = true; 16161 } 16162 } else { 16163 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16164 /*DiscardedValue*/false, 16165 /*IsConstexpr*/true); 16166 if (FullAssertExpr.isInvalid()) 16167 Failed = true; 16168 else 16169 AssertExpr = FullAssertExpr.get(); 16170 } 16171 16172 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16173 AssertExpr, AssertMessage, RParenLoc, 16174 Failed); 16175 16176 CurContext->addDecl(Decl); 16177 return Decl; 16178 } 16179 16180 /// Perform semantic analysis of the given friend type declaration. 16181 /// 16182 /// \returns A friend declaration that. 16183 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16184 SourceLocation FriendLoc, 16185 TypeSourceInfo *TSInfo) { 16186 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16187 16188 QualType T = TSInfo->getType(); 16189 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16190 16191 // C++03 [class.friend]p2: 16192 // An elaborated-type-specifier shall be used in a friend declaration 16193 // for a class.* 16194 // 16195 // * The class-key of the elaborated-type-specifier is required. 16196 if (!CodeSynthesisContexts.empty()) { 16197 // Do not complain about the form of friend template types during any kind 16198 // of code synthesis. For template instantiation, we will have complained 16199 // when the template was defined. 16200 } else { 16201 if (!T->isElaboratedTypeSpecifier()) { 16202 // If we evaluated the type to a record type, suggest putting 16203 // a tag in front. 16204 if (const RecordType *RT = T->getAs<RecordType>()) { 16205 RecordDecl *RD = RT->getDecl(); 16206 16207 SmallString<16> InsertionText(" "); 16208 InsertionText += RD->getKindName(); 16209 16210 Diag(TypeRange.getBegin(), 16211 getLangOpts().CPlusPlus11 ? 16212 diag::warn_cxx98_compat_unelaborated_friend_type : 16213 diag::ext_unelaborated_friend_type) 16214 << (unsigned) RD->getTagKind() 16215 << T 16216 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16217 InsertionText); 16218 } else { 16219 Diag(FriendLoc, 16220 getLangOpts().CPlusPlus11 ? 16221 diag::warn_cxx98_compat_nonclass_type_friend : 16222 diag::ext_nonclass_type_friend) 16223 << T 16224 << TypeRange; 16225 } 16226 } else if (T->getAs<EnumType>()) { 16227 Diag(FriendLoc, 16228 getLangOpts().CPlusPlus11 ? 16229 diag::warn_cxx98_compat_enum_friend : 16230 diag::ext_enum_friend) 16231 << T 16232 << TypeRange; 16233 } 16234 16235 // C++11 [class.friend]p3: 16236 // A friend declaration that does not declare a function shall have one 16237 // of the following forms: 16238 // friend elaborated-type-specifier ; 16239 // friend simple-type-specifier ; 16240 // friend typename-specifier ; 16241 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16242 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16243 } 16244 16245 // If the type specifier in a friend declaration designates a (possibly 16246 // cv-qualified) class type, that class is declared as a friend; otherwise, 16247 // the friend declaration is ignored. 16248 return FriendDecl::Create(Context, CurContext, 16249 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16250 FriendLoc); 16251 } 16252 16253 /// Handle a friend tag declaration where the scope specifier was 16254 /// templated. 16255 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16256 unsigned TagSpec, SourceLocation TagLoc, 16257 CXXScopeSpec &SS, IdentifierInfo *Name, 16258 SourceLocation NameLoc, 16259 const ParsedAttributesView &Attr, 16260 MultiTemplateParamsArg TempParamLists) { 16261 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16262 16263 bool IsMemberSpecialization = false; 16264 bool Invalid = false; 16265 16266 if (TemplateParameterList *TemplateParams = 16267 MatchTemplateParametersToScopeSpecifier( 16268 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16269 IsMemberSpecialization, Invalid)) { 16270 if (TemplateParams->size() > 0) { 16271 // This is a declaration of a class template. 16272 if (Invalid) 16273 return nullptr; 16274 16275 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16276 NameLoc, Attr, TemplateParams, AS_public, 16277 /*ModulePrivateLoc=*/SourceLocation(), 16278 FriendLoc, TempParamLists.size() - 1, 16279 TempParamLists.data()).get(); 16280 } else { 16281 // The "template<>" header is extraneous. 16282 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16283 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16284 IsMemberSpecialization = true; 16285 } 16286 } 16287 16288 if (Invalid) return nullptr; 16289 16290 bool isAllExplicitSpecializations = true; 16291 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16292 if (TempParamLists[I]->size()) { 16293 isAllExplicitSpecializations = false; 16294 break; 16295 } 16296 } 16297 16298 // FIXME: don't ignore attributes. 16299 16300 // If it's explicit specializations all the way down, just forget 16301 // about the template header and build an appropriate non-templated 16302 // friend. TODO: for source fidelity, remember the headers. 16303 if (isAllExplicitSpecializations) { 16304 if (SS.isEmpty()) { 16305 bool Owned = false; 16306 bool IsDependent = false; 16307 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16308 Attr, AS_public, 16309 /*ModulePrivateLoc=*/SourceLocation(), 16310 MultiTemplateParamsArg(), Owned, IsDependent, 16311 /*ScopedEnumKWLoc=*/SourceLocation(), 16312 /*ScopedEnumUsesClassTag=*/false, 16313 /*UnderlyingType=*/TypeResult(), 16314 /*IsTypeSpecifier=*/false, 16315 /*IsTemplateParamOrArg=*/false); 16316 } 16317 16318 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16319 ElaboratedTypeKeyword Keyword 16320 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16321 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16322 *Name, NameLoc); 16323 if (T.isNull()) 16324 return nullptr; 16325 16326 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16327 if (isa<DependentNameType>(T)) { 16328 DependentNameTypeLoc TL = 16329 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16330 TL.setElaboratedKeywordLoc(TagLoc); 16331 TL.setQualifierLoc(QualifierLoc); 16332 TL.setNameLoc(NameLoc); 16333 } else { 16334 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16335 TL.setElaboratedKeywordLoc(TagLoc); 16336 TL.setQualifierLoc(QualifierLoc); 16337 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16338 } 16339 16340 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16341 TSI, FriendLoc, TempParamLists); 16342 Friend->setAccess(AS_public); 16343 CurContext->addDecl(Friend); 16344 return Friend; 16345 } 16346 16347 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16348 16349 16350 16351 // Handle the case of a templated-scope friend class. e.g. 16352 // template <class T> class A<T>::B; 16353 // FIXME: we don't support these right now. 16354 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16355 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16356 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16357 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16358 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16359 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16360 TL.setElaboratedKeywordLoc(TagLoc); 16361 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16362 TL.setNameLoc(NameLoc); 16363 16364 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16365 TSI, FriendLoc, TempParamLists); 16366 Friend->setAccess(AS_public); 16367 Friend->setUnsupportedFriend(true); 16368 CurContext->addDecl(Friend); 16369 return Friend; 16370 } 16371 16372 /// Handle a friend type declaration. This works in tandem with 16373 /// ActOnTag. 16374 /// 16375 /// Notes on friend class templates: 16376 /// 16377 /// We generally treat friend class declarations as if they were 16378 /// declaring a class. So, for example, the elaborated type specifier 16379 /// in a friend declaration is required to obey the restrictions of a 16380 /// class-head (i.e. no typedefs in the scope chain), template 16381 /// parameters are required to match up with simple template-ids, &c. 16382 /// However, unlike when declaring a template specialization, it's 16383 /// okay to refer to a template specialization without an empty 16384 /// template parameter declaration, e.g. 16385 /// friend class A<T>::B<unsigned>; 16386 /// We permit this as a special case; if there are any template 16387 /// parameters present at all, require proper matching, i.e. 16388 /// template <> template \<class T> friend class A<int>::B; 16389 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16390 MultiTemplateParamsArg TempParams) { 16391 SourceLocation Loc = DS.getBeginLoc(); 16392 16393 assert(DS.isFriendSpecified()); 16394 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16395 16396 // C++ [class.friend]p3: 16397 // A friend declaration that does not declare a function shall have one of 16398 // the following forms: 16399 // friend elaborated-type-specifier ; 16400 // friend simple-type-specifier ; 16401 // friend typename-specifier ; 16402 // 16403 // Any declaration with a type qualifier does not have that form. (It's 16404 // legal to specify a qualified type as a friend, you just can't write the 16405 // keywords.) 16406 if (DS.getTypeQualifiers()) { 16407 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16408 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16409 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16410 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16411 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16412 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16413 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16414 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16415 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16416 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16417 } 16418 16419 // Try to convert the decl specifier to a type. This works for 16420 // friend templates because ActOnTag never produces a ClassTemplateDecl 16421 // for a TUK_Friend. 16422 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16423 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16424 QualType T = TSI->getType(); 16425 if (TheDeclarator.isInvalidType()) 16426 return nullptr; 16427 16428 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16429 return nullptr; 16430 16431 // This is definitely an error in C++98. It's probably meant to 16432 // be forbidden in C++0x, too, but the specification is just 16433 // poorly written. 16434 // 16435 // The problem is with declarations like the following: 16436 // template <T> friend A<T>::foo; 16437 // where deciding whether a class C is a friend or not now hinges 16438 // on whether there exists an instantiation of A that causes 16439 // 'foo' to equal C. There are restrictions on class-heads 16440 // (which we declare (by fiat) elaborated friend declarations to 16441 // be) that makes this tractable. 16442 // 16443 // FIXME: handle "template <> friend class A<T>;", which 16444 // is possibly well-formed? Who even knows? 16445 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16446 Diag(Loc, diag::err_tagless_friend_type_template) 16447 << DS.getSourceRange(); 16448 return nullptr; 16449 } 16450 16451 // C++98 [class.friend]p1: A friend of a class is a function 16452 // or class that is not a member of the class . . . 16453 // This is fixed in DR77, which just barely didn't make the C++03 16454 // deadline. It's also a very silly restriction that seriously 16455 // affects inner classes and which nobody else seems to implement; 16456 // thus we never diagnose it, not even in -pedantic. 16457 // 16458 // But note that we could warn about it: it's always useless to 16459 // friend one of your own members (it's not, however, worthless to 16460 // friend a member of an arbitrary specialization of your template). 16461 16462 Decl *D; 16463 if (!TempParams.empty()) 16464 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16465 TempParams, 16466 TSI, 16467 DS.getFriendSpecLoc()); 16468 else 16469 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16470 16471 if (!D) 16472 return nullptr; 16473 16474 D->setAccess(AS_public); 16475 CurContext->addDecl(D); 16476 16477 return D; 16478 } 16479 16480 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16481 MultiTemplateParamsArg TemplateParams) { 16482 const DeclSpec &DS = D.getDeclSpec(); 16483 16484 assert(DS.isFriendSpecified()); 16485 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16486 16487 SourceLocation Loc = D.getIdentifierLoc(); 16488 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16489 16490 // C++ [class.friend]p1 16491 // A friend of a class is a function or class.... 16492 // Note that this sees through typedefs, which is intended. 16493 // It *doesn't* see through dependent types, which is correct 16494 // according to [temp.arg.type]p3: 16495 // If a declaration acquires a function type through a 16496 // type dependent on a template-parameter and this causes 16497 // a declaration that does not use the syntactic form of a 16498 // function declarator to have a function type, the program 16499 // is ill-formed. 16500 if (!TInfo->getType()->isFunctionType()) { 16501 Diag(Loc, diag::err_unexpected_friend); 16502 16503 // It might be worthwhile to try to recover by creating an 16504 // appropriate declaration. 16505 return nullptr; 16506 } 16507 16508 // C++ [namespace.memdef]p3 16509 // - If a friend declaration in a non-local class first declares a 16510 // class or function, the friend class or function is a member 16511 // of the innermost enclosing namespace. 16512 // - The name of the friend is not found by simple name lookup 16513 // until a matching declaration is provided in that namespace 16514 // scope (either before or after the class declaration granting 16515 // friendship). 16516 // - If a friend function is called, its name may be found by the 16517 // name lookup that considers functions from namespaces and 16518 // classes associated with the types of the function arguments. 16519 // - When looking for a prior declaration of a class or a function 16520 // declared as a friend, scopes outside the innermost enclosing 16521 // namespace scope are not considered. 16522 16523 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16524 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16525 assert(NameInfo.getName()); 16526 16527 // Check for unexpanded parameter packs. 16528 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16529 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16530 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16531 return nullptr; 16532 16533 // The context we found the declaration in, or in which we should 16534 // create the declaration. 16535 DeclContext *DC; 16536 Scope *DCScope = S; 16537 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16538 ForExternalRedeclaration); 16539 16540 // There are five cases here. 16541 // - There's no scope specifier and we're in a local class. Only look 16542 // for functions declared in the immediately-enclosing block scope. 16543 // We recover from invalid scope qualifiers as if they just weren't there. 16544 FunctionDecl *FunctionContainingLocalClass = nullptr; 16545 if ((SS.isInvalid() || !SS.isSet()) && 16546 (FunctionContainingLocalClass = 16547 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16548 // C++11 [class.friend]p11: 16549 // If a friend declaration appears in a local class and the name 16550 // specified is an unqualified name, a prior declaration is 16551 // looked up without considering scopes that are outside the 16552 // innermost enclosing non-class scope. For a friend function 16553 // declaration, if there is no prior declaration, the program is 16554 // ill-formed. 16555 16556 // Find the innermost enclosing non-class scope. This is the block 16557 // scope containing the local class definition (or for a nested class, 16558 // the outer local class). 16559 DCScope = S->getFnParent(); 16560 16561 // Look up the function name in the scope. 16562 Previous.clear(LookupLocalFriendName); 16563 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16564 16565 if (!Previous.empty()) { 16566 // All possible previous declarations must have the same context: 16567 // either they were declared at block scope or they are members of 16568 // one of the enclosing local classes. 16569 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16570 } else { 16571 // This is ill-formed, but provide the context that we would have 16572 // declared the function in, if we were permitted to, for error recovery. 16573 DC = FunctionContainingLocalClass; 16574 } 16575 adjustContextForLocalExternDecl(DC); 16576 16577 // C++ [class.friend]p6: 16578 // A function can be defined in a friend declaration of a class if and 16579 // only if the class is a non-local class (9.8), the function name is 16580 // unqualified, and the function has namespace scope. 16581 if (D.isFunctionDefinition()) { 16582 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16583 } 16584 16585 // - There's no scope specifier, in which case we just go to the 16586 // appropriate scope and look for a function or function template 16587 // there as appropriate. 16588 } else if (SS.isInvalid() || !SS.isSet()) { 16589 // C++11 [namespace.memdef]p3: 16590 // If the name in a friend declaration is neither qualified nor 16591 // a template-id and the declaration is a function or an 16592 // elaborated-type-specifier, the lookup to determine whether 16593 // the entity has been previously declared shall not consider 16594 // any scopes outside the innermost enclosing namespace. 16595 bool isTemplateId = 16596 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16597 16598 // Find the appropriate context according to the above. 16599 DC = CurContext; 16600 16601 // Skip class contexts. If someone can cite chapter and verse 16602 // for this behavior, that would be nice --- it's what GCC and 16603 // EDG do, and it seems like a reasonable intent, but the spec 16604 // really only says that checks for unqualified existing 16605 // declarations should stop at the nearest enclosing namespace, 16606 // not that they should only consider the nearest enclosing 16607 // namespace. 16608 while (DC->isRecord()) 16609 DC = DC->getParent(); 16610 16611 DeclContext *LookupDC = DC; 16612 while (LookupDC->isTransparentContext()) 16613 LookupDC = LookupDC->getParent(); 16614 16615 while (true) { 16616 LookupQualifiedName(Previous, LookupDC); 16617 16618 if (!Previous.empty()) { 16619 DC = LookupDC; 16620 break; 16621 } 16622 16623 if (isTemplateId) { 16624 if (isa<TranslationUnitDecl>(LookupDC)) break; 16625 } else { 16626 if (LookupDC->isFileContext()) break; 16627 } 16628 LookupDC = LookupDC->getParent(); 16629 } 16630 16631 DCScope = getScopeForDeclContext(S, DC); 16632 16633 // - There's a non-dependent scope specifier, in which case we 16634 // compute it and do a previous lookup there for a function 16635 // or function template. 16636 } else if (!SS.getScopeRep()->isDependent()) { 16637 DC = computeDeclContext(SS); 16638 if (!DC) return nullptr; 16639 16640 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16641 16642 LookupQualifiedName(Previous, DC); 16643 16644 // C++ [class.friend]p1: A friend of a class is a function or 16645 // class that is not a member of the class . . . 16646 if (DC->Equals(CurContext)) 16647 Diag(DS.getFriendSpecLoc(), 16648 getLangOpts().CPlusPlus11 ? 16649 diag::warn_cxx98_compat_friend_is_member : 16650 diag::err_friend_is_member); 16651 16652 if (D.isFunctionDefinition()) { 16653 // C++ [class.friend]p6: 16654 // A function can be defined in a friend declaration of a class if and 16655 // only if the class is a non-local class (9.8), the function name is 16656 // unqualified, and the function has namespace scope. 16657 // 16658 // FIXME: We should only do this if the scope specifier names the 16659 // innermost enclosing namespace; otherwise the fixit changes the 16660 // meaning of the code. 16661 SemaDiagnosticBuilder DB 16662 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16663 16664 DB << SS.getScopeRep(); 16665 if (DC->isFileContext()) 16666 DB << FixItHint::CreateRemoval(SS.getRange()); 16667 SS.clear(); 16668 } 16669 16670 // - There's a scope specifier that does not match any template 16671 // parameter lists, in which case we use some arbitrary context, 16672 // create a method or method template, and wait for instantiation. 16673 // - There's a scope specifier that does match some template 16674 // parameter lists, which we don't handle right now. 16675 } else { 16676 if (D.isFunctionDefinition()) { 16677 // C++ [class.friend]p6: 16678 // A function can be defined in a friend declaration of a class if and 16679 // only if the class is a non-local class (9.8), the function name is 16680 // unqualified, and the function has namespace scope. 16681 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16682 << SS.getScopeRep(); 16683 } 16684 16685 DC = CurContext; 16686 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16687 } 16688 16689 if (!DC->isRecord()) { 16690 int DiagArg = -1; 16691 switch (D.getName().getKind()) { 16692 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16693 case UnqualifiedIdKind::IK_ConstructorName: 16694 DiagArg = 0; 16695 break; 16696 case UnqualifiedIdKind::IK_DestructorName: 16697 DiagArg = 1; 16698 break; 16699 case UnqualifiedIdKind::IK_ConversionFunctionId: 16700 DiagArg = 2; 16701 break; 16702 case UnqualifiedIdKind::IK_DeductionGuideName: 16703 DiagArg = 3; 16704 break; 16705 case UnqualifiedIdKind::IK_Identifier: 16706 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16707 case UnqualifiedIdKind::IK_LiteralOperatorId: 16708 case UnqualifiedIdKind::IK_OperatorFunctionId: 16709 case UnqualifiedIdKind::IK_TemplateId: 16710 break; 16711 } 16712 // This implies that it has to be an operator or function. 16713 if (DiagArg >= 0) { 16714 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16715 return nullptr; 16716 } 16717 } 16718 16719 // FIXME: This is an egregious hack to cope with cases where the scope stack 16720 // does not contain the declaration context, i.e., in an out-of-line 16721 // definition of a class. 16722 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16723 if (!DCScope) { 16724 FakeDCScope.setEntity(DC); 16725 DCScope = &FakeDCScope; 16726 } 16727 16728 bool AddToScope = true; 16729 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16730 TemplateParams, AddToScope); 16731 if (!ND) return nullptr; 16732 16733 assert(ND->getLexicalDeclContext() == CurContext); 16734 16735 // If we performed typo correction, we might have added a scope specifier 16736 // and changed the decl context. 16737 DC = ND->getDeclContext(); 16738 16739 // Add the function declaration to the appropriate lookup tables, 16740 // adjusting the redeclarations list as necessary. We don't 16741 // want to do this yet if the friending class is dependent. 16742 // 16743 // Also update the scope-based lookup if the target context's 16744 // lookup context is in lexical scope. 16745 if (!CurContext->isDependentContext()) { 16746 DC = DC->getRedeclContext(); 16747 DC->makeDeclVisibleInContext(ND); 16748 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16749 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16750 } 16751 16752 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16753 D.getIdentifierLoc(), ND, 16754 DS.getFriendSpecLoc()); 16755 FrD->setAccess(AS_public); 16756 CurContext->addDecl(FrD); 16757 16758 if (ND->isInvalidDecl()) { 16759 FrD->setInvalidDecl(); 16760 } else { 16761 if (DC->isRecord()) CheckFriendAccess(ND); 16762 16763 FunctionDecl *FD; 16764 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16765 FD = FTD->getTemplatedDecl(); 16766 else 16767 FD = cast<FunctionDecl>(ND); 16768 16769 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16770 // default argument expression, that declaration shall be a definition 16771 // and shall be the only declaration of the function or function 16772 // template in the translation unit. 16773 if (functionDeclHasDefaultArgument(FD)) { 16774 // We can't look at FD->getPreviousDecl() because it may not have been set 16775 // if we're in a dependent context. If the function is known to be a 16776 // redeclaration, we will have narrowed Previous down to the right decl. 16777 if (D.isRedeclaration()) { 16778 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16779 Diag(Previous.getRepresentativeDecl()->getLocation(), 16780 diag::note_previous_declaration); 16781 } else if (!D.isFunctionDefinition()) 16782 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16783 } 16784 16785 // Mark templated-scope function declarations as unsupported. 16786 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16787 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16788 << SS.getScopeRep() << SS.getRange() 16789 << cast<CXXRecordDecl>(CurContext); 16790 FrD->setUnsupportedFriend(true); 16791 } 16792 } 16793 16794 return ND; 16795 } 16796 16797 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16798 AdjustDeclIfTemplate(Dcl); 16799 16800 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16801 if (!Fn) { 16802 Diag(DelLoc, diag::err_deleted_non_function); 16803 return; 16804 } 16805 16806 // Deleted function does not have a body. 16807 Fn->setWillHaveBody(false); 16808 16809 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16810 // Don't consider the implicit declaration we generate for explicit 16811 // specializations. FIXME: Do not generate these implicit declarations. 16812 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16813 Prev->getPreviousDecl()) && 16814 !Prev->isDefined()) { 16815 Diag(DelLoc, diag::err_deleted_decl_not_first); 16816 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16817 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16818 : diag::note_previous_declaration); 16819 // We can't recover from this; the declaration might have already 16820 // been used. 16821 Fn->setInvalidDecl(); 16822 return; 16823 } 16824 16825 // To maintain the invariant that functions are only deleted on their first 16826 // declaration, mark the implicitly-instantiated declaration of the 16827 // explicitly-specialized function as deleted instead of marking the 16828 // instantiated redeclaration. 16829 Fn = Fn->getCanonicalDecl(); 16830 } 16831 16832 // dllimport/dllexport cannot be deleted. 16833 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16834 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16835 Fn->setInvalidDecl(); 16836 } 16837 16838 // C++11 [basic.start.main]p3: 16839 // A program that defines main as deleted [...] is ill-formed. 16840 if (Fn->isMain()) 16841 Diag(DelLoc, diag::err_deleted_main); 16842 16843 // C++11 [dcl.fct.def.delete]p4: 16844 // A deleted function is implicitly inline. 16845 Fn->setImplicitlyInline(); 16846 Fn->setDeletedAsWritten(); 16847 } 16848 16849 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16850 if (!Dcl || Dcl->isInvalidDecl()) 16851 return; 16852 16853 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16854 if (!FD) { 16855 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16856 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16857 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16858 return; 16859 } 16860 } 16861 16862 Diag(DefaultLoc, diag::err_default_special_members) 16863 << getLangOpts().CPlusPlus20; 16864 return; 16865 } 16866 16867 // Reject if this can't possibly be a defaultable function. 16868 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16869 if (!DefKind && 16870 // A dependent function that doesn't locally look defaultable can 16871 // still instantiate to a defaultable function if it's a constructor 16872 // or assignment operator. 16873 (!FD->isDependentContext() || 16874 (!isa<CXXConstructorDecl>(FD) && 16875 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16876 Diag(DefaultLoc, diag::err_default_special_members) 16877 << getLangOpts().CPlusPlus20; 16878 return; 16879 } 16880 16881 if (DefKind.isComparison() && 16882 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16883 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16884 << (int)DefKind.asComparison(); 16885 return; 16886 } 16887 16888 // Issue compatibility warning. We already warned if the operator is 16889 // 'operator<=>' when parsing the '<=>' token. 16890 if (DefKind.isComparison() && 16891 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16892 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16893 ? diag::warn_cxx17_compat_defaulted_comparison 16894 : diag::ext_defaulted_comparison); 16895 } 16896 16897 FD->setDefaulted(); 16898 FD->setExplicitlyDefaulted(); 16899 16900 // Defer checking functions that are defaulted in a dependent context. 16901 if (FD->isDependentContext()) 16902 return; 16903 16904 // Unset that we will have a body for this function. We might not, 16905 // if it turns out to be trivial, and we don't need this marking now 16906 // that we've marked it as defaulted. 16907 FD->setWillHaveBody(false); 16908 16909 // If this definition appears within the record, do the checking when 16910 // the record is complete. This is always the case for a defaulted 16911 // comparison. 16912 if (DefKind.isComparison()) 16913 return; 16914 auto *MD = cast<CXXMethodDecl>(FD); 16915 16916 const FunctionDecl *Primary = FD; 16917 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16918 // Ask the template instantiation pattern that actually had the 16919 // '= default' on it. 16920 Primary = Pattern; 16921 16922 // If the method was defaulted on its first declaration, we will have 16923 // already performed the checking in CheckCompletedCXXClass. Such a 16924 // declaration doesn't trigger an implicit definition. 16925 if (Primary->getCanonicalDecl()->isDefaulted()) 16926 return; 16927 16928 // FIXME: Once we support defining comparisons out of class, check for a 16929 // defaulted comparison here. 16930 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16931 MD->setInvalidDecl(); 16932 else 16933 DefineDefaultedFunction(*this, MD, DefaultLoc); 16934 } 16935 16936 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16937 for (Stmt *SubStmt : S->children()) { 16938 if (!SubStmt) 16939 continue; 16940 if (isa<ReturnStmt>(SubStmt)) 16941 Self.Diag(SubStmt->getBeginLoc(), 16942 diag::err_return_in_constructor_handler); 16943 if (!isa<Expr>(SubStmt)) 16944 SearchForReturnInStmt(Self, SubStmt); 16945 } 16946 } 16947 16948 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16949 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16950 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16951 SearchForReturnInStmt(*this, Handler); 16952 } 16953 } 16954 16955 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16956 const CXXMethodDecl *Old) { 16957 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16958 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16959 16960 if (OldFT->hasExtParameterInfos()) { 16961 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16962 // A parameter of the overriding method should be annotated with noescape 16963 // if the corresponding parameter of the overridden method is annotated. 16964 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16965 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16966 Diag(New->getParamDecl(I)->getLocation(), 16967 diag::warn_overriding_method_missing_noescape); 16968 Diag(Old->getParamDecl(I)->getLocation(), 16969 diag::note_overridden_marked_noescape); 16970 } 16971 } 16972 16973 // Virtual overrides must have the same code_seg. 16974 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16975 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16976 if ((NewCSA || OldCSA) && 16977 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16978 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16979 Diag(Old->getLocation(), diag::note_previous_declaration); 16980 return true; 16981 } 16982 16983 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16984 16985 // If the calling conventions match, everything is fine 16986 if (NewCC == OldCC) 16987 return false; 16988 16989 // If the calling conventions mismatch because the new function is static, 16990 // suppress the calling convention mismatch error; the error about static 16991 // function override (err_static_overrides_virtual from 16992 // Sema::CheckFunctionDeclaration) is more clear. 16993 if (New->getStorageClass() == SC_Static) 16994 return false; 16995 16996 Diag(New->getLocation(), 16997 diag::err_conflicting_overriding_cc_attributes) 16998 << New->getDeclName() << New->getType() << Old->getType(); 16999 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17000 return true; 17001 } 17002 17003 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17004 const CXXMethodDecl *Old) { 17005 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17006 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17007 17008 if (Context.hasSameType(NewTy, OldTy) || 17009 NewTy->isDependentType() || OldTy->isDependentType()) 17010 return false; 17011 17012 // Check if the return types are covariant 17013 QualType NewClassTy, OldClassTy; 17014 17015 /// Both types must be pointers or references to classes. 17016 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17017 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17018 NewClassTy = NewPT->getPointeeType(); 17019 OldClassTy = OldPT->getPointeeType(); 17020 } 17021 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17022 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17023 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17024 NewClassTy = NewRT->getPointeeType(); 17025 OldClassTy = OldRT->getPointeeType(); 17026 } 17027 } 17028 } 17029 17030 // The return types aren't either both pointers or references to a class type. 17031 if (NewClassTy.isNull()) { 17032 Diag(New->getLocation(), 17033 diag::err_different_return_type_for_overriding_virtual_function) 17034 << New->getDeclName() << NewTy << OldTy 17035 << New->getReturnTypeSourceRange(); 17036 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17037 << Old->getReturnTypeSourceRange(); 17038 17039 return true; 17040 } 17041 17042 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17043 // C++14 [class.virtual]p8: 17044 // If the class type in the covariant return type of D::f differs from 17045 // that of B::f, the class type in the return type of D::f shall be 17046 // complete at the point of declaration of D::f or shall be the class 17047 // type D. 17048 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17049 if (!RT->isBeingDefined() && 17050 RequireCompleteType(New->getLocation(), NewClassTy, 17051 diag::err_covariant_return_incomplete, 17052 New->getDeclName())) 17053 return true; 17054 } 17055 17056 // Check if the new class derives from the old class. 17057 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17058 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17059 << New->getDeclName() << NewTy << OldTy 17060 << New->getReturnTypeSourceRange(); 17061 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17062 << Old->getReturnTypeSourceRange(); 17063 return true; 17064 } 17065 17066 // Check if we the conversion from derived to base is valid. 17067 if (CheckDerivedToBaseConversion( 17068 NewClassTy, OldClassTy, 17069 diag::err_covariant_return_inaccessible_base, 17070 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17071 New->getLocation(), New->getReturnTypeSourceRange(), 17072 New->getDeclName(), nullptr)) { 17073 // FIXME: this note won't trigger for delayed access control 17074 // diagnostics, and it's impossible to get an undelayed error 17075 // here from access control during the original parse because 17076 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17077 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17078 << Old->getReturnTypeSourceRange(); 17079 return true; 17080 } 17081 } 17082 17083 // The qualifiers of the return types must be the same. 17084 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17085 Diag(New->getLocation(), 17086 diag::err_covariant_return_type_different_qualifications) 17087 << New->getDeclName() << NewTy << OldTy 17088 << New->getReturnTypeSourceRange(); 17089 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17090 << Old->getReturnTypeSourceRange(); 17091 return true; 17092 } 17093 17094 17095 // The new class type must have the same or less qualifiers as the old type. 17096 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17097 Diag(New->getLocation(), 17098 diag::err_covariant_return_type_class_type_more_qualified) 17099 << New->getDeclName() << NewTy << OldTy 17100 << New->getReturnTypeSourceRange(); 17101 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17102 << Old->getReturnTypeSourceRange(); 17103 return true; 17104 } 17105 17106 return false; 17107 } 17108 17109 /// Mark the given method pure. 17110 /// 17111 /// \param Method the method to be marked pure. 17112 /// 17113 /// \param InitRange the source range that covers the "0" initializer. 17114 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17115 SourceLocation EndLoc = InitRange.getEnd(); 17116 if (EndLoc.isValid()) 17117 Method->setRangeEnd(EndLoc); 17118 17119 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17120 Method->setPure(); 17121 return false; 17122 } 17123 17124 if (!Method->isInvalidDecl()) 17125 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17126 << Method->getDeclName() << InitRange; 17127 return true; 17128 } 17129 17130 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17131 if (D->getFriendObjectKind()) 17132 Diag(D->getLocation(), diag::err_pure_friend); 17133 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17134 CheckPureMethod(M, ZeroLoc); 17135 else 17136 Diag(D->getLocation(), diag::err_illegal_initializer); 17137 } 17138 17139 /// Determine whether the given declaration is a global variable or 17140 /// static data member. 17141 static bool isNonlocalVariable(const Decl *D) { 17142 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17143 return Var->hasGlobalStorage(); 17144 17145 return false; 17146 } 17147 17148 /// Invoked when we are about to parse an initializer for the declaration 17149 /// 'Dcl'. 17150 /// 17151 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17152 /// static data member of class X, names should be looked up in the scope of 17153 /// class X. If the declaration had a scope specifier, a scope will have 17154 /// been created and passed in for this purpose. Otherwise, S will be null. 17155 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17156 // If there is no declaration, there was an error parsing it. 17157 if (!D || D->isInvalidDecl()) 17158 return; 17159 17160 // We will always have a nested name specifier here, but this declaration 17161 // might not be out of line if the specifier names the current namespace: 17162 // extern int n; 17163 // int ::n = 0; 17164 if (S && D->isOutOfLine()) 17165 EnterDeclaratorContext(S, D->getDeclContext()); 17166 17167 // If we are parsing the initializer for a static data member, push a 17168 // new expression evaluation context that is associated with this static 17169 // data member. 17170 if (isNonlocalVariable(D)) 17171 PushExpressionEvaluationContext( 17172 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17173 } 17174 17175 /// Invoked after we are finished parsing an initializer for the declaration D. 17176 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17177 // If there is no declaration, there was an error parsing it. 17178 if (!D || D->isInvalidDecl()) 17179 return; 17180 17181 if (isNonlocalVariable(D)) 17182 PopExpressionEvaluationContext(); 17183 17184 if (S && D->isOutOfLine()) 17185 ExitDeclaratorContext(S); 17186 } 17187 17188 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17189 /// C++ if/switch/while/for statement. 17190 /// e.g: "if (int x = f()) {...}" 17191 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17192 // C++ 6.4p2: 17193 // The declarator shall not specify a function or an array. 17194 // The type-specifier-seq shall not contain typedef and shall not declare a 17195 // new class or enumeration. 17196 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17197 "Parser allowed 'typedef' as storage class of condition decl."); 17198 17199 Decl *Dcl = ActOnDeclarator(S, D); 17200 if (!Dcl) 17201 return true; 17202 17203 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17204 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17205 << D.getSourceRange(); 17206 return true; 17207 } 17208 17209 return Dcl; 17210 } 17211 17212 void Sema::LoadExternalVTableUses() { 17213 if (!ExternalSource) 17214 return; 17215 17216 SmallVector<ExternalVTableUse, 4> VTables; 17217 ExternalSource->ReadUsedVTables(VTables); 17218 SmallVector<VTableUse, 4> NewUses; 17219 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17220 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17221 = VTablesUsed.find(VTables[I].Record); 17222 // Even if a definition wasn't required before, it may be required now. 17223 if (Pos != VTablesUsed.end()) { 17224 if (!Pos->second && VTables[I].DefinitionRequired) 17225 Pos->second = true; 17226 continue; 17227 } 17228 17229 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17230 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17231 } 17232 17233 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17234 } 17235 17236 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17237 bool DefinitionRequired) { 17238 // Ignore any vtable uses in unevaluated operands or for classes that do 17239 // not have a vtable. 17240 if (!Class->isDynamicClass() || Class->isDependentContext() || 17241 CurContext->isDependentContext() || isUnevaluatedContext()) 17242 return; 17243 // Do not mark as used if compiling for the device outside of the target 17244 // region. 17245 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17246 !isInOpenMPDeclareTargetContext() && 17247 !isInOpenMPTargetExecutionDirective()) { 17248 if (!DefinitionRequired) 17249 MarkVirtualMembersReferenced(Loc, Class); 17250 return; 17251 } 17252 17253 // Try to insert this class into the map. 17254 LoadExternalVTableUses(); 17255 Class = Class->getCanonicalDecl(); 17256 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17257 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17258 if (!Pos.second) { 17259 // If we already had an entry, check to see if we are promoting this vtable 17260 // to require a definition. If so, we need to reappend to the VTableUses 17261 // list, since we may have already processed the first entry. 17262 if (DefinitionRequired && !Pos.first->second) { 17263 Pos.first->second = true; 17264 } else { 17265 // Otherwise, we can early exit. 17266 return; 17267 } 17268 } else { 17269 // The Microsoft ABI requires that we perform the destructor body 17270 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17271 // the deleting destructor is emitted with the vtable, not with the 17272 // destructor definition as in the Itanium ABI. 17273 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17274 CXXDestructorDecl *DD = Class->getDestructor(); 17275 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17276 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17277 // If this is an out-of-line declaration, marking it referenced will 17278 // not do anything. Manually call CheckDestructor to look up operator 17279 // delete(). 17280 ContextRAII SavedContext(*this, DD); 17281 CheckDestructor(DD); 17282 } else { 17283 MarkFunctionReferenced(Loc, Class->getDestructor()); 17284 } 17285 } 17286 } 17287 } 17288 17289 // Local classes need to have their virtual members marked 17290 // immediately. For all other classes, we mark their virtual members 17291 // at the end of the translation unit. 17292 if (Class->isLocalClass()) 17293 MarkVirtualMembersReferenced(Loc, Class); 17294 else 17295 VTableUses.push_back(std::make_pair(Class, Loc)); 17296 } 17297 17298 bool Sema::DefineUsedVTables() { 17299 LoadExternalVTableUses(); 17300 if (VTableUses.empty()) 17301 return false; 17302 17303 // Note: The VTableUses vector could grow as a result of marking 17304 // the members of a class as "used", so we check the size each 17305 // time through the loop and prefer indices (which are stable) to 17306 // iterators (which are not). 17307 bool DefinedAnything = false; 17308 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17309 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17310 if (!Class) 17311 continue; 17312 TemplateSpecializationKind ClassTSK = 17313 Class->getTemplateSpecializationKind(); 17314 17315 SourceLocation Loc = VTableUses[I].second; 17316 17317 bool DefineVTable = true; 17318 17319 // If this class has a key function, but that key function is 17320 // defined in another translation unit, we don't need to emit the 17321 // vtable even though we're using it. 17322 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17323 if (KeyFunction && !KeyFunction->hasBody()) { 17324 // The key function is in another translation unit. 17325 DefineVTable = false; 17326 TemplateSpecializationKind TSK = 17327 KeyFunction->getTemplateSpecializationKind(); 17328 assert(TSK != TSK_ExplicitInstantiationDefinition && 17329 TSK != TSK_ImplicitInstantiation && 17330 "Instantiations don't have key functions"); 17331 (void)TSK; 17332 } else if (!KeyFunction) { 17333 // If we have a class with no key function that is the subject 17334 // of an explicit instantiation declaration, suppress the 17335 // vtable; it will live with the explicit instantiation 17336 // definition. 17337 bool IsExplicitInstantiationDeclaration = 17338 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17339 for (auto R : Class->redecls()) { 17340 TemplateSpecializationKind TSK 17341 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17342 if (TSK == TSK_ExplicitInstantiationDeclaration) 17343 IsExplicitInstantiationDeclaration = true; 17344 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17345 IsExplicitInstantiationDeclaration = false; 17346 break; 17347 } 17348 } 17349 17350 if (IsExplicitInstantiationDeclaration) 17351 DefineVTable = false; 17352 } 17353 17354 // The exception specifications for all virtual members may be needed even 17355 // if we are not providing an authoritative form of the vtable in this TU. 17356 // We may choose to emit it available_externally anyway. 17357 if (!DefineVTable) { 17358 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17359 continue; 17360 } 17361 17362 // Mark all of the virtual members of this class as referenced, so 17363 // that we can build a vtable. Then, tell the AST consumer that a 17364 // vtable for this class is required. 17365 DefinedAnything = true; 17366 MarkVirtualMembersReferenced(Loc, Class); 17367 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17368 if (VTablesUsed[Canonical]) 17369 Consumer.HandleVTable(Class); 17370 17371 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17372 // no key function or the key function is inlined. Don't warn in C++ ABIs 17373 // that lack key functions, since the user won't be able to make one. 17374 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17375 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17376 const FunctionDecl *KeyFunctionDef = nullptr; 17377 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17378 KeyFunctionDef->isInlined())) { 17379 Diag(Class->getLocation(), 17380 ClassTSK == TSK_ExplicitInstantiationDefinition 17381 ? diag::warn_weak_template_vtable 17382 : diag::warn_weak_vtable) 17383 << Class; 17384 } 17385 } 17386 } 17387 VTableUses.clear(); 17388 17389 return DefinedAnything; 17390 } 17391 17392 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17393 const CXXRecordDecl *RD) { 17394 for (const auto *I : RD->methods()) 17395 if (I->isVirtual() && !I->isPure()) 17396 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17397 } 17398 17399 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17400 const CXXRecordDecl *RD, 17401 bool ConstexprOnly) { 17402 // Mark all functions which will appear in RD's vtable as used. 17403 CXXFinalOverriderMap FinalOverriders; 17404 RD->getFinalOverriders(FinalOverriders); 17405 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17406 E = FinalOverriders.end(); 17407 I != E; ++I) { 17408 for (OverridingMethods::const_iterator OI = I->second.begin(), 17409 OE = I->second.end(); 17410 OI != OE; ++OI) { 17411 assert(OI->second.size() > 0 && "no final overrider"); 17412 CXXMethodDecl *Overrider = OI->second.front().Method; 17413 17414 // C++ [basic.def.odr]p2: 17415 // [...] A virtual member function is used if it is not pure. [...] 17416 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17417 MarkFunctionReferenced(Loc, Overrider); 17418 } 17419 } 17420 17421 // Only classes that have virtual bases need a VTT. 17422 if (RD->getNumVBases() == 0) 17423 return; 17424 17425 for (const auto &I : RD->bases()) { 17426 const auto *Base = 17427 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17428 if (Base->getNumVBases() == 0) 17429 continue; 17430 MarkVirtualMembersReferenced(Loc, Base); 17431 } 17432 } 17433 17434 /// SetIvarInitializers - This routine builds initialization ASTs for the 17435 /// Objective-C implementation whose ivars need be initialized. 17436 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17437 if (!getLangOpts().CPlusPlus) 17438 return; 17439 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17440 SmallVector<ObjCIvarDecl*, 8> ivars; 17441 CollectIvarsToConstructOrDestruct(OID, ivars); 17442 if (ivars.empty()) 17443 return; 17444 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17445 for (unsigned i = 0; i < ivars.size(); i++) { 17446 FieldDecl *Field = ivars[i]; 17447 if (Field->isInvalidDecl()) 17448 continue; 17449 17450 CXXCtorInitializer *Member; 17451 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17452 InitializationKind InitKind = 17453 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17454 17455 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17456 ExprResult MemberInit = 17457 InitSeq.Perform(*this, InitEntity, InitKind, None); 17458 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17459 // Note, MemberInit could actually come back empty if no initialization 17460 // is required (e.g., because it would call a trivial default constructor) 17461 if (!MemberInit.get() || MemberInit.isInvalid()) 17462 continue; 17463 17464 Member = 17465 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17466 SourceLocation(), 17467 MemberInit.getAs<Expr>(), 17468 SourceLocation()); 17469 AllToInit.push_back(Member); 17470 17471 // Be sure that the destructor is accessible and is marked as referenced. 17472 if (const RecordType *RecordTy = 17473 Context.getBaseElementType(Field->getType()) 17474 ->getAs<RecordType>()) { 17475 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17476 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17477 MarkFunctionReferenced(Field->getLocation(), Destructor); 17478 CheckDestructorAccess(Field->getLocation(), Destructor, 17479 PDiag(diag::err_access_dtor_ivar) 17480 << Context.getBaseElementType(Field->getType())); 17481 } 17482 } 17483 } 17484 ObjCImplementation->setIvarInitializers(Context, 17485 AllToInit.data(), AllToInit.size()); 17486 } 17487 } 17488 17489 static 17490 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17491 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17492 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17493 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17494 Sema &S) { 17495 if (Ctor->isInvalidDecl()) 17496 return; 17497 17498 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17499 17500 // Target may not be determinable yet, for instance if this is a dependent 17501 // call in an uninstantiated template. 17502 if (Target) { 17503 const FunctionDecl *FNTarget = nullptr; 17504 (void)Target->hasBody(FNTarget); 17505 Target = const_cast<CXXConstructorDecl*>( 17506 cast_or_null<CXXConstructorDecl>(FNTarget)); 17507 } 17508 17509 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17510 // Avoid dereferencing a null pointer here. 17511 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17512 17513 if (!Current.insert(Canonical).second) 17514 return; 17515 17516 // We know that beyond here, we aren't chaining into a cycle. 17517 if (!Target || !Target->isDelegatingConstructor() || 17518 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17519 Valid.insert(Current.begin(), Current.end()); 17520 Current.clear(); 17521 // We've hit a cycle. 17522 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17523 Current.count(TCanonical)) { 17524 // If we haven't diagnosed this cycle yet, do so now. 17525 if (!Invalid.count(TCanonical)) { 17526 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17527 diag::warn_delegating_ctor_cycle) 17528 << Ctor; 17529 17530 // Don't add a note for a function delegating directly to itself. 17531 if (TCanonical != Canonical) 17532 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17533 17534 CXXConstructorDecl *C = Target; 17535 while (C->getCanonicalDecl() != Canonical) { 17536 const FunctionDecl *FNTarget = nullptr; 17537 (void)C->getTargetConstructor()->hasBody(FNTarget); 17538 assert(FNTarget && "Ctor cycle through bodiless function"); 17539 17540 C = const_cast<CXXConstructorDecl*>( 17541 cast<CXXConstructorDecl>(FNTarget)); 17542 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17543 } 17544 } 17545 17546 Invalid.insert(Current.begin(), Current.end()); 17547 Current.clear(); 17548 } else { 17549 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17550 } 17551 } 17552 17553 17554 void Sema::CheckDelegatingCtorCycles() { 17555 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17556 17557 for (DelegatingCtorDeclsType::iterator 17558 I = DelegatingCtorDecls.begin(ExternalSource), 17559 E = DelegatingCtorDecls.end(); 17560 I != E; ++I) 17561 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17562 17563 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17564 (*CI)->setInvalidDecl(); 17565 } 17566 17567 namespace { 17568 /// AST visitor that finds references to the 'this' expression. 17569 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17570 Sema &S; 17571 17572 public: 17573 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17574 17575 bool VisitCXXThisExpr(CXXThisExpr *E) { 17576 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17577 << E->isImplicit(); 17578 return false; 17579 } 17580 }; 17581 } 17582 17583 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17584 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17585 if (!TSInfo) 17586 return false; 17587 17588 TypeLoc TL = TSInfo->getTypeLoc(); 17589 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17590 if (!ProtoTL) 17591 return false; 17592 17593 // C++11 [expr.prim.general]p3: 17594 // [The expression this] shall not appear before the optional 17595 // cv-qualifier-seq and it shall not appear within the declaration of a 17596 // static member function (although its type and value category are defined 17597 // within a static member function as they are within a non-static member 17598 // function). [ Note: this is because declaration matching does not occur 17599 // until the complete declarator is known. - end note ] 17600 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17601 FindCXXThisExpr Finder(*this); 17602 17603 // If the return type came after the cv-qualifier-seq, check it now. 17604 if (Proto->hasTrailingReturn() && 17605 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17606 return true; 17607 17608 // Check the exception specification. 17609 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17610 return true; 17611 17612 // Check the trailing requires clause 17613 if (Expr *E = Method->getTrailingRequiresClause()) 17614 if (!Finder.TraverseStmt(E)) 17615 return true; 17616 17617 return checkThisInStaticMemberFunctionAttributes(Method); 17618 } 17619 17620 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17621 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17622 if (!TSInfo) 17623 return false; 17624 17625 TypeLoc TL = TSInfo->getTypeLoc(); 17626 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17627 if (!ProtoTL) 17628 return false; 17629 17630 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17631 FindCXXThisExpr Finder(*this); 17632 17633 switch (Proto->getExceptionSpecType()) { 17634 case EST_Unparsed: 17635 case EST_Uninstantiated: 17636 case EST_Unevaluated: 17637 case EST_BasicNoexcept: 17638 case EST_NoThrow: 17639 case EST_DynamicNone: 17640 case EST_MSAny: 17641 case EST_None: 17642 break; 17643 17644 case EST_DependentNoexcept: 17645 case EST_NoexceptFalse: 17646 case EST_NoexceptTrue: 17647 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17648 return true; 17649 LLVM_FALLTHROUGH; 17650 17651 case EST_Dynamic: 17652 for (const auto &E : Proto->exceptions()) { 17653 if (!Finder.TraverseType(E)) 17654 return true; 17655 } 17656 break; 17657 } 17658 17659 return false; 17660 } 17661 17662 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17663 FindCXXThisExpr Finder(*this); 17664 17665 // Check attributes. 17666 for (const auto *A : Method->attrs()) { 17667 // FIXME: This should be emitted by tblgen. 17668 Expr *Arg = nullptr; 17669 ArrayRef<Expr *> Args; 17670 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17671 Arg = G->getArg(); 17672 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17673 Arg = G->getArg(); 17674 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17675 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17676 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17677 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17678 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17679 Arg = ETLF->getSuccessValue(); 17680 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17681 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17682 Arg = STLF->getSuccessValue(); 17683 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17684 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17685 Arg = LR->getArg(); 17686 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17687 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17688 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17689 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17690 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17691 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17692 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17693 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17694 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17695 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17696 17697 if (Arg && !Finder.TraverseStmt(Arg)) 17698 return true; 17699 17700 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17701 if (!Finder.TraverseStmt(Args[I])) 17702 return true; 17703 } 17704 } 17705 17706 return false; 17707 } 17708 17709 void Sema::checkExceptionSpecification( 17710 bool IsTopLevel, ExceptionSpecificationType EST, 17711 ArrayRef<ParsedType> DynamicExceptions, 17712 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17713 SmallVectorImpl<QualType> &Exceptions, 17714 FunctionProtoType::ExceptionSpecInfo &ESI) { 17715 Exceptions.clear(); 17716 ESI.Type = EST; 17717 if (EST == EST_Dynamic) { 17718 Exceptions.reserve(DynamicExceptions.size()); 17719 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17720 // FIXME: Preserve type source info. 17721 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17722 17723 if (IsTopLevel) { 17724 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17725 collectUnexpandedParameterPacks(ET, Unexpanded); 17726 if (!Unexpanded.empty()) { 17727 DiagnoseUnexpandedParameterPacks( 17728 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17729 Unexpanded); 17730 continue; 17731 } 17732 } 17733 17734 // Check that the type is valid for an exception spec, and 17735 // drop it if not. 17736 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17737 Exceptions.push_back(ET); 17738 } 17739 ESI.Exceptions = Exceptions; 17740 return; 17741 } 17742 17743 if (isComputedNoexcept(EST)) { 17744 assert((NoexceptExpr->isTypeDependent() || 17745 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17746 Context.BoolTy) && 17747 "Parser should have made sure that the expression is boolean"); 17748 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17749 ESI.Type = EST_BasicNoexcept; 17750 return; 17751 } 17752 17753 ESI.NoexceptExpr = NoexceptExpr; 17754 return; 17755 } 17756 } 17757 17758 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17759 ExceptionSpecificationType EST, 17760 SourceRange SpecificationRange, 17761 ArrayRef<ParsedType> DynamicExceptions, 17762 ArrayRef<SourceRange> DynamicExceptionRanges, 17763 Expr *NoexceptExpr) { 17764 if (!MethodD) 17765 return; 17766 17767 // Dig out the method we're referring to. 17768 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17769 MethodD = FunTmpl->getTemplatedDecl(); 17770 17771 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17772 if (!Method) 17773 return; 17774 17775 // Check the exception specification. 17776 llvm::SmallVector<QualType, 4> Exceptions; 17777 FunctionProtoType::ExceptionSpecInfo ESI; 17778 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17779 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17780 ESI); 17781 17782 // Update the exception specification on the function type. 17783 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17784 17785 if (Method->isStatic()) 17786 checkThisInStaticMemberFunctionExceptionSpec(Method); 17787 17788 if (Method->isVirtual()) { 17789 // Check overrides, which we previously had to delay. 17790 for (const CXXMethodDecl *O : Method->overridden_methods()) 17791 CheckOverridingFunctionExceptionSpec(Method, O); 17792 } 17793 } 17794 17795 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17796 /// 17797 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17798 SourceLocation DeclStart, Declarator &D, 17799 Expr *BitWidth, 17800 InClassInitStyle InitStyle, 17801 AccessSpecifier AS, 17802 const ParsedAttr &MSPropertyAttr) { 17803 IdentifierInfo *II = D.getIdentifier(); 17804 if (!II) { 17805 Diag(DeclStart, diag::err_anonymous_property); 17806 return nullptr; 17807 } 17808 SourceLocation Loc = D.getIdentifierLoc(); 17809 17810 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17811 QualType T = TInfo->getType(); 17812 if (getLangOpts().CPlusPlus) { 17813 CheckExtraCXXDefaultArguments(D); 17814 17815 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17816 UPPC_DataMemberType)) { 17817 D.setInvalidType(); 17818 T = Context.IntTy; 17819 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17820 } 17821 } 17822 17823 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17824 17825 if (D.getDeclSpec().isInlineSpecified()) 17826 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17827 << getLangOpts().CPlusPlus17; 17828 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17829 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17830 diag::err_invalid_thread) 17831 << DeclSpec::getSpecifierName(TSCS); 17832 17833 // Check to see if this name was declared as a member previously 17834 NamedDecl *PrevDecl = nullptr; 17835 LookupResult Previous(*this, II, Loc, LookupMemberName, 17836 ForVisibleRedeclaration); 17837 LookupName(Previous, S); 17838 switch (Previous.getResultKind()) { 17839 case LookupResult::Found: 17840 case LookupResult::FoundUnresolvedValue: 17841 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17842 break; 17843 17844 case LookupResult::FoundOverloaded: 17845 PrevDecl = Previous.getRepresentativeDecl(); 17846 break; 17847 17848 case LookupResult::NotFound: 17849 case LookupResult::NotFoundInCurrentInstantiation: 17850 case LookupResult::Ambiguous: 17851 break; 17852 } 17853 17854 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17855 // Maybe we will complain about the shadowed template parameter. 17856 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17857 // Just pretend that we didn't see the previous declaration. 17858 PrevDecl = nullptr; 17859 } 17860 17861 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17862 PrevDecl = nullptr; 17863 17864 SourceLocation TSSL = D.getBeginLoc(); 17865 MSPropertyDecl *NewPD = 17866 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17867 MSPropertyAttr.getPropertyDataGetter(), 17868 MSPropertyAttr.getPropertyDataSetter()); 17869 ProcessDeclAttributes(TUScope, NewPD, D); 17870 NewPD->setAccess(AS); 17871 17872 if (NewPD->isInvalidDecl()) 17873 Record->setInvalidDecl(); 17874 17875 if (D.getDeclSpec().isModulePrivateSpecified()) 17876 NewPD->setModulePrivate(); 17877 17878 if (NewPD->isInvalidDecl() && PrevDecl) { 17879 // Don't introduce NewFD into scope; there's already something 17880 // with the same name in the same scope. 17881 } else if (II) { 17882 PushOnScopeChains(NewPD, S); 17883 } else 17884 Record->addDecl(NewPD); 17885 17886 return NewPD; 17887 } 17888 17889 void Sema::ActOnStartFunctionDeclarationDeclarator( 17890 Declarator &Declarator, unsigned TemplateParameterDepth) { 17891 auto &Info = InventedParameterInfos.emplace_back(); 17892 TemplateParameterList *ExplicitParams = nullptr; 17893 ArrayRef<TemplateParameterList *> ExplicitLists = 17894 Declarator.getTemplateParameterLists(); 17895 if (!ExplicitLists.empty()) { 17896 bool IsMemberSpecialization, IsInvalid; 17897 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17898 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17899 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17900 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17901 /*SuppressDiagnostic=*/true); 17902 } 17903 if (ExplicitParams) { 17904 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17905 for (NamedDecl *Param : *ExplicitParams) 17906 Info.TemplateParams.push_back(Param); 17907 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17908 } else { 17909 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17910 Info.NumExplicitTemplateParams = 0; 17911 } 17912 } 17913 17914 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17915 auto &FSI = InventedParameterInfos.back(); 17916 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17917 if (FSI.NumExplicitTemplateParams != 0) { 17918 TemplateParameterList *ExplicitParams = 17919 Declarator.getTemplateParameterLists().back(); 17920 Declarator.setInventedTemplateParameterList( 17921 TemplateParameterList::Create( 17922 Context, ExplicitParams->getTemplateLoc(), 17923 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17924 ExplicitParams->getRAngleLoc(), 17925 ExplicitParams->getRequiresClause())); 17926 } else { 17927 Declarator.setInventedTemplateParameterList( 17928 TemplateParameterList::Create( 17929 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17930 SourceLocation(), /*RequiresClause=*/nullptr)); 17931 } 17932 } 17933 InventedParameterInfos.pop_back(); 17934 } 17935