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/Specifiers.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "clang/Sema/SemaInternal.h" 41 #include "clang/Sema/Template.h" 42 #include "llvm/ADT/ScopeExit.h" 43 #include "llvm/ADT/SmallString.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/StringExtras.h" 46 #include <map> 47 #include <set> 48 49 using namespace clang; 50 51 //===----------------------------------------------------------------------===// 52 // CheckDefaultArgumentVisitor 53 //===----------------------------------------------------------------------===// 54 55 namespace { 56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 57 /// the default argument of a parameter to determine whether it 58 /// contains any ill-formed subexpressions. For example, this will 59 /// diagnose the use of local variables or parameters within the 60 /// default argument expression. 61 class CheckDefaultArgumentVisitor 62 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 63 Sema &S; 64 const Expr *DefaultArg; 65 66 public: 67 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 68 : S(S), DefaultArg(DefaultArg) {} 69 70 bool VisitExpr(const Expr *Node); 71 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 72 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 73 bool VisitLambdaExpr(const LambdaExpr *Lambda); 74 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 75 }; 76 77 /// VisitExpr - Visit all of the children of this expression. 78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 79 bool IsInvalid = false; 80 for (const Stmt *SubStmt : Node->children()) 81 IsInvalid |= Visit(SubStmt); 82 return IsInvalid; 83 } 84 85 /// VisitDeclRefExpr - Visit a reference to a declaration, to 86 /// determine whether this declaration can be used in the default 87 /// argument expression. 88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 89 const NamedDecl *Decl = DRE->getDecl(); 90 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p9: 92 // [...] parameters of a function shall not be used in default 93 // argument expressions, even if they are not evaluated. [...] 94 // 95 // C++17 [dcl.fct.default]p9 (by CWG 2082): 96 // [...] A parameter shall not appear as a potentially-evaluated 97 // expression in a default argument. [...] 98 // 99 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 100 return S.Diag(DRE->getBeginLoc(), 101 diag::err_param_default_argument_references_param) 102 << Param->getDeclName() << DefaultArg->getSourceRange(); 103 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 104 // C++ [dcl.fct.default]p7: 105 // Local variables shall not be used in default argument 106 // expressions. 107 // 108 // C++17 [dcl.fct.default]p7 (by CWG 2082): 109 // A local variable shall not appear as a potentially-evaluated 110 // expression in a default argument. 111 // 112 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 113 // Note: A local variable cannot be odr-used (6.3) in a default argument. 114 // 115 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 116 return S.Diag(DRE->getBeginLoc(), 117 diag::err_param_default_argument_references_local) 118 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 119 } 120 121 return false; 122 } 123 124 /// VisitCXXThisExpr - Visit a C++ "this" expression. 125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 126 // C++ [dcl.fct.default]p8: 127 // The keyword this shall not be used in a default argument of a 128 // member function. 129 return S.Diag(ThisE->getBeginLoc(), 130 diag::err_param_default_argument_references_this) 131 << ThisE->getSourceRange(); 132 } 133 134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 135 const PseudoObjectExpr *POE) { 136 bool Invalid = false; 137 for (const Expr *E : POE->semantics()) { 138 // Look through bindings. 139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 140 E = OVE->getSourceExpr(); 141 assert(E && "pseudo-object binding without source expression?"); 142 } 143 144 Invalid |= Visit(E); 145 } 146 return Invalid; 147 } 148 149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 150 // C++11 [expr.lambda.prim]p13: 151 // A lambda-expression appearing in a default argument shall not 152 // implicitly or explicitly capture any entity. 153 if (Lambda->capture_begin() == Lambda->capture_end()) 154 return false; 155 156 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 157 } 158 } // namespace 159 160 void 161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 162 const CXXMethodDecl *Method) { 163 // If we have an MSAny spec already, don't bother. 164 if (!Method || ComputedEST == EST_MSAny) 165 return; 166 167 const FunctionProtoType *Proto 168 = Method->getType()->getAs<FunctionProtoType>(); 169 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 170 if (!Proto) 171 return; 172 173 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 174 175 // If we have a throw-all spec at this point, ignore the function. 176 if (ComputedEST == EST_None) 177 return; 178 179 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 180 EST = EST_BasicNoexcept; 181 182 switch (EST) { 183 case EST_Unparsed: 184 case EST_Uninstantiated: 185 case EST_Unevaluated: 186 llvm_unreachable("should not see unresolved exception specs here"); 187 188 // If this function can throw any exceptions, make a note of that. 189 case EST_MSAny: 190 case EST_None: 191 // FIXME: Whichever we see last of MSAny and None determines our result. 192 // We should make a consistent, order-independent choice here. 193 ClearExceptions(); 194 ComputedEST = EST; 195 return; 196 case EST_NoexceptFalse: 197 ClearExceptions(); 198 ComputedEST = EST_None; 199 return; 200 // FIXME: If the call to this decl is using any of its default arguments, we 201 // need to search them for potentially-throwing calls. 202 // If this function has a basic noexcept, it doesn't affect the outcome. 203 case EST_BasicNoexcept: 204 case EST_NoexceptTrue: 205 case EST_NoThrow: 206 return; 207 // If we're still at noexcept(true) and there's a throw() callee, 208 // change to that specification. 209 case EST_DynamicNone: 210 if (ComputedEST == EST_BasicNoexcept) 211 ComputedEST = EST_DynamicNone; 212 return; 213 case EST_DependentNoexcept: 214 llvm_unreachable( 215 "should not generate implicit declarations for dependent cases"); 216 case EST_Dynamic: 217 break; 218 } 219 assert(EST == EST_Dynamic && "EST case not considered earlier."); 220 assert(ComputedEST != EST_None && 221 "Shouldn't collect exceptions when throw-all is guaranteed."); 222 ComputedEST = EST_Dynamic; 223 // Record the exceptions in this function's exception specification. 224 for (const auto &E : Proto->exceptions()) 225 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 226 Exceptions.push_back(E); 227 } 228 229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 230 if (!S || ComputedEST == EST_MSAny) 231 return; 232 233 // FIXME: 234 // 235 // C++0x [except.spec]p14: 236 // [An] implicit exception-specification specifies the type-id T if and 237 // only if T is allowed by the exception-specification of a function directly 238 // invoked by f's implicit definition; f shall allow all exceptions if any 239 // function it directly invokes allows all exceptions, and f shall allow no 240 // exceptions if every function it directly invokes allows no exceptions. 241 // 242 // Note in particular that if an implicit exception-specification is generated 243 // for a function containing a throw-expression, that specification can still 244 // be noexcept(true). 245 // 246 // Note also that 'directly invoked' is not defined in the standard, and there 247 // is no indication that we should only consider potentially-evaluated calls. 248 // 249 // Ultimately we should implement the intent of the standard: the exception 250 // specification should be the set of exceptions which can be thrown by the 251 // implicit definition. For now, we assume that any non-nothrow expression can 252 // throw any exception. 253 254 if (Self->canThrow(S)) 255 ComputedEST = EST_None; 256 } 257 258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new (Context) OpaqueValueExpr( 385 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 386 } 387 388 /// CheckExtraCXXDefaultArguments - Check for any extra default 389 /// arguments in the declarator, which is not a function declaration 390 /// or definition and therefore is not permitted to have default 391 /// arguments. This routine should be invoked for every declarator 392 /// that is not a function declaration or definition. 393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 394 // C++ [dcl.fct.default]p3 395 // A default argument expression shall be specified only in the 396 // parameter-declaration-clause of a function declaration or in a 397 // template-parameter (14.1). It shall not be specified for a 398 // parameter pack. If it is specified in a 399 // parameter-declaration-clause, it shall not occur within a 400 // declarator or abstract-declarator of a parameter-declaration. 401 bool MightBeFunction = D.isFunctionDeclarationContext(); 402 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 403 DeclaratorChunk &chunk = D.getTypeObject(i); 404 if (chunk.Kind == DeclaratorChunk::Function) { 405 if (MightBeFunction) { 406 // This is a function declaration. It can have default arguments, but 407 // keep looking in case its return type is a function type with default 408 // arguments. 409 MightBeFunction = false; 410 continue; 411 } 412 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 413 ++argIdx) { 414 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 415 if (Param->hasUnparsedDefaultArg()) { 416 std::unique_ptr<CachedTokens> Toks = 417 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 418 SourceRange SR; 419 if (Toks->size() > 1) 420 SR = SourceRange((*Toks)[1].getLocation(), 421 Toks->back().getLocation()); 422 else 423 SR = UnparsedDefaultArgLocs[Param]; 424 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 425 << SR; 426 } else if (Param->getDefaultArg()) { 427 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 428 << Param->getDefaultArg()->getSourceRange(); 429 Param->setDefaultArg(nullptr); 430 } 431 } 432 } else if (chunk.Kind != DeclaratorChunk::Paren) { 433 MightBeFunction = false; 434 } 435 } 436 } 437 438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 439 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) { 440 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 441 }); 442 } 443 444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 445 /// function, once we already know that they have the same 446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 447 /// error, false otherwise. 448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 449 Scope *S) { 450 bool Invalid = false; 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 459 // Find the previous declaration for the purpose of default arguments. 460 FunctionDecl *PrevForDefaultArgs = Old; 461 for (/**/; PrevForDefaultArgs; 462 // Don't bother looking back past the latest decl if this is a local 463 // extern declaration; nothing else could work. 464 PrevForDefaultArgs = New->isLocalExternDecl() 465 ? nullptr 466 : PrevForDefaultArgs->getPreviousDecl()) { 467 // Ignore hidden declarations. 468 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 469 continue; 470 471 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 472 !New->isCXXClassMember()) { 473 // Ignore default arguments of old decl if they are not in 474 // the same scope and this is not an out-of-line definition of 475 // a member function. 476 continue; 477 } 478 479 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 480 // If only one of these is a local function declaration, then they are 481 // declared in different scopes, even though isDeclInScope may think 482 // they're in the same scope. (If both are local, the scope check is 483 // sufficient, and if neither is local, then they are in the same scope.) 484 continue; 485 } 486 487 // We found the right previous declaration. 488 break; 489 } 490 491 // C++ [dcl.fct.default]p4: 492 // For non-template functions, default arguments can be added in 493 // later declarations of a function in the same 494 // scope. Declarations in different scopes have completely 495 // distinct sets of default arguments. That is, declarations in 496 // inner scopes do not acquire default arguments from 497 // declarations in outer scopes, and vice versa. In a given 498 // function declaration, all parameters subsequent to a 499 // parameter with a default argument shall have default 500 // arguments supplied in this or previous declarations. A 501 // default argument shall not be redefined by a later 502 // declaration (not even to the same value). 503 // 504 // C++ [dcl.fct.default]p6: 505 // Except for member functions of class templates, the default arguments 506 // in a member function definition that appears outside of the class 507 // definition are added to the set of default arguments provided by the 508 // member function declaration in the class definition. 509 for (unsigned p = 0, NumParams = PrevForDefaultArgs 510 ? PrevForDefaultArgs->getNumParams() 511 : 0; 512 p < NumParams; ++p) { 513 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 514 ParmVarDecl *NewParam = New->getParamDecl(p); 515 516 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 517 bool NewParamHasDfl = NewParam->hasDefaultArg(); 518 519 if (OldParamHasDfl && NewParamHasDfl) { 520 unsigned DiagDefaultParamID = 521 diag::err_param_default_argument_redefinition; 522 523 // MSVC accepts that default parameters be redefined for member functions 524 // of template class. The new default parameter's value is ignored. 525 Invalid = true; 526 if (getLangOpts().MicrosoftExt) { 527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 528 if (MD && MD->getParent()->getDescribedClassTemplate()) { 529 // Merge the old default argument into the new parameter. 530 NewParam->setHasInheritedDefaultArg(); 531 if (OldParam->hasUninstantiatedDefaultArg()) 532 NewParam->setUninstantiatedDefaultArg( 533 OldParam->getUninstantiatedDefaultArg()); 534 else 535 NewParam->setDefaultArg(OldParam->getInit()); 536 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 537 Invalid = false; 538 } 539 } 540 541 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 542 // hint here. Alternatively, we could walk the type-source information 543 // for NewParam to find the last source location in the type... but it 544 // isn't worth the effort right now. This is the kind of test case that 545 // is hard to get right: 546 // int f(int); 547 // void g(int (*fp)(int) = f); 548 // void g(int (*fp)(int) = &f); 549 Diag(NewParam->getLocation(), DiagDefaultParamID) 550 << NewParam->getDefaultArgRange(); 551 552 // Look for the function declaration where the default argument was 553 // actually written, which may be a declaration prior to Old. 554 for (auto Older = PrevForDefaultArgs; 555 OldParam->hasInheritedDefaultArg(); /**/) { 556 Older = Older->getPreviousDecl(); 557 OldParam = Older->getParamDecl(p); 558 } 559 560 Diag(OldParam->getLocation(), diag::note_previous_definition) 561 << OldParam->getDefaultArgRange(); 562 } else if (OldParamHasDfl) { 563 // Merge the old default argument into the new parameter unless the new 564 // function is a friend declaration in a template class. In the latter 565 // case the default arguments will be inherited when the friend 566 // declaration will be instantiated. 567 if (New->getFriendObjectKind() == Decl::FOK_None || 568 !New->getLexicalDeclContext()->isDependentContext()) { 569 // It's important to use getInit() here; getDefaultArg() 570 // strips off any top-level ExprWithCleanups. 571 NewParam->setHasInheritedDefaultArg(); 572 if (OldParam->hasUnparsedDefaultArg()) 573 NewParam->setUnparsedDefaultArg(); 574 else if (OldParam->hasUninstantiatedDefaultArg()) 575 NewParam->setUninstantiatedDefaultArg( 576 OldParam->getUninstantiatedDefaultArg()); 577 else 578 NewParam->setDefaultArg(OldParam->getInit()); 579 } 580 } else if (NewParamHasDfl) { 581 if (New->getDescribedFunctionTemplate()) { 582 // Paragraph 4, quoted above, only applies to non-template functions. 583 Diag(NewParam->getLocation(), 584 diag::err_param_default_argument_template_redecl) 585 << NewParam->getDefaultArgRange(); 586 Diag(PrevForDefaultArgs->getLocation(), 587 diag::note_template_prev_declaration) 588 << false; 589 } else if (New->getTemplateSpecializationKind() 590 != TSK_ImplicitInstantiation && 591 New->getTemplateSpecializationKind() != TSK_Undeclared) { 592 // C++ [temp.expr.spec]p21: 593 // Default function arguments shall not be specified in a declaration 594 // or a definition for one of the following explicit specializations: 595 // - the explicit specialization of a function template; 596 // - the explicit specialization of a member function template; 597 // - the explicit specialization of a member function of a class 598 // template where the class template specialization to which the 599 // member function specialization belongs is implicitly 600 // instantiated. 601 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 602 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 603 << New->getDeclName() 604 << NewParam->getDefaultArgRange(); 605 } else if (New->getDeclContext()->isDependentContext()) { 606 // C++ [dcl.fct.default]p6 (DR217): 607 // Default arguments for a member function of a class template shall 608 // be specified on the initial declaration of the member function 609 // within the class template. 610 // 611 // Reading the tea leaves a bit in DR217 and its reference to DR205 612 // leads me to the conclusion that one cannot add default function 613 // arguments for an out-of-line definition of a member function of a 614 // dependent type. 615 int WhichKind = 2; 616 if (CXXRecordDecl *Record 617 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 618 if (Record->getDescribedClassTemplate()) 619 WhichKind = 0; 620 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 621 WhichKind = 1; 622 else 623 WhichKind = 2; 624 } 625 626 Diag(NewParam->getLocation(), 627 diag::err_param_default_argument_member_template_redecl) 628 << WhichKind 629 << NewParam->getDefaultArgRange(); 630 } 631 } 632 } 633 634 // DR1344: If a default argument is added outside a class definition and that 635 // default argument makes the function a special member function, the program 636 // is ill-formed. This can only happen for constructors. 637 if (isa<CXXConstructorDecl>(New) && 638 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 639 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 640 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 641 if (NewSM != OldSM) { 642 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 643 assert(NewParam->hasDefaultArg()); 644 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 645 << NewParam->getDefaultArgRange() << NewSM; 646 Diag(Old->getLocation(), diag::note_previous_declaration); 647 } 648 } 649 650 const FunctionDecl *Def; 651 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 652 // template has a constexpr specifier then all its declarations shall 653 // contain the constexpr specifier. 654 if (New->getConstexprKind() != Old->getConstexprKind()) { 655 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 656 << New << static_cast<int>(New->getConstexprKind()) 657 << static_cast<int>(Old->getConstexprKind()); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 661 Old->isDefined(Def) && 662 // If a friend function is inlined but does not have 'inline' 663 // specifier, it is a definition. Do not report attribute conflict 664 // in this case, redefinition will be diagnosed later. 665 (New->isInlineSpecified() || 666 New->getFriendObjectKind() == Decl::FOK_None)) { 667 // C++11 [dcl.fcn.spec]p4: 668 // If the definition of a function appears in a translation unit before its 669 // first declaration as inline, the program is ill-formed. 670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 671 Diag(Def->getLocation(), diag::note_previous_definition); 672 Invalid = true; 673 } 674 675 // C++17 [temp.deduct.guide]p3: 676 // Two deduction guide declarations in the same translation unit 677 // for the same class template shall not have equivalent 678 // parameter-declaration-clauses. 679 if (isa<CXXDeductionGuideDecl>(New) && 680 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 681 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 } 684 685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 686 // argument expression, that declaration shall be a definition and shall be 687 // the only declaration of the function or function template in the 688 // translation unit. 689 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 690 functionDeclHasDefaultArgument(Old)) { 691 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 692 Diag(Old->getLocation(), diag::note_previous_declaration); 693 Invalid = true; 694 } 695 696 // C++11 [temp.friend]p4 (DR329): 697 // When a function is defined in a friend function declaration in a class 698 // template, the function is instantiated when the function is odr-used. 699 // The same restrictions on multiple declarations and definitions that 700 // apply to non-template function declarations and definitions also apply 701 // to these implicit definitions. 702 const FunctionDecl *OldDefinition = nullptr; 703 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 704 Old->isDefined(OldDefinition, true)) 705 CheckForFunctionRedefinition(New, OldDefinition); 706 707 return Invalid; 708 } 709 710 NamedDecl * 711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 712 MultiTemplateParamsArg TemplateParamLists) { 713 assert(D.isDecompositionDeclarator()); 714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 715 716 // The syntax only allows a decomposition declarator as a simple-declaration, 717 // a for-range-declaration, or a condition in Clang, but we parse it in more 718 // cases than that. 719 if (!D.mayHaveDecompositionDeclarator()) { 720 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 721 << Decomp.getSourceRange(); 722 return nullptr; 723 } 724 725 if (!TemplateParamLists.empty()) { 726 // FIXME: There's no rule against this, but there are also no rules that 727 // would actually make it usable, so we reject it for now. 728 Diag(TemplateParamLists.front()->getTemplateLoc(), 729 diag::err_decomp_decl_template); 730 return nullptr; 731 } 732 733 Diag(Decomp.getLSquareLoc(), 734 !getLangOpts().CPlusPlus17 735 ? diag::ext_decomp_decl 736 : D.getContext() == DeclaratorContext::Condition 737 ? diag::ext_decomp_decl_cond 738 : diag::warn_cxx14_compat_decomp_decl) 739 << Decomp.getSourceRange(); 740 741 // The semantic context is always just the current context. 742 DeclContext *const DC = CurContext; 743 744 // C++17 [dcl.dcl]/8: 745 // The decl-specifier-seq shall contain only the type-specifier auto 746 // and cv-qualifiers. 747 // C++2a [dcl.dcl]/8: 748 // If decl-specifier-seq contains any decl-specifier other than static, 749 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 750 auto &DS = D.getDeclSpec(); 751 { 752 SmallVector<StringRef, 8> BadSpecifiers; 753 SmallVector<SourceLocation, 8> BadSpecifierLocs; 754 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 755 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 756 if (auto SCS = DS.getStorageClassSpec()) { 757 if (SCS == DeclSpec::SCS_static) { 758 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 759 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 760 } else { 761 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 762 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 763 } 764 } 765 if (auto TSCS = DS.getThreadStorageClassSpec()) { 766 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 767 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 768 } 769 if (DS.hasConstexprSpecifier()) { 770 BadSpecifiers.push_back( 771 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 772 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 773 } 774 if (DS.isInlineSpecified()) { 775 BadSpecifiers.push_back("inline"); 776 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 777 } 778 if (!BadSpecifiers.empty()) { 779 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 780 Err << (int)BadSpecifiers.size() 781 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 782 // Don't add FixItHints to remove the specifiers; we do still respect 783 // them when building the underlying variable. 784 for (auto Loc : BadSpecifierLocs) 785 Err << SourceRange(Loc, Loc); 786 } else if (!CPlusPlus20Specifiers.empty()) { 787 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 788 getLangOpts().CPlusPlus20 789 ? diag::warn_cxx17_compat_decomp_decl_spec 790 : diag::ext_decomp_decl_spec); 791 Warn << (int)CPlusPlus20Specifiers.size() 792 << llvm::join(CPlusPlus20Specifiers.begin(), 793 CPlusPlus20Specifiers.end(), " "); 794 for (auto Loc : CPlusPlus20SpecifierLocs) 795 Warn << SourceRange(Loc, Loc); 796 } 797 // We can't recover from it being declared as a typedef. 798 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 799 return nullptr; 800 } 801 802 // C++2a [dcl.struct.bind]p1: 803 // A cv that includes volatile is deprecated 804 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 805 getLangOpts().CPlusPlus20) 806 Diag(DS.getVolatileSpecLoc(), 807 diag::warn_deprecated_volatile_structured_binding); 808 809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 810 QualType R = TInfo->getType(); 811 812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 813 UPPC_DeclarationType)) 814 D.setInvalidType(); 815 816 // The syntax only allows a single ref-qualifier prior to the decomposition 817 // declarator. No other declarator chunks are permitted. Also check the type 818 // specifier here. 819 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 820 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 821 (D.getNumTypeObjects() == 1 && 822 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 823 Diag(Decomp.getLSquareLoc(), 824 (D.hasGroupingParens() || 825 (D.getNumTypeObjects() && 826 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 827 ? diag::err_decomp_decl_parens 828 : diag::err_decomp_decl_type) 829 << R; 830 831 // In most cases, there's no actual problem with an explicitly-specified 832 // type, but a function type won't work here, and ActOnVariableDeclarator 833 // shouldn't be called for such a type. 834 if (R->isFunctionType()) 835 D.setInvalidType(); 836 } 837 838 // Build the BindingDecls. 839 SmallVector<BindingDecl*, 8> Bindings; 840 841 // Build the BindingDecls. 842 for (auto &B : D.getDecompositionDeclarator().bindings()) { 843 // Check for name conflicts. 844 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 846 ForVisibleRedeclaration); 847 LookupName(Previous, S, 848 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 849 850 // It's not permitted to shadow a template parameter name. 851 if (Previous.isSingleResult() && 852 Previous.getFoundDecl()->isTemplateParameter()) { 853 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 854 Previous.getFoundDecl()); 855 Previous.clear(); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 860 // Find the shadowed declaration before filtering for scope. 861 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 862 ? getShadowedDeclaration(BD, Previous) 863 : nullptr; 864 865 bool ConsiderLinkage = DC->isFunctionOrMethod() && 866 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 867 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 868 /*AllowInlineNamespace*/false); 869 870 if (!Previous.empty()) { 871 auto *Old = Previous.getRepresentativeDecl(); 872 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 873 Diag(Old->getLocation(), diag::note_previous_definition); 874 } else if (ShadowedDecl && !D.isRedeclaration()) { 875 CheckShadow(BD, ShadowedDecl, Previous); 876 } 877 PushOnScopeChains(BD, S, true); 878 Bindings.push_back(BD); 879 ParsingInitForAutoVars.insert(BD); 880 } 881 882 // There are no prior lookup results for the variable itself, because it 883 // is unnamed. 884 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 885 Decomp.getLSquareLoc()); 886 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 887 ForVisibleRedeclaration); 888 889 // Build the variable that holds the non-decomposed object. 890 bool AddToScope = true; 891 NamedDecl *New = 892 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 893 MultiTemplateParamsArg(), AddToScope, Bindings); 894 if (AddToScope) { 895 S->AddDecl(New); 896 CurContext->addHiddenDecl(New); 897 } 898 899 if (isInOpenMPDeclareTargetContext()) 900 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 901 902 return New; 903 } 904 905 static bool checkSimpleDecomposition( 906 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 907 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 908 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 909 if ((int64_t)Bindings.size() != NumElems) { 910 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 911 << DecompType << (unsigned)Bindings.size() 912 << (unsigned)NumElems.getLimitedValue(UINT_MAX) 913 << toString(NumElems, 10) << (NumElems < Bindings.size()); 914 return true; 915 } 916 917 unsigned I = 0; 918 for (auto *B : Bindings) { 919 SourceLocation Loc = B->getLocation(); 920 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 921 if (E.isInvalid()) 922 return true; 923 E = GetInit(Loc, E.get(), I++); 924 if (E.isInvalid()) 925 return true; 926 B->setBinding(ElemType, E.get()); 927 } 928 929 return false; 930 } 931 932 static bool checkArrayLikeDecomposition(Sema &S, 933 ArrayRef<BindingDecl *> Bindings, 934 ValueDecl *Src, QualType DecompType, 935 const llvm::APSInt &NumElems, 936 QualType ElemType) { 937 return checkSimpleDecomposition( 938 S, Bindings, Src, DecompType, NumElems, ElemType, 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 ExprResult E = S.ActOnIntegerConstant(Loc, I); 941 if (E.isInvalid()) 942 return ExprError(); 943 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 944 }); 945 } 946 947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 948 ValueDecl *Src, QualType DecompType, 949 const ConstantArrayType *CAT) { 950 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 951 llvm::APSInt(CAT->getSize()), 952 CAT->getElementType()); 953 } 954 955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 956 ValueDecl *Src, QualType DecompType, 957 const VectorType *VT) { 958 return checkArrayLikeDecomposition( 959 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 960 S.Context.getQualifiedType(VT->getElementType(), 961 DecompType.getQualifiers())); 962 } 963 964 static bool checkComplexDecomposition(Sema &S, 965 ArrayRef<BindingDecl *> Bindings, 966 ValueDecl *Src, QualType DecompType, 967 const ComplexType *CT) { 968 return checkSimpleDecomposition( 969 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 970 S.Context.getQualifiedType(CT->getElementType(), 971 DecompType.getQualifiers()), 972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 973 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 974 }); 975 } 976 977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 978 TemplateArgumentListInfo &Args, 979 const TemplateParameterList *Params) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 unsigned I = 0; 984 for (auto &Arg : Args.arguments()) { 985 if (!First) 986 OS << ", "; 987 Arg.getArgument().print(PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument( 989 PrintingPolicy, Params, I)); 990 First = false; 991 I++; 992 } 993 return std::string(OS.str()); 994 } 995 996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 997 SourceLocation Loc, StringRef Trait, 998 TemplateArgumentListInfo &Args, 999 unsigned DiagID) { 1000 auto DiagnoseMissing = [&] { 1001 if (DiagID) 1002 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1003 Args, /*Params*/ nullptr); 1004 return true; 1005 }; 1006 1007 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1008 NamespaceDecl *Std = S.getStdNamespace(); 1009 if (!Std) 1010 return DiagnoseMissing(); 1011 1012 // Look up the trait itself, within namespace std. We can diagnose various 1013 // problems with this lookup even if we've been asked to not diagnose a 1014 // missing specialization, because this can only fail if the user has been 1015 // declaring their own names in namespace std or we don't support the 1016 // standard library implementation in use. 1017 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1018 Loc, Sema::LookupOrdinaryName); 1019 if (!S.LookupQualifiedName(Result, Std)) 1020 return DiagnoseMissing(); 1021 if (Result.isAmbiguous()) 1022 return true; 1023 1024 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1025 if (!TraitTD) { 1026 Result.suppressDiagnostics(); 1027 NamedDecl *Found = *Result.begin(); 1028 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1029 S.Diag(Found->getLocation(), diag::note_declared_at); 1030 return true; 1031 } 1032 1033 // Build the template-id. 1034 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1035 if (TraitTy.isNull()) 1036 return true; 1037 if (!S.isCompleteType(Loc, TraitTy)) { 1038 if (DiagID) 1039 S.RequireCompleteType( 1040 Loc, TraitTy, DiagID, 1041 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1042 TraitTD->getTemplateParameters())); 1043 return true; 1044 } 1045 1046 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1047 assert(RD && "specialization of class template is not a class?"); 1048 1049 // Look up the member of the trait type. 1050 S.LookupQualifiedName(TraitMemberLookup, RD); 1051 return TraitMemberLookup.isAmbiguous(); 1052 } 1053 1054 static TemplateArgumentLoc 1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1056 uint64_t I) { 1057 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1058 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1059 } 1060 1061 static TemplateArgumentLoc 1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1063 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1064 } 1065 1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1067 1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1069 llvm::APSInt &Size) { 1070 EnterExpressionEvaluationContext ContextRAII( 1071 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1072 1073 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1074 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1075 1076 // Form template argument list for tuple_size<T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1079 1080 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1081 // it's not tuple-like. 1082 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1083 R.empty()) 1084 return IsTupleLike::NotTupleLike; 1085 1086 // If we get this far, we've committed to the tuple interpretation, but 1087 // we can still fail if there actually isn't a usable ::value. 1088 1089 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1090 LookupResult &R; 1091 TemplateArgumentListInfo &Args; 1092 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1093 : R(R), Args(Args) {} 1094 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1095 SourceLocation Loc) override { 1096 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1097 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1098 /*Params*/ nullptr); 1099 } 1100 } Diagnoser(R, Args); 1101 1102 ExprResult E = 1103 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1104 if (E.isInvalid()) 1105 return IsTupleLike::Error; 1106 1107 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1108 if (E.isInvalid()) 1109 return IsTupleLike::Error; 1110 1111 return IsTupleLike::TupleLike; 1112 } 1113 1114 /// \return std::tuple_element<I, T>::type. 1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1116 unsigned I, QualType T) { 1117 // Form template argument list for tuple_element<I, T>. 1118 TemplateArgumentListInfo Args(Loc, Loc); 1119 Args.addArgument( 1120 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1121 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1122 1123 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1124 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1125 if (lookupStdTypeTraitMember( 1126 S, R, Loc, "tuple_element", Args, 1127 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1128 return QualType(); 1129 1130 auto *TD = R.getAsSingle<TypeDecl>(); 1131 if (!TD) { 1132 R.suppressDiagnostics(); 1133 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1134 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1135 /*Params*/ nullptr); 1136 if (!R.empty()) 1137 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1138 return QualType(); 1139 } 1140 1141 return S.Context.getTypeDeclType(TD); 1142 } 1143 1144 namespace { 1145 struct InitializingBinding { 1146 Sema &S; 1147 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1148 Sema::CodeSynthesisContext Ctx; 1149 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1150 Ctx.PointOfInstantiation = BD->getLocation(); 1151 Ctx.Entity = BD; 1152 S.pushCodeSynthesisContext(Ctx); 1153 } 1154 ~InitializingBinding() { 1155 S.popCodeSynthesisContext(); 1156 } 1157 }; 1158 } 1159 1160 static bool checkTupleLikeDecomposition(Sema &S, 1161 ArrayRef<BindingDecl *> Bindings, 1162 VarDecl *Src, QualType DecompType, 1163 const llvm::APSInt &TupleSize) { 1164 if ((int64_t)Bindings.size() != TupleSize) { 1165 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1166 << DecompType << (unsigned)Bindings.size() 1167 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1168 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1169 return true; 1170 } 1171 1172 if (Bindings.empty()) 1173 return false; 1174 1175 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1176 1177 // [dcl.decomp]p3: 1178 // The unqualified-id get is looked up in the scope of E by class member 1179 // access lookup ... 1180 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1181 bool UseMemberGet = false; 1182 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1183 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1184 S.LookupQualifiedName(MemberGet, RD); 1185 if (MemberGet.isAmbiguous()) 1186 return true; 1187 // ... and if that finds at least one declaration that is a function 1188 // template whose first template parameter is a non-type parameter ... 1189 for (NamedDecl *D : MemberGet) { 1190 if (FunctionTemplateDecl *FTD = 1191 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1192 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1193 if (TPL->size() != 0 && 1194 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1195 // ... the initializer is e.get<i>(). 1196 UseMemberGet = true; 1197 break; 1198 } 1199 } 1200 } 1201 } 1202 1203 unsigned I = 0; 1204 for (auto *B : Bindings) { 1205 InitializingBinding InitContext(S, B); 1206 SourceLocation Loc = B->getLocation(); 1207 1208 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1209 if (E.isInvalid()) 1210 return true; 1211 1212 // e is an lvalue if the type of the entity is an lvalue reference and 1213 // an xvalue otherwise 1214 if (!Src->getType()->isLValueReferenceType()) 1215 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1216 E.get(), nullptr, VK_XValue, 1217 FPOptionsOverride()); 1218 1219 TemplateArgumentListInfo Args(Loc, Loc); 1220 Args.addArgument( 1221 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1222 1223 if (UseMemberGet) { 1224 // if [lookup of member get] finds at least one declaration, the 1225 // initializer is e.get<i-1>(). 1226 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1227 CXXScopeSpec(), SourceLocation(), nullptr, 1228 MemberGet, &Args, nullptr); 1229 if (E.isInvalid()) 1230 return true; 1231 1232 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1233 } else { 1234 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1235 // in the associated namespaces. 1236 Expr *Get = UnresolvedLookupExpr::Create( 1237 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1238 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1239 UnresolvedSetIterator(), UnresolvedSetIterator()); 1240 1241 Expr *Arg = E.get(); 1242 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1243 } 1244 if (E.isInvalid()) 1245 return true; 1246 Expr *Init = E.get(); 1247 1248 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1249 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1250 if (T.isNull()) 1251 return true; 1252 1253 // each vi is a variable of type "reference to T" initialized with the 1254 // initializer, where the reference is an lvalue reference if the 1255 // initializer is an lvalue and an rvalue reference otherwise 1256 QualType RefType = 1257 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1258 if (RefType.isNull()) 1259 return true; 1260 auto *RefVD = VarDecl::Create( 1261 S.Context, Src->getDeclContext(), Loc, Loc, 1262 B->getDeclName().getAsIdentifierInfo(), RefType, 1263 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1264 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1265 RefVD->setTSCSpec(Src->getTSCSpec()); 1266 RefVD->setImplicit(); 1267 if (Src->isInlineSpecified()) 1268 RefVD->setInlineSpecified(); 1269 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1270 1271 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1272 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1273 InitializationSequence Seq(S, Entity, Kind, Init); 1274 E = Seq.Perform(S, Entity, Kind, Init); 1275 if (E.isInvalid()) 1276 return true; 1277 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1278 if (E.isInvalid()) 1279 return true; 1280 RefVD->setInit(E.get()); 1281 S.CheckCompleteVariableDeclaration(RefVD); 1282 1283 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1284 DeclarationNameInfo(B->getDeclName(), Loc), 1285 RefVD); 1286 if (E.isInvalid()) 1287 return true; 1288 1289 B->setBinding(T, E.get()); 1290 I++; 1291 } 1292 1293 return false; 1294 } 1295 1296 /// Find the base class to decompose in a built-in decomposition of a class type. 1297 /// This base class search is, unfortunately, not quite like any other that we 1298 /// perform anywhere else in C++. 1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1300 const CXXRecordDecl *RD, 1301 CXXCastPath &BasePath) { 1302 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1303 CXXBasePath &Path) { 1304 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1305 }; 1306 1307 const CXXRecordDecl *ClassWithFields = nullptr; 1308 AccessSpecifier AS = AS_public; 1309 if (RD->hasDirectFields()) 1310 // [dcl.decomp]p4: 1311 // Otherwise, all of E's non-static data members shall be public direct 1312 // members of E ... 1313 ClassWithFields = RD; 1314 else { 1315 // ... or of ... 1316 CXXBasePaths Paths; 1317 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1318 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1319 // If no classes have fields, just decompose RD itself. (This will work 1320 // if and only if zero bindings were provided.) 1321 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1322 } 1323 1324 CXXBasePath *BestPath = nullptr; 1325 for (auto &P : Paths) { 1326 if (!BestPath) 1327 BestPath = &P; 1328 else if (!S.Context.hasSameType(P.back().Base->getType(), 1329 BestPath->back().Base->getType())) { 1330 // ... the same ... 1331 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1332 << false << RD << BestPath->back().Base->getType() 1333 << P.back().Base->getType(); 1334 return DeclAccessPair(); 1335 } else if (P.Access < BestPath->Access) { 1336 BestPath = &P; 1337 } 1338 } 1339 1340 // ... unambiguous ... 1341 QualType BaseType = BestPath->back().Base->getType(); 1342 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1343 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1344 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1345 return DeclAccessPair(); 1346 } 1347 1348 // ... [accessible, implied by other rules] base class of E. 1349 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1350 *BestPath, diag::err_decomp_decl_inaccessible_base); 1351 AS = BestPath->Access; 1352 1353 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1354 S.BuildBasePathArray(Paths, BasePath); 1355 } 1356 1357 // The above search did not check whether the selected class itself has base 1358 // classes with fields, so check that now. 1359 CXXBasePaths Paths; 1360 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1361 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1362 << (ClassWithFields == RD) << RD << ClassWithFields 1363 << Paths.front().back().Base->getType(); 1364 return DeclAccessPair(); 1365 } 1366 1367 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1368 } 1369 1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1371 ValueDecl *Src, QualType DecompType, 1372 const CXXRecordDecl *OrigRD) { 1373 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1374 diag::err_incomplete_type)) 1375 return true; 1376 1377 CXXCastPath BasePath; 1378 DeclAccessPair BasePair = 1379 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1380 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1381 if (!RD) 1382 return true; 1383 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1384 DecompType.getQualifiers()); 1385 1386 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1387 unsigned NumFields = llvm::count_if( 1388 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1389 assert(Bindings.size() != NumFields); 1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1392 << (NumFields < Bindings.size()); 1393 return true; 1394 }; 1395 1396 // all of E's non-static data members shall be [...] well-formed 1397 // when named as e.name in the context of the structured binding, 1398 // E shall not have an anonymous union member, ... 1399 unsigned I = 0; 1400 for (auto *FD : RD->fields()) { 1401 if (FD->isUnnamedBitfield()) 1402 continue; 1403 1404 // All the non-static data members are required to be nameable, so they 1405 // must all have names. 1406 if (!FD->getDeclName()) { 1407 if (RD->isLambda()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1409 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1410 return true; 1411 } 1412 1413 if (FD->isAnonymousStructOrUnion()) { 1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1415 << DecompType << FD->getType()->isUnionType(); 1416 S.Diag(FD->getLocation(), diag::note_declared_at); 1417 return true; 1418 } 1419 1420 // FIXME: Are there any other ways we could have an anonymous member? 1421 } 1422 1423 // We have a real field to bind. 1424 if (I >= Bindings.size()) 1425 return DiagnoseBadNumberOfBindings(); 1426 auto *B = Bindings[I++]; 1427 SourceLocation Loc = B->getLocation(); 1428 1429 // The field must be accessible in the context of the structured binding. 1430 // We already checked that the base class is accessible. 1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1432 // const_cast here. 1433 S.CheckStructuredBindingMemberAccess( 1434 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1436 BasePair.getAccess(), FD->getAccess()))); 1437 1438 // Initialize the binding to Src.FD. 1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1440 if (E.isInvalid()) 1441 return true; 1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1443 VK_LValue, &BasePath); 1444 if (E.isInvalid()) 1445 return true; 1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1447 CXXScopeSpec(), FD, 1448 DeclAccessPair::make(FD, FD->getAccess()), 1449 DeclarationNameInfo(FD->getDeclName(), Loc)); 1450 if (E.isInvalid()) 1451 return true; 1452 1453 // If the type of the member is T, the referenced type is cv T, where cv is 1454 // the cv-qualification of the decomposition expression. 1455 // 1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1457 // 'const' to the type of the field. 1458 Qualifiers Q = DecompType.getQualifiers(); 1459 if (FD->isMutable()) 1460 Q.removeConst(); 1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1462 } 1463 1464 if (I != Bindings.size()) 1465 return DiagnoseBadNumberOfBindings(); 1466 1467 return false; 1468 } 1469 1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1471 QualType DecompType = DD->getType(); 1472 1473 // If the type of the decomposition is dependent, then so is the type of 1474 // each binding. 1475 if (DecompType->isDependentType()) { 1476 for (auto *B : DD->bindings()) 1477 B->setType(Context.DependentTy); 1478 return; 1479 } 1480 1481 DecompType = DecompType.getNonReferenceType(); 1482 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1483 1484 // C++1z [dcl.decomp]/2: 1485 // If E is an array type [...] 1486 // As an extension, we also support decomposition of built-in complex and 1487 // vector types. 1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 if (auto *VT = DecompType->getAs<VectorType>()) { 1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1495 DD->setInvalidDecl(); 1496 return; 1497 } 1498 if (auto *CT = DecompType->getAs<ComplexType>()) { 1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1500 DD->setInvalidDecl(); 1501 return; 1502 } 1503 1504 // C++1z [dcl.decomp]/3: 1505 // if the expression std::tuple_size<E>::value is a well-formed integral 1506 // constant expression, [...] 1507 llvm::APSInt TupleSize(32); 1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1509 case IsTupleLike::Error: 1510 DD->setInvalidDecl(); 1511 return; 1512 1513 case IsTupleLike::TupleLike: 1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1515 DD->setInvalidDecl(); 1516 return; 1517 1518 case IsTupleLike::NotTupleLike: 1519 break; 1520 } 1521 1522 // C++1z [dcl.dcl]/8: 1523 // [E shall be of array or non-union class type] 1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1525 if (!RD || RD->isUnion()) { 1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1527 << DD << !RD << DecompType; 1528 DD->setInvalidDecl(); 1529 return; 1530 } 1531 1532 // C++1z [dcl.decomp]/4: 1533 // all of E's non-static data members shall be [...] direct members of 1534 // E or of the same unambiguous public base class of E, ... 1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1536 DD->setInvalidDecl(); 1537 } 1538 1539 /// Merge the exception specifications of two variable declarations. 1540 /// 1541 /// This is called when there's a redeclaration of a VarDecl. The function 1542 /// checks if the redeclaration might have an exception specification and 1543 /// validates compatibility and merges the specs if necessary. 1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1545 // Shortcut if exceptions are disabled. 1546 if (!getLangOpts().CXXExceptions) 1547 return; 1548 1549 assert(Context.hasSameType(New->getType(), Old->getType()) && 1550 "Should only be called if types are otherwise the same."); 1551 1552 QualType NewType = New->getType(); 1553 QualType OldType = Old->getType(); 1554 1555 // We're only interested in pointers and references to functions, as well 1556 // as pointers to member functions. 1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1558 NewType = R->getPointeeType(); 1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1561 NewType = P->getPointeeType(); 1562 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1564 NewType = M->getPointeeType(); 1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1566 } 1567 1568 if (!NewType->isFunctionProtoType()) 1569 return; 1570 1571 // There's lots of special cases for functions. For function pointers, system 1572 // libraries are hopefully not as broken so that we don't need these 1573 // workarounds. 1574 if (CheckEquivalentExceptionSpec( 1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1577 New->setInvalidDecl(); 1578 } 1579 } 1580 1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1582 /// function declaration are well-formed according to C++ 1583 /// [dcl.fct.default]. 1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1585 unsigned NumParams = FD->getNumParams(); 1586 unsigned ParamIdx = 0; 1587 1588 // This checking doesn't make sense for explicit specializations; their 1589 // default arguments are determined by the declaration we're specializing, 1590 // not by FD. 1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1592 return; 1593 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1594 if (FTD->isMemberSpecialization()) 1595 return; 1596 1597 // Find first parameter with a default argument 1598 for (; ParamIdx < NumParams; ++ParamIdx) { 1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1600 if (Param->hasDefaultArg()) 1601 break; 1602 } 1603 1604 // C++20 [dcl.fct.default]p4: 1605 // In a given function declaration, each parameter subsequent to a parameter 1606 // with a default argument shall have a default argument supplied in this or 1607 // a previous declaration, unless the parameter was expanded from a 1608 // parameter pack, or shall be a function parameter pack. 1609 for (; ParamIdx < NumParams; ++ParamIdx) { 1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1612 !(CurrentInstantiationScope && 1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1614 if (Param->isInvalidDecl()) 1615 /* We already complained about this parameter. */; 1616 else if (Param->getIdentifier()) 1617 Diag(Param->getLocation(), 1618 diag::err_param_default_argument_missing_name) 1619 << Param->getIdentifier(); 1620 else 1621 Diag(Param->getLocation(), 1622 diag::err_param_default_argument_missing); 1623 } 1624 } 1625 } 1626 1627 /// Check that the given type is a literal type. Issue a diagnostic if not, 1628 /// if Kind is Diagnose. 1629 /// \return \c true if a problem has been found (and optionally diagnosed). 1630 template <typename... Ts> 1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1632 SourceLocation Loc, QualType T, unsigned DiagID, 1633 Ts &&...DiagArgs) { 1634 if (T->isDependentType()) 1635 return false; 1636 1637 switch (Kind) { 1638 case Sema::CheckConstexprKind::Diagnose: 1639 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1640 std::forward<Ts>(DiagArgs)...); 1641 1642 case Sema::CheckConstexprKind::CheckValid: 1643 return !T->isLiteralType(SemaRef.Context); 1644 } 1645 1646 llvm_unreachable("unknown CheckConstexprKind"); 1647 } 1648 1649 /// Determine whether a destructor cannot be constexpr due to 1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1651 const CXXDestructorDecl *DD, 1652 Sema::CheckConstexprKind Kind) { 1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1654 const CXXRecordDecl *RD = 1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1656 if (!RD || RD->hasConstexprDestructor()) 1657 return true; 1658 1659 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1661 << static_cast<int>(DD->getConstexprKind()) << !FD 1662 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1665 } 1666 return false; 1667 }; 1668 1669 const CXXRecordDecl *RD = DD->getParent(); 1670 for (const CXXBaseSpecifier &B : RD->bases()) 1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1672 return false; 1673 for (const FieldDecl *FD : RD->fields()) 1674 if (!Check(FD->getLocation(), FD->getType(), FD)) 1675 return false; 1676 return true; 1677 } 1678 1679 /// Check whether a function's parameter types are all literal types. If so, 1680 /// return true. If not, produce a suitable diagnostic and return false. 1681 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1682 const FunctionDecl *FD, 1683 Sema::CheckConstexprKind Kind) { 1684 unsigned ArgIndex = 0; 1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1687 e = FT->param_type_end(); 1688 i != e; ++i, ++ArgIndex) { 1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1690 SourceLocation ParamLoc = PD->getLocation(); 1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1692 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1694 FD->isConsteval())) 1695 return false; 1696 } 1697 return true; 1698 } 1699 1700 /// Check whether a function's return type is a literal type. If so, return 1701 /// true. If not, produce a suitable diagnostic and return false. 1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1703 Sema::CheckConstexprKind Kind) { 1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1705 diag::err_constexpr_non_literal_return, 1706 FD->isConsteval())) 1707 return false; 1708 return true; 1709 } 1710 1711 /// Get diagnostic %select index for tag kind for 1712 /// record diagnostic message. 1713 /// WARNING: Indexes apply to particular diagnostics only! 1714 /// 1715 /// \returns diagnostic %select index. 1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1717 switch (Tag) { 1718 case TTK_Struct: return 0; 1719 case TTK_Interface: return 1; 1720 case TTK_Class: return 2; 1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1722 } 1723 } 1724 1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1726 Stmt *Body, 1727 Sema::CheckConstexprKind Kind); 1728 1729 // Check whether a function declaration satisfies the requirements of a 1730 // constexpr function definition or a constexpr constructor definition. If so, 1731 // return true. If not, produce appropriate diagnostics (unless asked not to by 1732 // Kind) and return false. 1733 // 1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1736 CheckConstexprKind Kind) { 1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1738 if (MD && MD->isInstance()) { 1739 // C++11 [dcl.constexpr]p4: 1740 // The definition of a constexpr constructor shall satisfy the following 1741 // constraints: 1742 // - the class shall not have any virtual base classes; 1743 // 1744 // FIXME: This only applies to constructors and destructors, not arbitrary 1745 // member functions. 1746 const CXXRecordDecl *RD = MD->getParent(); 1747 if (RD->getNumVBases()) { 1748 if (Kind == CheckConstexprKind::CheckValid) 1749 return false; 1750 1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1752 << isa<CXXConstructorDecl>(NewFD) 1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1754 for (const auto &I : RD->vbases()) 1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1756 << I.getSourceRange(); 1757 return false; 1758 } 1759 } 1760 1761 if (!isa<CXXConstructorDecl>(NewFD)) { 1762 // C++11 [dcl.constexpr]p3: 1763 // The definition of a constexpr function shall satisfy the following 1764 // constraints: 1765 // - it shall not be virtual; (removed in C++20) 1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1767 if (Method && Method->isVirtual()) { 1768 if (getLangOpts().CPlusPlus20) { 1769 if (Kind == CheckConstexprKind::Diagnose) 1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1771 } else { 1772 if (Kind == CheckConstexprKind::CheckValid) 1773 return false; 1774 1775 Method = Method->getCanonicalDecl(); 1776 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1777 1778 // If it's not obvious why this function is virtual, find an overridden 1779 // function which uses the 'virtual' keyword. 1780 const CXXMethodDecl *WrittenVirtual = Method; 1781 while (!WrittenVirtual->isVirtualAsWritten()) 1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1783 if (WrittenVirtual != Method) 1784 Diag(WrittenVirtual->getLocation(), 1785 diag::note_overridden_virtual_function); 1786 return false; 1787 } 1788 } 1789 1790 // - its return type shall be a literal type; 1791 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1792 return false; 1793 } 1794 1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1796 // A destructor can be constexpr only if the defaulted destructor could be; 1797 // we don't need to check the members and bases if we already know they all 1798 // have constexpr destructors. 1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1800 if (Kind == CheckConstexprKind::CheckValid) 1801 return false; 1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1803 return false; 1804 } 1805 } 1806 1807 // - each of its parameter types shall be a literal type; 1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1809 return false; 1810 1811 Stmt *Body = NewFD->getBody(); 1812 assert(Body && 1813 "CheckConstexprFunctionDefinition called on function with no body"); 1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1815 } 1816 1817 /// Check the given declaration statement is legal within a constexpr function 1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1819 /// 1820 /// \return true if the body is OK (maybe only as an extension), false if we 1821 /// have diagnosed a problem. 1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1823 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1824 Sema::CheckConstexprKind Kind) { 1825 // C++11 [dcl.constexpr]p3 and p4: 1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1827 // contain only 1828 for (const auto *DclIt : DS->decls()) { 1829 switch (DclIt->getKind()) { 1830 case Decl::StaticAssert: 1831 case Decl::Using: 1832 case Decl::UsingShadow: 1833 case Decl::UsingDirective: 1834 case Decl::UnresolvedUsingTypename: 1835 case Decl::UnresolvedUsingValue: 1836 case Decl::UsingEnum: 1837 // - static_assert-declarations 1838 // - using-declarations, 1839 // - using-directives, 1840 // - using-enum-declaration 1841 continue; 1842 1843 case Decl::Typedef: 1844 case Decl::TypeAlias: { 1845 // - typedef declarations and alias-declarations that do not define 1846 // classes or enumerations, 1847 const auto *TN = cast<TypedefNameDecl>(DclIt); 1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1849 // Don't allow variably-modified types in constexpr functions. 1850 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1853 << TL.getSourceRange() << TL.getType() 1854 << isa<CXXConstructorDecl>(Dcl); 1855 } 1856 return false; 1857 } 1858 continue; 1859 } 1860 1861 case Decl::Enum: 1862 case Decl::CXXRecord: 1863 // C++1y allows types to be defined, not just declared. 1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1865 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1866 SemaRef.Diag(DS->getBeginLoc(), 1867 SemaRef.getLangOpts().CPlusPlus14 1868 ? diag::warn_cxx11_compat_constexpr_type_definition 1869 : diag::ext_constexpr_type_definition) 1870 << isa<CXXConstructorDecl>(Dcl); 1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1872 return false; 1873 } 1874 } 1875 continue; 1876 1877 case Decl::EnumConstant: 1878 case Decl::IndirectField: 1879 case Decl::ParmVar: 1880 // These can only appear with other declarations which are banned in 1881 // C++11 and permitted in C++1y, so ignore them. 1882 continue; 1883 1884 case Decl::Var: 1885 case Decl::Decomposition: { 1886 // C++1y [dcl.constexpr]p3 allows anything except: 1887 // a definition of a variable of non-literal type or of static or 1888 // thread storage duration or [before C++2a] for which no 1889 // initialization is performed. 1890 const auto *VD = cast<VarDecl>(DclIt); 1891 if (VD->isThisDeclarationADefinition()) { 1892 if (VD->isStaticLocal()) { 1893 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1894 SemaRef.Diag(VD->getLocation(), 1895 SemaRef.getLangOpts().CPlusPlus2b 1896 ? diag::warn_cxx20_compat_constexpr_var 1897 : diag::ext_constexpr_static_var) 1898 << isa<CXXConstructorDecl>(Dcl) 1899 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1900 } else if (!SemaRef.getLangOpts().CPlusPlus2b) { 1901 return false; 1902 } 1903 } 1904 if (SemaRef.LangOpts.CPlusPlus2b) { 1905 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1906 diag::warn_cxx20_compat_constexpr_var, 1907 isa<CXXConstructorDecl>(Dcl), 1908 /*variable of non-literal type*/ 2); 1909 } else if (CheckLiteralType( 1910 SemaRef, Kind, VD->getLocation(), VD->getType(), 1911 diag::err_constexpr_local_var_non_literal_type, 1912 isa<CXXConstructorDecl>(Dcl))) { 1913 return false; 1914 } 1915 if (!VD->getType()->isDependentType() && 1916 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1917 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1918 SemaRef.Diag( 1919 VD->getLocation(), 1920 SemaRef.getLangOpts().CPlusPlus20 1921 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1922 : diag::ext_constexpr_local_var_no_init) 1923 << isa<CXXConstructorDecl>(Dcl); 1924 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1925 return false; 1926 } 1927 continue; 1928 } 1929 } 1930 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1931 SemaRef.Diag(VD->getLocation(), 1932 SemaRef.getLangOpts().CPlusPlus14 1933 ? diag::warn_cxx11_compat_constexpr_local_var 1934 : diag::ext_constexpr_local_var) 1935 << isa<CXXConstructorDecl>(Dcl); 1936 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1937 return false; 1938 } 1939 continue; 1940 } 1941 1942 case Decl::NamespaceAlias: 1943 case Decl::Function: 1944 // These are disallowed in C++11 and permitted in C++1y. Allow them 1945 // everywhere as an extension. 1946 if (!Cxx1yLoc.isValid()) 1947 Cxx1yLoc = DS->getBeginLoc(); 1948 continue; 1949 1950 default: 1951 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1952 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1953 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1954 } 1955 return false; 1956 } 1957 } 1958 1959 return true; 1960 } 1961 1962 /// Check that the given field is initialized within a constexpr constructor. 1963 /// 1964 /// \param Dcl The constexpr constructor being checked. 1965 /// \param Field The field being checked. This may be a member of an anonymous 1966 /// struct or union nested within the class being checked. 1967 /// \param Inits All declarations, including anonymous struct/union members and 1968 /// indirect members, for which any initialization was provided. 1969 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1970 /// multiple notes for different members to the same error. 1971 /// \param Kind Whether we're diagnosing a constructor as written or determining 1972 /// whether the formal requirements are satisfied. 1973 /// \return \c false if we're checking for validity and the constructor does 1974 /// not satisfy the requirements on a constexpr constructor. 1975 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1976 const FunctionDecl *Dcl, 1977 FieldDecl *Field, 1978 llvm::SmallSet<Decl*, 16> &Inits, 1979 bool &Diagnosed, 1980 Sema::CheckConstexprKind Kind) { 1981 // In C++20 onwards, there's nothing to check for validity. 1982 if (Kind == Sema::CheckConstexprKind::CheckValid && 1983 SemaRef.getLangOpts().CPlusPlus20) 1984 return true; 1985 1986 if (Field->isInvalidDecl()) 1987 return true; 1988 1989 if (Field->isUnnamedBitfield()) 1990 return true; 1991 1992 // Anonymous unions with no variant members and empty anonymous structs do not 1993 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1994 // indirect fields don't need initializing. 1995 if (Field->isAnonymousStructOrUnion() && 1996 (Field->getType()->isUnionType() 1997 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1998 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1999 return true; 2000 2001 if (!Inits.count(Field)) { 2002 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2003 if (!Diagnosed) { 2004 SemaRef.Diag(Dcl->getLocation(), 2005 SemaRef.getLangOpts().CPlusPlus20 2006 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 2007 : diag::ext_constexpr_ctor_missing_init); 2008 Diagnosed = true; 2009 } 2010 SemaRef.Diag(Field->getLocation(), 2011 diag::note_constexpr_ctor_missing_init); 2012 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2013 return false; 2014 } 2015 } else if (Field->isAnonymousStructOrUnion()) { 2016 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2017 for (auto *I : RD->fields()) 2018 // If an anonymous union contains an anonymous struct of which any member 2019 // is initialized, all members must be initialized. 2020 if (!RD->isUnion() || Inits.count(I)) 2021 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2022 Kind)) 2023 return false; 2024 } 2025 return true; 2026 } 2027 2028 /// Check the provided statement is allowed in a constexpr function 2029 /// definition. 2030 static bool 2031 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2032 SmallVectorImpl<SourceLocation> &ReturnStmts, 2033 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2034 SourceLocation &Cxx2bLoc, 2035 Sema::CheckConstexprKind Kind) { 2036 // - its function-body shall be [...] a compound-statement that contains only 2037 switch (S->getStmtClass()) { 2038 case Stmt::NullStmtClass: 2039 // - null statements, 2040 return true; 2041 2042 case Stmt::DeclStmtClass: 2043 // - static_assert-declarations 2044 // - using-declarations, 2045 // - using-directives, 2046 // - typedef declarations and alias-declarations that do not define 2047 // classes or enumerations, 2048 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2049 return false; 2050 return true; 2051 2052 case Stmt::ReturnStmtClass: 2053 // - and exactly one return statement; 2054 if (isa<CXXConstructorDecl>(Dcl)) { 2055 // C++1y allows return statements in constexpr constructors. 2056 if (!Cxx1yLoc.isValid()) 2057 Cxx1yLoc = S->getBeginLoc(); 2058 return true; 2059 } 2060 2061 ReturnStmts.push_back(S->getBeginLoc()); 2062 return true; 2063 2064 case Stmt::AttributedStmtClass: 2065 // Attributes on a statement don't affect its formal kind and hence don't 2066 // affect its validity in a constexpr function. 2067 return CheckConstexprFunctionStmt( 2068 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts, 2069 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind); 2070 2071 case Stmt::CompoundStmtClass: { 2072 // C++1y allows compound-statements. 2073 if (!Cxx1yLoc.isValid()) 2074 Cxx1yLoc = S->getBeginLoc(); 2075 2076 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2077 for (auto *BodyIt : CompStmt->body()) { 2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2080 return false; 2081 } 2082 return true; 2083 } 2084 2085 case Stmt::IfStmtClass: { 2086 // C++1y allows if-statements. 2087 if (!Cxx1yLoc.isValid()) 2088 Cxx1yLoc = S->getBeginLoc(); 2089 2090 IfStmt *If = cast<IfStmt>(S); 2091 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2092 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2093 return false; 2094 if (If->getElse() && 2095 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2096 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2097 return false; 2098 return true; 2099 } 2100 2101 case Stmt::WhileStmtClass: 2102 case Stmt::DoStmtClass: 2103 case Stmt::ForStmtClass: 2104 case Stmt::CXXForRangeStmtClass: 2105 case Stmt::ContinueStmtClass: 2106 // C++1y allows all of these. We don't allow them as extensions in C++11, 2107 // because they don't make sense without variable mutation. 2108 if (!SemaRef.getLangOpts().CPlusPlus14) 2109 break; 2110 if (!Cxx1yLoc.isValid()) 2111 Cxx1yLoc = S->getBeginLoc(); 2112 for (Stmt *SubStmt : S->children()) { 2113 if (SubStmt && 2114 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2115 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2116 return false; 2117 } 2118 return true; 2119 2120 case Stmt::SwitchStmtClass: 2121 case Stmt::CaseStmtClass: 2122 case Stmt::DefaultStmtClass: 2123 case Stmt::BreakStmtClass: 2124 // C++1y allows switch-statements, and since they don't need variable 2125 // mutation, we can reasonably allow them in C++11 as an extension. 2126 if (!Cxx1yLoc.isValid()) 2127 Cxx1yLoc = S->getBeginLoc(); 2128 for (Stmt *SubStmt : S->children()) { 2129 if (SubStmt && 2130 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2131 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2132 return false; 2133 } 2134 return true; 2135 2136 case Stmt::LabelStmtClass: 2137 case Stmt::GotoStmtClass: 2138 if (Cxx2bLoc.isInvalid()) 2139 Cxx2bLoc = S->getBeginLoc(); 2140 for (Stmt *SubStmt : S->children()) { 2141 if (SubStmt && 2142 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2143 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2144 return false; 2145 } 2146 return true; 2147 2148 case Stmt::GCCAsmStmtClass: 2149 case Stmt::MSAsmStmtClass: 2150 // C++2a allows inline assembly statements. 2151 case Stmt::CXXTryStmtClass: 2152 if (Cxx2aLoc.isInvalid()) 2153 Cxx2aLoc = S->getBeginLoc(); 2154 for (Stmt *SubStmt : S->children()) { 2155 if (SubStmt && 2156 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2157 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2158 return false; 2159 } 2160 return true; 2161 2162 case Stmt::CXXCatchStmtClass: 2163 // Do not bother checking the language mode (already covered by the 2164 // try block check). 2165 if (!CheckConstexprFunctionStmt( 2166 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts, 2167 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2168 return false; 2169 return true; 2170 2171 default: 2172 if (!isa<Expr>(S)) 2173 break; 2174 2175 // C++1y allows expression-statements. 2176 if (!Cxx1yLoc.isValid()) 2177 Cxx1yLoc = S->getBeginLoc(); 2178 return true; 2179 } 2180 2181 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2182 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2183 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2184 } 2185 return false; 2186 } 2187 2188 /// Check the body for the given constexpr function declaration only contains 2189 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2190 /// 2191 /// \return true if the body is OK, false if we have found or diagnosed a 2192 /// problem. 2193 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2194 Stmt *Body, 2195 Sema::CheckConstexprKind Kind) { 2196 SmallVector<SourceLocation, 4> ReturnStmts; 2197 2198 if (isa<CXXTryStmt>(Body)) { 2199 // C++11 [dcl.constexpr]p3: 2200 // The definition of a constexpr function shall satisfy the following 2201 // constraints: [...] 2202 // - its function-body shall be = delete, = default, or a 2203 // compound-statement 2204 // 2205 // C++11 [dcl.constexpr]p4: 2206 // In the definition of a constexpr constructor, [...] 2207 // - its function-body shall not be a function-try-block; 2208 // 2209 // This restriction is lifted in C++2a, as long as inner statements also 2210 // apply the general constexpr rules. 2211 switch (Kind) { 2212 case Sema::CheckConstexprKind::CheckValid: 2213 if (!SemaRef.getLangOpts().CPlusPlus20) 2214 return false; 2215 break; 2216 2217 case Sema::CheckConstexprKind::Diagnose: 2218 SemaRef.Diag(Body->getBeginLoc(), 2219 !SemaRef.getLangOpts().CPlusPlus20 2220 ? diag::ext_constexpr_function_try_block_cxx20 2221 : diag::warn_cxx17_compat_constexpr_function_try_block) 2222 << isa<CXXConstructorDecl>(Dcl); 2223 break; 2224 } 2225 } 2226 2227 // - its function-body shall be [...] a compound-statement that contains only 2228 // [... list of cases ...] 2229 // 2230 // Note that walking the children here is enough to properly check for 2231 // CompoundStmt and CXXTryStmt body. 2232 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc; 2233 for (Stmt *SubStmt : Body->children()) { 2234 if (SubStmt && 2235 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2236 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2237 return false; 2238 } 2239 2240 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2241 // If this is only valid as an extension, report that we don't satisfy the 2242 // constraints of the current language. 2243 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) || 2244 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2245 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2246 return false; 2247 } else if (Cxx2bLoc.isValid()) { 2248 SemaRef.Diag(Cxx2bLoc, 2249 SemaRef.getLangOpts().CPlusPlus2b 2250 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt 2251 : diag::ext_constexpr_body_invalid_stmt_cxx2b) 2252 << isa<CXXConstructorDecl>(Dcl); 2253 } else if (Cxx2aLoc.isValid()) { 2254 SemaRef.Diag(Cxx2aLoc, 2255 SemaRef.getLangOpts().CPlusPlus20 2256 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2257 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2258 << isa<CXXConstructorDecl>(Dcl); 2259 } else if (Cxx1yLoc.isValid()) { 2260 SemaRef.Diag(Cxx1yLoc, 2261 SemaRef.getLangOpts().CPlusPlus14 2262 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2263 : diag::ext_constexpr_body_invalid_stmt) 2264 << isa<CXXConstructorDecl>(Dcl); 2265 } 2266 2267 if (const CXXConstructorDecl *Constructor 2268 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2269 const CXXRecordDecl *RD = Constructor->getParent(); 2270 // DR1359: 2271 // - every non-variant non-static data member and base class sub-object 2272 // shall be initialized; 2273 // DR1460: 2274 // - if the class is a union having variant members, exactly one of them 2275 // shall be initialized; 2276 if (RD->isUnion()) { 2277 if (Constructor->getNumCtorInitializers() == 0 && 2278 RD->hasVariantMembers()) { 2279 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2280 SemaRef.Diag( 2281 Dcl->getLocation(), 2282 SemaRef.getLangOpts().CPlusPlus20 2283 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2284 : diag::ext_constexpr_union_ctor_no_init); 2285 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2286 return false; 2287 } 2288 } 2289 } else if (!Constructor->isDependentContext() && 2290 !Constructor->isDelegatingConstructor()) { 2291 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2292 2293 // Skip detailed checking if we have enough initializers, and we would 2294 // allow at most one initializer per member. 2295 bool AnyAnonStructUnionMembers = false; 2296 unsigned Fields = 0; 2297 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2298 E = RD->field_end(); I != E; ++I, ++Fields) { 2299 if (I->isAnonymousStructOrUnion()) { 2300 AnyAnonStructUnionMembers = true; 2301 break; 2302 } 2303 } 2304 // DR1460: 2305 // - if the class is a union-like class, but is not a union, for each of 2306 // its anonymous union members having variant members, exactly one of 2307 // them shall be initialized; 2308 if (AnyAnonStructUnionMembers || 2309 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2310 // Check initialization of non-static data members. Base classes are 2311 // always initialized so do not need to be checked. Dependent bases 2312 // might not have initializers in the member initializer list. 2313 llvm::SmallSet<Decl*, 16> Inits; 2314 for (const auto *I: Constructor->inits()) { 2315 if (FieldDecl *FD = I->getMember()) 2316 Inits.insert(FD); 2317 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2318 Inits.insert(ID->chain_begin(), ID->chain_end()); 2319 } 2320 2321 bool Diagnosed = false; 2322 for (auto *I : RD->fields()) 2323 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2324 Kind)) 2325 return false; 2326 } 2327 } 2328 } else { 2329 if (ReturnStmts.empty()) { 2330 // C++1y doesn't require constexpr functions to contain a 'return' 2331 // statement. We still do, unless the return type might be void, because 2332 // otherwise if there's no return statement, the function cannot 2333 // be used in a core constant expression. 2334 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2335 (Dcl->getReturnType()->isVoidType() || 2336 Dcl->getReturnType()->isDependentType()); 2337 switch (Kind) { 2338 case Sema::CheckConstexprKind::Diagnose: 2339 SemaRef.Diag(Dcl->getLocation(), 2340 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2341 : diag::err_constexpr_body_no_return) 2342 << Dcl->isConsteval(); 2343 if (!OK) 2344 return false; 2345 break; 2346 2347 case Sema::CheckConstexprKind::CheckValid: 2348 // The formal requirements don't include this rule in C++14, even 2349 // though the "must be able to produce a constant expression" rules 2350 // still imply it in some cases. 2351 if (!SemaRef.getLangOpts().CPlusPlus14) 2352 return false; 2353 break; 2354 } 2355 } else if (ReturnStmts.size() > 1) { 2356 switch (Kind) { 2357 case Sema::CheckConstexprKind::Diagnose: 2358 SemaRef.Diag( 2359 ReturnStmts.back(), 2360 SemaRef.getLangOpts().CPlusPlus14 2361 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2362 : diag::ext_constexpr_body_multiple_return); 2363 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2364 SemaRef.Diag(ReturnStmts[I], 2365 diag::note_constexpr_body_previous_return); 2366 break; 2367 2368 case Sema::CheckConstexprKind::CheckValid: 2369 if (!SemaRef.getLangOpts().CPlusPlus14) 2370 return false; 2371 break; 2372 } 2373 } 2374 } 2375 2376 // C++11 [dcl.constexpr]p5: 2377 // if no function argument values exist such that the function invocation 2378 // substitution would produce a constant expression, the program is 2379 // ill-formed; no diagnostic required. 2380 // C++11 [dcl.constexpr]p3: 2381 // - every constructor call and implicit conversion used in initializing the 2382 // return value shall be one of those allowed in a constant expression. 2383 // C++11 [dcl.constexpr]p4: 2384 // - every constructor involved in initializing non-static data members and 2385 // base class sub-objects shall be a constexpr constructor. 2386 // 2387 // Note that this rule is distinct from the "requirements for a constexpr 2388 // function", so is not checked in CheckValid mode. 2389 SmallVector<PartialDiagnosticAt, 8> Diags; 2390 if (Kind == Sema::CheckConstexprKind::Diagnose && 2391 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2392 SemaRef.Diag(Dcl->getLocation(), 2393 diag::ext_constexpr_function_never_constant_expr) 2394 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2395 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2396 SemaRef.Diag(Diags[I].first, Diags[I].second); 2397 // Don't return false here: we allow this for compatibility in 2398 // system headers. 2399 } 2400 2401 return true; 2402 } 2403 2404 /// Get the class that is directly named by the current context. This is the 2405 /// class for which an unqualified-id in this scope could name a constructor 2406 /// or destructor. 2407 /// 2408 /// If the scope specifier denotes a class, this will be that class. 2409 /// If the scope specifier is empty, this will be the class whose 2410 /// member-specification we are currently within. Otherwise, there 2411 /// is no such class. 2412 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2413 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2414 2415 if (SS && SS->isInvalid()) 2416 return nullptr; 2417 2418 if (SS && SS->isNotEmpty()) { 2419 DeclContext *DC = computeDeclContext(*SS, true); 2420 return dyn_cast_or_null<CXXRecordDecl>(DC); 2421 } 2422 2423 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2424 } 2425 2426 /// isCurrentClassName - Determine whether the identifier II is the 2427 /// name of the class type currently being defined. In the case of 2428 /// nested classes, this will only return true if II is the name of 2429 /// the innermost class. 2430 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2431 const CXXScopeSpec *SS) { 2432 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2433 return CurDecl && &II == CurDecl->getIdentifier(); 2434 } 2435 2436 /// Determine whether the identifier II is a typo for the name of 2437 /// the class type currently being defined. If so, update it to the identifier 2438 /// that should have been used. 2439 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2440 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2441 2442 if (!getLangOpts().SpellChecking) 2443 return false; 2444 2445 CXXRecordDecl *CurDecl; 2446 if (SS && SS->isSet() && !SS->isInvalid()) { 2447 DeclContext *DC = computeDeclContext(*SS, true); 2448 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2449 } else 2450 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2451 2452 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2453 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2454 < II->getLength()) { 2455 II = CurDecl->getIdentifier(); 2456 return true; 2457 } 2458 2459 return false; 2460 } 2461 2462 /// Determine whether the given class is a base class of the given 2463 /// class, including looking at dependent bases. 2464 static bool findCircularInheritance(const CXXRecordDecl *Class, 2465 const CXXRecordDecl *Current) { 2466 SmallVector<const CXXRecordDecl*, 8> Queue; 2467 2468 Class = Class->getCanonicalDecl(); 2469 while (true) { 2470 for (const auto &I : Current->bases()) { 2471 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2472 if (!Base) 2473 continue; 2474 2475 Base = Base->getDefinition(); 2476 if (!Base) 2477 continue; 2478 2479 if (Base->getCanonicalDecl() == Class) 2480 return true; 2481 2482 Queue.push_back(Base); 2483 } 2484 2485 if (Queue.empty()) 2486 return false; 2487 2488 Current = Queue.pop_back_val(); 2489 } 2490 2491 return false; 2492 } 2493 2494 /// Check the validity of a C++ base class specifier. 2495 /// 2496 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2497 /// and returns NULL otherwise. 2498 CXXBaseSpecifier * 2499 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2500 SourceRange SpecifierRange, 2501 bool Virtual, AccessSpecifier Access, 2502 TypeSourceInfo *TInfo, 2503 SourceLocation EllipsisLoc) { 2504 // In HLSL, unspecified class access is public rather than private. 2505 if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class && 2506 Access == AS_none) 2507 Access = AS_public; 2508 2509 QualType BaseType = TInfo->getType(); 2510 if (BaseType->containsErrors()) { 2511 // Already emitted a diagnostic when parsing the error type. 2512 return nullptr; 2513 } 2514 // C++ [class.union]p1: 2515 // A union shall not have base classes. 2516 if (Class->isUnion()) { 2517 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2518 << SpecifierRange; 2519 return nullptr; 2520 } 2521 2522 if (EllipsisLoc.isValid() && 2523 !TInfo->getType()->containsUnexpandedParameterPack()) { 2524 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2525 << TInfo->getTypeLoc().getSourceRange(); 2526 EllipsisLoc = SourceLocation(); 2527 } 2528 2529 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2530 2531 if (BaseType->isDependentType()) { 2532 // Make sure that we don't have circular inheritance among our dependent 2533 // bases. For non-dependent bases, the check for completeness below handles 2534 // this. 2535 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2536 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2537 ((BaseDecl = BaseDecl->getDefinition()) && 2538 findCircularInheritance(Class, BaseDecl))) { 2539 Diag(BaseLoc, diag::err_circular_inheritance) 2540 << BaseType << Context.getTypeDeclType(Class); 2541 2542 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2543 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2544 << BaseType; 2545 2546 return nullptr; 2547 } 2548 } 2549 2550 // Make sure that we don't make an ill-formed AST where the type of the 2551 // Class is non-dependent and its attached base class specifier is an 2552 // dependent type, which violates invariants in many clang code paths (e.g. 2553 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2554 // explicitly mark the Class decl invalid. The diagnostic was already 2555 // emitted. 2556 if (!Class->getTypeForDecl()->isDependentType()) 2557 Class->setInvalidDecl(); 2558 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2559 Class->getTagKind() == TTK_Class, 2560 Access, TInfo, EllipsisLoc); 2561 } 2562 2563 // Base specifiers must be record types. 2564 if (!BaseType->isRecordType()) { 2565 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2566 return nullptr; 2567 } 2568 2569 // C++ [class.union]p1: 2570 // A union shall not be used as a base class. 2571 if (BaseType->isUnionType()) { 2572 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2573 return nullptr; 2574 } 2575 2576 // For the MS ABI, propagate DLL attributes to base class templates. 2577 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2578 if (Attr *ClassAttr = getDLLAttr(Class)) { 2579 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2580 BaseType->getAsCXXRecordDecl())) { 2581 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2582 BaseLoc); 2583 } 2584 } 2585 } 2586 2587 // C++ [class.derived]p2: 2588 // The class-name in a base-specifier shall not be an incompletely 2589 // defined class. 2590 if (RequireCompleteType(BaseLoc, BaseType, 2591 diag::err_incomplete_base_class, SpecifierRange)) { 2592 Class->setInvalidDecl(); 2593 return nullptr; 2594 } 2595 2596 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2597 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2598 assert(BaseDecl && "Record type has no declaration"); 2599 BaseDecl = BaseDecl->getDefinition(); 2600 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2601 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2602 assert(CXXBaseDecl && "Base type is not a C++ type"); 2603 2604 // Microsoft docs say: 2605 // "If a base-class has a code_seg attribute, derived classes must have the 2606 // same attribute." 2607 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2608 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2609 if ((DerivedCSA || BaseCSA) && 2610 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2611 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2612 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2613 << CXXBaseDecl; 2614 return nullptr; 2615 } 2616 2617 // A class which contains a flexible array member is not suitable for use as a 2618 // base class: 2619 // - If the layout determines that a base comes before another base, 2620 // the flexible array member would index into the subsequent base. 2621 // - If the layout determines that base comes before the derived class, 2622 // the flexible array member would index into the derived class. 2623 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2624 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2625 << CXXBaseDecl->getDeclName(); 2626 return nullptr; 2627 } 2628 2629 // C++ [class]p3: 2630 // If a class is marked final and it appears as a base-type-specifier in 2631 // base-clause, the program is ill-formed. 2632 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2633 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2634 << CXXBaseDecl->getDeclName() 2635 << FA->isSpelledAsSealed(); 2636 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2637 << CXXBaseDecl->getDeclName() << FA->getRange(); 2638 return nullptr; 2639 } 2640 2641 if (BaseDecl->isInvalidDecl()) 2642 Class->setInvalidDecl(); 2643 2644 // Create the base specifier. 2645 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2646 Class->getTagKind() == TTK_Class, 2647 Access, TInfo, EllipsisLoc); 2648 } 2649 2650 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2651 /// one entry in the base class list of a class specifier, for 2652 /// example: 2653 /// class foo : public bar, virtual private baz { 2654 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2655 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2656 const ParsedAttributesView &Attributes, 2657 bool Virtual, AccessSpecifier Access, 2658 ParsedType basetype, SourceLocation BaseLoc, 2659 SourceLocation EllipsisLoc) { 2660 if (!classdecl) 2661 return true; 2662 2663 AdjustDeclIfTemplate(classdecl); 2664 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2665 if (!Class) 2666 return true; 2667 2668 // We haven't yet attached the base specifiers. 2669 Class->setIsParsingBaseSpecifiers(); 2670 2671 // We do not support any C++11 attributes on base-specifiers yet. 2672 // Diagnose any attributes we see. 2673 for (const ParsedAttr &AL : Attributes) { 2674 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2675 continue; 2676 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2677 ? (unsigned)diag::warn_unknown_attribute_ignored 2678 : (unsigned)diag::err_base_specifier_attribute) 2679 << AL << AL.getRange(); 2680 } 2681 2682 TypeSourceInfo *TInfo = nullptr; 2683 GetTypeFromParser(basetype, &TInfo); 2684 2685 if (EllipsisLoc.isInvalid() && 2686 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2687 UPPC_BaseType)) 2688 return true; 2689 2690 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2691 Virtual, Access, TInfo, 2692 EllipsisLoc)) 2693 return BaseSpec; 2694 else 2695 Class->setInvalidDecl(); 2696 2697 return true; 2698 } 2699 2700 /// Use small set to collect indirect bases. As this is only used 2701 /// locally, there's no need to abstract the small size parameter. 2702 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2703 2704 /// Recursively add the bases of Type. Don't add Type itself. 2705 static void 2706 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2707 const QualType &Type) 2708 { 2709 // Even though the incoming type is a base, it might not be 2710 // a class -- it could be a template parm, for instance. 2711 if (auto Rec = Type->getAs<RecordType>()) { 2712 auto Decl = Rec->getAsCXXRecordDecl(); 2713 2714 // Iterate over its bases. 2715 for (const auto &BaseSpec : Decl->bases()) { 2716 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2717 .getUnqualifiedType(); 2718 if (Set.insert(Base).second) 2719 // If we've not already seen it, recurse. 2720 NoteIndirectBases(Context, Set, Base); 2721 } 2722 } 2723 } 2724 2725 /// Performs the actual work of attaching the given base class 2726 /// specifiers to a C++ class. 2727 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2728 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2729 if (Bases.empty()) 2730 return false; 2731 2732 // Used to keep track of which base types we have already seen, so 2733 // that we can properly diagnose redundant direct base types. Note 2734 // that the key is always the unqualified canonical type of the base 2735 // class. 2736 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2737 2738 // Used to track indirect bases so we can see if a direct base is 2739 // ambiguous. 2740 IndirectBaseSet IndirectBaseTypes; 2741 2742 // Copy non-redundant base specifiers into permanent storage. 2743 unsigned NumGoodBases = 0; 2744 bool Invalid = false; 2745 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2746 QualType NewBaseType 2747 = Context.getCanonicalType(Bases[idx]->getType()); 2748 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2749 2750 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2751 if (KnownBase) { 2752 // C++ [class.mi]p3: 2753 // A class shall not be specified as a direct base class of a 2754 // derived class more than once. 2755 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2756 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2757 2758 // Delete the duplicate base class specifier; we're going to 2759 // overwrite its pointer later. 2760 Context.Deallocate(Bases[idx]); 2761 2762 Invalid = true; 2763 } else { 2764 // Okay, add this new base class. 2765 KnownBase = Bases[idx]; 2766 Bases[NumGoodBases++] = Bases[idx]; 2767 2768 if (NewBaseType->isDependentType()) 2769 continue; 2770 // Note this base's direct & indirect bases, if there could be ambiguity. 2771 if (Bases.size() > 1) 2772 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2773 2774 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2775 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2776 if (Class->isInterface() && 2777 (!RD->isInterfaceLike() || 2778 KnownBase->getAccessSpecifier() != AS_public)) { 2779 // The Microsoft extension __interface does not permit bases that 2780 // are not themselves public interfaces. 2781 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2782 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2783 << RD->getSourceRange(); 2784 Invalid = true; 2785 } 2786 if (RD->hasAttr<WeakAttr>()) 2787 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2788 } 2789 } 2790 } 2791 2792 // Attach the remaining base class specifiers to the derived class. 2793 Class->setBases(Bases.data(), NumGoodBases); 2794 2795 // Check that the only base classes that are duplicate are virtual. 2796 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2797 // Check whether this direct base is inaccessible due to ambiguity. 2798 QualType BaseType = Bases[idx]->getType(); 2799 2800 // Skip all dependent types in templates being used as base specifiers. 2801 // Checks below assume that the base specifier is a CXXRecord. 2802 if (BaseType->isDependentType()) 2803 continue; 2804 2805 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2806 .getUnqualifiedType(); 2807 2808 if (IndirectBaseTypes.count(CanonicalBase)) { 2809 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2810 /*DetectVirtual=*/true); 2811 bool found 2812 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2813 assert(found); 2814 (void)found; 2815 2816 if (Paths.isAmbiguous(CanonicalBase)) 2817 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2818 << BaseType << getAmbiguousPathsDisplayString(Paths) 2819 << Bases[idx]->getSourceRange(); 2820 else 2821 assert(Bases[idx]->isVirtual()); 2822 } 2823 2824 // Delete the base class specifier, since its data has been copied 2825 // into the CXXRecordDecl. 2826 Context.Deallocate(Bases[idx]); 2827 } 2828 2829 return Invalid; 2830 } 2831 2832 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2833 /// class, after checking whether there are any duplicate base 2834 /// classes. 2835 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2836 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2837 if (!ClassDecl || Bases.empty()) 2838 return; 2839 2840 AdjustDeclIfTemplate(ClassDecl); 2841 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2842 } 2843 2844 /// Determine whether the type \p Derived is a C++ class that is 2845 /// derived from the type \p Base. 2846 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2847 if (!getLangOpts().CPlusPlus) 2848 return false; 2849 2850 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2851 if (!DerivedRD) 2852 return false; 2853 2854 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2855 if (!BaseRD) 2856 return false; 2857 2858 // If either the base or the derived type is invalid, don't try to 2859 // check whether one is derived from the other. 2860 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2861 return false; 2862 2863 // FIXME: In a modules build, do we need the entire path to be visible for us 2864 // to be able to use the inheritance relationship? 2865 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2866 return false; 2867 2868 return DerivedRD->isDerivedFrom(BaseRD); 2869 } 2870 2871 /// Determine whether the type \p Derived is a C++ class that is 2872 /// derived from the type \p Base. 2873 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2874 CXXBasePaths &Paths) { 2875 if (!getLangOpts().CPlusPlus) 2876 return false; 2877 2878 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2879 if (!DerivedRD) 2880 return false; 2881 2882 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2883 if (!BaseRD) 2884 return false; 2885 2886 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2887 return false; 2888 2889 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2890 } 2891 2892 static void BuildBasePathArray(const CXXBasePath &Path, 2893 CXXCastPath &BasePathArray) { 2894 // We first go backward and check if we have a virtual base. 2895 // FIXME: It would be better if CXXBasePath had the base specifier for 2896 // the nearest virtual base. 2897 unsigned Start = 0; 2898 for (unsigned I = Path.size(); I != 0; --I) { 2899 if (Path[I - 1].Base->isVirtual()) { 2900 Start = I - 1; 2901 break; 2902 } 2903 } 2904 2905 // Now add all bases. 2906 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2907 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2908 } 2909 2910 2911 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2912 CXXCastPath &BasePathArray) { 2913 assert(BasePathArray.empty() && "Base path array must be empty!"); 2914 assert(Paths.isRecordingPaths() && "Must record paths!"); 2915 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2916 } 2917 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2918 /// conversion (where Derived and Base are class types) is 2919 /// well-formed, meaning that the conversion is unambiguous (and 2920 /// that all of the base classes are accessible). Returns true 2921 /// and emits a diagnostic if the code is ill-formed, returns false 2922 /// otherwise. Loc is the location where this routine should point to 2923 /// if there is an error, and Range is the source range to highlight 2924 /// if there is an error. 2925 /// 2926 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2927 /// diagnostic for the respective type of error will be suppressed, but the 2928 /// check for ill-formed code will still be performed. 2929 bool 2930 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2931 unsigned InaccessibleBaseID, 2932 unsigned AmbiguousBaseConvID, 2933 SourceLocation Loc, SourceRange Range, 2934 DeclarationName Name, 2935 CXXCastPath *BasePath, 2936 bool IgnoreAccess) { 2937 // First, determine whether the path from Derived to Base is 2938 // ambiguous. This is slightly more expensive than checking whether 2939 // the Derived to Base conversion exists, because here we need to 2940 // explore multiple paths to determine if there is an ambiguity. 2941 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2942 /*DetectVirtual=*/false); 2943 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2944 if (!DerivationOkay) 2945 return true; 2946 2947 const CXXBasePath *Path = nullptr; 2948 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2949 Path = &Paths.front(); 2950 2951 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2952 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2953 // user to access such bases. 2954 if (!Path && getLangOpts().MSVCCompat) { 2955 for (const CXXBasePath &PossiblePath : Paths) { 2956 if (PossiblePath.size() == 1) { 2957 Path = &PossiblePath; 2958 if (AmbiguousBaseConvID) 2959 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2960 << Base << Derived << Range; 2961 break; 2962 } 2963 } 2964 } 2965 2966 if (Path) { 2967 if (!IgnoreAccess) { 2968 // Check that the base class can be accessed. 2969 switch ( 2970 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2971 case AR_inaccessible: 2972 return true; 2973 case AR_accessible: 2974 case AR_dependent: 2975 case AR_delayed: 2976 break; 2977 } 2978 } 2979 2980 // Build a base path if necessary. 2981 if (BasePath) 2982 ::BuildBasePathArray(*Path, *BasePath); 2983 return false; 2984 } 2985 2986 if (AmbiguousBaseConvID) { 2987 // We know that the derived-to-base conversion is ambiguous, and 2988 // we're going to produce a diagnostic. Perform the derived-to-base 2989 // search just one more time to compute all of the possible paths so 2990 // that we can print them out. This is more expensive than any of 2991 // the previous derived-to-base checks we've done, but at this point 2992 // performance isn't as much of an issue. 2993 Paths.clear(); 2994 Paths.setRecordingPaths(true); 2995 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2996 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2997 (void)StillOkay; 2998 2999 // Build up a textual representation of the ambiguous paths, e.g., 3000 // D -> B -> A, that will be used to illustrate the ambiguous 3001 // conversions in the diagnostic. We only print one of the paths 3002 // to each base class subobject. 3003 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3004 3005 Diag(Loc, AmbiguousBaseConvID) 3006 << Derived << Base << PathDisplayStr << Range << Name; 3007 } 3008 return true; 3009 } 3010 3011 bool 3012 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3013 SourceLocation Loc, SourceRange Range, 3014 CXXCastPath *BasePath, 3015 bool IgnoreAccess) { 3016 return CheckDerivedToBaseConversion( 3017 Derived, Base, diag::err_upcast_to_inaccessible_base, 3018 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 3019 BasePath, IgnoreAccess); 3020 } 3021 3022 3023 /// Builds a string representing ambiguous paths from a 3024 /// specific derived class to different subobjects of the same base 3025 /// class. 3026 /// 3027 /// This function builds a string that can be used in error messages 3028 /// to show the different paths that one can take through the 3029 /// inheritance hierarchy to go from the derived class to different 3030 /// subobjects of a base class. The result looks something like this: 3031 /// @code 3032 /// struct D -> struct B -> struct A 3033 /// struct D -> struct C -> struct A 3034 /// @endcode 3035 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 3036 std::string PathDisplayStr; 3037 std::set<unsigned> DisplayedPaths; 3038 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3039 Path != Paths.end(); ++Path) { 3040 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3041 // We haven't displayed a path to this particular base 3042 // class subobject yet. 3043 PathDisplayStr += "\n "; 3044 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3045 for (CXXBasePath::const_iterator Element = Path->begin(); 3046 Element != Path->end(); ++Element) 3047 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3048 } 3049 } 3050 3051 return PathDisplayStr; 3052 } 3053 3054 //===----------------------------------------------------------------------===// 3055 // C++ class member Handling 3056 //===----------------------------------------------------------------------===// 3057 3058 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3059 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3060 SourceLocation ColonLoc, 3061 const ParsedAttributesView &Attrs) { 3062 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3063 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3064 ASLoc, ColonLoc); 3065 CurContext->addHiddenDecl(ASDecl); 3066 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3067 } 3068 3069 /// CheckOverrideControl - Check C++11 override control semantics. 3070 void Sema::CheckOverrideControl(NamedDecl *D) { 3071 if (D->isInvalidDecl()) 3072 return; 3073 3074 // We only care about "override" and "final" declarations. 3075 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3076 return; 3077 3078 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3079 3080 // We can't check dependent instance methods. 3081 if (MD && MD->isInstance() && 3082 (MD->getParent()->hasAnyDependentBases() || 3083 MD->getType()->isDependentType())) 3084 return; 3085 3086 if (MD && !MD->isVirtual()) { 3087 // If we have a non-virtual method, check if if hides a virtual method. 3088 // (In that case, it's most likely the method has the wrong type.) 3089 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3090 FindHiddenVirtualMethods(MD, OverloadedMethods); 3091 3092 if (!OverloadedMethods.empty()) { 3093 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3094 Diag(OA->getLocation(), 3095 diag::override_keyword_hides_virtual_member_function) 3096 << "override" << (OverloadedMethods.size() > 1); 3097 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3098 Diag(FA->getLocation(), 3099 diag::override_keyword_hides_virtual_member_function) 3100 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3101 << (OverloadedMethods.size() > 1); 3102 } 3103 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3104 MD->setInvalidDecl(); 3105 return; 3106 } 3107 // Fall through into the general case diagnostic. 3108 // FIXME: We might want to attempt typo correction here. 3109 } 3110 3111 if (!MD || !MD->isVirtual()) { 3112 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3113 Diag(OA->getLocation(), 3114 diag::override_keyword_only_allowed_on_virtual_member_functions) 3115 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3116 D->dropAttr<OverrideAttr>(); 3117 } 3118 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3119 Diag(FA->getLocation(), 3120 diag::override_keyword_only_allowed_on_virtual_member_functions) 3121 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3122 << FixItHint::CreateRemoval(FA->getLocation()); 3123 D->dropAttr<FinalAttr>(); 3124 } 3125 return; 3126 } 3127 3128 // C++11 [class.virtual]p5: 3129 // If a function is marked with the virt-specifier override and 3130 // does not override a member function of a base class, the program is 3131 // ill-formed. 3132 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3133 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3134 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3135 << MD->getDeclName(); 3136 } 3137 3138 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3139 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3140 return; 3141 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3142 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3143 return; 3144 3145 SourceLocation Loc = MD->getLocation(); 3146 SourceLocation SpellingLoc = Loc; 3147 if (getSourceManager().isMacroArgExpansion(Loc)) 3148 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3149 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3150 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3151 return; 3152 3153 if (MD->size_overridden_methods() > 0) { 3154 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3155 unsigned DiagID = 3156 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3157 ? DiagInconsistent 3158 : DiagSuggest; 3159 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3160 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3161 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3162 }; 3163 if (isa<CXXDestructorDecl>(MD)) 3164 EmitDiag( 3165 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3166 diag::warn_suggest_destructor_marked_not_override_overriding); 3167 else 3168 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3169 diag::warn_suggest_function_marked_not_override_overriding); 3170 } 3171 } 3172 3173 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3174 /// function overrides a virtual member function marked 'final', according to 3175 /// C++11 [class.virtual]p4. 3176 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3177 const CXXMethodDecl *Old) { 3178 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3179 if (!FA) 3180 return false; 3181 3182 Diag(New->getLocation(), diag::err_final_function_overridden) 3183 << New->getDeclName() 3184 << FA->isSpelledAsSealed(); 3185 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3186 return true; 3187 } 3188 3189 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3190 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3191 // FIXME: Destruction of ObjC lifetime types has side-effects. 3192 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3193 return !RD->isCompleteDefinition() || 3194 !RD->hasTrivialDefaultConstructor() || 3195 !RD->hasTrivialDestructor(); 3196 return false; 3197 } 3198 3199 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3200 ParsedAttributesView::const_iterator Itr = 3201 llvm::find_if(list, [](const ParsedAttr &AL) { 3202 return AL.isDeclspecPropertyAttribute(); 3203 }); 3204 if (Itr != list.end()) 3205 return &*Itr; 3206 return nullptr; 3207 } 3208 3209 // Check if there is a field shadowing. 3210 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3211 DeclarationName FieldName, 3212 const CXXRecordDecl *RD, 3213 bool DeclIsField) { 3214 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3215 return; 3216 3217 // To record a shadowed field in a base 3218 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3219 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3220 CXXBasePath &Path) { 3221 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3222 // Record an ambiguous path directly 3223 if (Bases.find(Base) != Bases.end()) 3224 return true; 3225 for (const auto Field : Base->lookup(FieldName)) { 3226 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3227 Field->getAccess() != AS_private) { 3228 assert(Field->getAccess() != AS_none); 3229 assert(Bases.find(Base) == Bases.end()); 3230 Bases[Base] = Field; 3231 return true; 3232 } 3233 } 3234 return false; 3235 }; 3236 3237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3238 /*DetectVirtual=*/true); 3239 if (!RD->lookupInBases(FieldShadowed, Paths)) 3240 return; 3241 3242 for (const auto &P : Paths) { 3243 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3244 auto It = Bases.find(Base); 3245 // Skip duplicated bases 3246 if (It == Bases.end()) 3247 continue; 3248 auto BaseField = It->second; 3249 assert(BaseField->getAccess() != AS_private); 3250 if (AS_none != 3251 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3252 Diag(Loc, diag::warn_shadow_field) 3253 << FieldName << RD << Base << DeclIsField; 3254 Diag(BaseField->getLocation(), diag::note_shadow_field); 3255 Bases.erase(It); 3256 } 3257 } 3258 } 3259 3260 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3261 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3262 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3263 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3264 /// present (but parsing it has been deferred). 3265 NamedDecl * 3266 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3267 MultiTemplateParamsArg TemplateParameterLists, 3268 Expr *BW, const VirtSpecifiers &VS, 3269 InClassInitStyle InitStyle) { 3270 const DeclSpec &DS = D.getDeclSpec(); 3271 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3272 DeclarationName Name = NameInfo.getName(); 3273 SourceLocation Loc = NameInfo.getLoc(); 3274 3275 // For anonymous bitfields, the location should point to the type. 3276 if (Loc.isInvalid()) 3277 Loc = D.getBeginLoc(); 3278 3279 Expr *BitWidth = static_cast<Expr*>(BW); 3280 3281 assert(isa<CXXRecordDecl>(CurContext)); 3282 assert(!DS.isFriendSpecified()); 3283 3284 bool isFunc = D.isDeclarationOfFunction(); 3285 const ParsedAttr *MSPropertyAttr = 3286 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3287 3288 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3289 // The Microsoft extension __interface only permits public member functions 3290 // and prohibits constructors, destructors, operators, non-public member 3291 // functions, static methods and data members. 3292 unsigned InvalidDecl; 3293 bool ShowDeclName = true; 3294 if (!isFunc && 3295 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3296 InvalidDecl = 0; 3297 else if (!isFunc) 3298 InvalidDecl = 1; 3299 else if (AS != AS_public) 3300 InvalidDecl = 2; 3301 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3302 InvalidDecl = 3; 3303 else switch (Name.getNameKind()) { 3304 case DeclarationName::CXXConstructorName: 3305 InvalidDecl = 4; 3306 ShowDeclName = false; 3307 break; 3308 3309 case DeclarationName::CXXDestructorName: 3310 InvalidDecl = 5; 3311 ShowDeclName = false; 3312 break; 3313 3314 case DeclarationName::CXXOperatorName: 3315 case DeclarationName::CXXConversionFunctionName: 3316 InvalidDecl = 6; 3317 break; 3318 3319 default: 3320 InvalidDecl = 0; 3321 break; 3322 } 3323 3324 if (InvalidDecl) { 3325 if (ShowDeclName) 3326 Diag(Loc, diag::err_invalid_member_in_interface) 3327 << (InvalidDecl-1) << Name; 3328 else 3329 Diag(Loc, diag::err_invalid_member_in_interface) 3330 << (InvalidDecl-1) << ""; 3331 return nullptr; 3332 } 3333 } 3334 3335 // C++ 9.2p6: A member shall not be declared to have automatic storage 3336 // duration (auto, register) or with the extern storage-class-specifier. 3337 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3338 // data members and cannot be applied to names declared const or static, 3339 // and cannot be applied to reference members. 3340 switch (DS.getStorageClassSpec()) { 3341 case DeclSpec::SCS_unspecified: 3342 case DeclSpec::SCS_typedef: 3343 case DeclSpec::SCS_static: 3344 break; 3345 case DeclSpec::SCS_mutable: 3346 if (isFunc) { 3347 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3348 3349 // FIXME: It would be nicer if the keyword was ignored only for this 3350 // declarator. Otherwise we could get follow-up errors. 3351 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3352 } 3353 break; 3354 default: 3355 Diag(DS.getStorageClassSpecLoc(), 3356 diag::err_storageclass_invalid_for_member); 3357 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3358 break; 3359 } 3360 3361 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3362 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3363 !isFunc); 3364 3365 if (DS.hasConstexprSpecifier() && isInstField) { 3366 SemaDiagnosticBuilder B = 3367 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3368 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3369 if (InitStyle == ICIS_NoInit) { 3370 B << 0 << 0; 3371 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3372 B << FixItHint::CreateRemoval(ConstexprLoc); 3373 else { 3374 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3375 D.getMutableDeclSpec().ClearConstexprSpec(); 3376 const char *PrevSpec; 3377 unsigned DiagID; 3378 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3379 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3380 (void)Failed; 3381 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3382 } 3383 } else { 3384 B << 1; 3385 const char *PrevSpec; 3386 unsigned DiagID; 3387 if (D.getMutableDeclSpec().SetStorageClassSpec( 3388 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3389 Context.getPrintingPolicy())) { 3390 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3391 "This is the only DeclSpec that should fail to be applied"); 3392 B << 1; 3393 } else { 3394 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3395 isInstField = false; 3396 } 3397 } 3398 } 3399 3400 NamedDecl *Member; 3401 if (isInstField) { 3402 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3403 3404 // Data members must have identifiers for names. 3405 if (!Name.isIdentifier()) { 3406 Diag(Loc, diag::err_bad_variable_name) 3407 << Name; 3408 return nullptr; 3409 } 3410 3411 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3412 3413 // Member field could not be with "template" keyword. 3414 // So TemplateParameterLists should be empty in this case. 3415 if (TemplateParameterLists.size()) { 3416 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3417 if (TemplateParams->size()) { 3418 // There is no such thing as a member field template. 3419 Diag(D.getIdentifierLoc(), diag::err_template_member) 3420 << II 3421 << SourceRange(TemplateParams->getTemplateLoc(), 3422 TemplateParams->getRAngleLoc()); 3423 } else { 3424 // There is an extraneous 'template<>' for this member. 3425 Diag(TemplateParams->getTemplateLoc(), 3426 diag::err_template_member_noparams) 3427 << II 3428 << SourceRange(TemplateParams->getTemplateLoc(), 3429 TemplateParams->getRAngleLoc()); 3430 } 3431 return nullptr; 3432 } 3433 3434 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 3435 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments) 3436 << II 3437 << SourceRange(D.getName().TemplateId->LAngleLoc, 3438 D.getName().TemplateId->RAngleLoc) 3439 << D.getName().TemplateId->LAngleLoc; 3440 D.SetIdentifier(II, Loc); 3441 } 3442 3443 if (SS.isSet() && !SS.isInvalid()) { 3444 // The user provided a superfluous scope specifier inside a class 3445 // definition: 3446 // 3447 // class X { 3448 // int X::member; 3449 // }; 3450 if (DeclContext *DC = computeDeclContext(SS, false)) 3451 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3452 D.getName().getKind() == 3453 UnqualifiedIdKind::IK_TemplateId); 3454 else 3455 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3456 << Name << SS.getRange(); 3457 3458 SS.clear(); 3459 } 3460 3461 if (MSPropertyAttr) { 3462 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3463 BitWidth, InitStyle, AS, *MSPropertyAttr); 3464 if (!Member) 3465 return nullptr; 3466 isInstField = false; 3467 } else { 3468 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3469 BitWidth, InitStyle, AS); 3470 if (!Member) 3471 return nullptr; 3472 } 3473 3474 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3475 } else { 3476 Member = HandleDeclarator(S, D, TemplateParameterLists); 3477 if (!Member) 3478 return nullptr; 3479 3480 // Non-instance-fields can't have a bitfield. 3481 if (BitWidth) { 3482 if (Member->isInvalidDecl()) { 3483 // don't emit another diagnostic. 3484 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3485 // C++ 9.6p3: A bit-field shall not be a static member. 3486 // "static member 'A' cannot be a bit-field" 3487 Diag(Loc, diag::err_static_not_bitfield) 3488 << Name << BitWidth->getSourceRange(); 3489 } else if (isa<TypedefDecl>(Member)) { 3490 // "typedef member 'x' cannot be a bit-field" 3491 Diag(Loc, diag::err_typedef_not_bitfield) 3492 << Name << BitWidth->getSourceRange(); 3493 } else { 3494 // A function typedef ("typedef int f(); f a;"). 3495 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3496 Diag(Loc, diag::err_not_integral_type_bitfield) 3497 << Name << cast<ValueDecl>(Member)->getType() 3498 << BitWidth->getSourceRange(); 3499 } 3500 3501 BitWidth = nullptr; 3502 Member->setInvalidDecl(); 3503 } 3504 3505 NamedDecl *NonTemplateMember = Member; 3506 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3507 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3508 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3509 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3510 3511 Member->setAccess(AS); 3512 3513 // If we have declared a member function template or static data member 3514 // template, set the access of the templated declaration as well. 3515 if (NonTemplateMember != Member) 3516 NonTemplateMember->setAccess(AS); 3517 3518 // C++ [temp.deduct.guide]p3: 3519 // A deduction guide [...] for a member class template [shall be 3520 // declared] with the same access [as the template]. 3521 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3522 auto *TD = DG->getDeducedTemplate(); 3523 // Access specifiers are only meaningful if both the template and the 3524 // deduction guide are from the same scope. 3525 if (AS != TD->getAccess() && 3526 TD->getDeclContext()->getRedeclContext()->Equals( 3527 DG->getDeclContext()->getRedeclContext())) { 3528 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3529 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3530 << TD->getAccess(); 3531 const AccessSpecDecl *LastAccessSpec = nullptr; 3532 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3533 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3534 LastAccessSpec = AccessSpec; 3535 } 3536 assert(LastAccessSpec && "differing access with no access specifier"); 3537 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3538 << AS; 3539 } 3540 } 3541 } 3542 3543 if (VS.isOverrideSpecified()) 3544 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3545 AttributeCommonInfo::AS_Keyword)); 3546 if (VS.isFinalSpecified()) 3547 Member->addAttr(FinalAttr::Create( 3548 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3549 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3550 3551 if (VS.getLastLocation().isValid()) { 3552 // Update the end location of a method that has a virt-specifiers. 3553 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3554 MD->setRangeEnd(VS.getLastLocation()); 3555 } 3556 3557 CheckOverrideControl(Member); 3558 3559 assert((Name || isInstField) && "No identifier for non-field ?"); 3560 3561 if (isInstField) { 3562 FieldDecl *FD = cast<FieldDecl>(Member); 3563 FieldCollector->Add(FD); 3564 3565 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3566 // Remember all explicit private FieldDecls that have a name, no side 3567 // effects and are not part of a dependent type declaration. 3568 if (!FD->isImplicit() && FD->getDeclName() && 3569 FD->getAccess() == AS_private && 3570 !FD->hasAttr<UnusedAttr>() && 3571 !FD->getParent()->isDependentContext() && 3572 !InitializationHasSideEffects(*FD)) 3573 UnusedPrivateFields.insert(FD); 3574 } 3575 } 3576 3577 return Member; 3578 } 3579 3580 namespace { 3581 class UninitializedFieldVisitor 3582 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3583 Sema &S; 3584 // List of Decls to generate a warning on. Also remove Decls that become 3585 // initialized. 3586 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3587 // List of base classes of the record. Classes are removed after their 3588 // initializers. 3589 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3590 // Vector of decls to be removed from the Decl set prior to visiting the 3591 // nodes. These Decls may have been initialized in the prior initializer. 3592 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3593 // If non-null, add a note to the warning pointing back to the constructor. 3594 const CXXConstructorDecl *Constructor; 3595 // Variables to hold state when processing an initializer list. When 3596 // InitList is true, special case initialization of FieldDecls matching 3597 // InitListFieldDecl. 3598 bool InitList; 3599 FieldDecl *InitListFieldDecl; 3600 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3601 3602 public: 3603 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3604 UninitializedFieldVisitor(Sema &S, 3605 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3606 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3607 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3608 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3609 3610 // Returns true if the use of ME is not an uninitialized use. 3611 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3612 bool CheckReferenceOnly) { 3613 llvm::SmallVector<FieldDecl*, 4> Fields; 3614 bool ReferenceField = false; 3615 while (ME) { 3616 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3617 if (!FD) 3618 return false; 3619 Fields.push_back(FD); 3620 if (FD->getType()->isReferenceType()) 3621 ReferenceField = true; 3622 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3623 } 3624 3625 // Binding a reference to an uninitialized field is not an 3626 // uninitialized use. 3627 if (CheckReferenceOnly && !ReferenceField) 3628 return true; 3629 3630 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3631 // Discard the first field since it is the field decl that is being 3632 // initialized. 3633 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) 3634 UsedFieldIndex.push_back(FD->getFieldIndex()); 3635 3636 for (auto UsedIter = UsedFieldIndex.begin(), 3637 UsedEnd = UsedFieldIndex.end(), 3638 OrigIter = InitFieldIndex.begin(), 3639 OrigEnd = InitFieldIndex.end(); 3640 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3641 if (*UsedIter < *OrigIter) 3642 return true; 3643 if (*UsedIter > *OrigIter) 3644 break; 3645 } 3646 3647 return false; 3648 } 3649 3650 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3651 bool AddressOf) { 3652 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3653 return; 3654 3655 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3656 // or union. 3657 MemberExpr *FieldME = ME; 3658 3659 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3660 3661 Expr *Base = ME; 3662 while (MemberExpr *SubME = 3663 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3664 3665 if (isa<VarDecl>(SubME->getMemberDecl())) 3666 return; 3667 3668 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3669 if (!FD->isAnonymousStructOrUnion()) 3670 FieldME = SubME; 3671 3672 if (!FieldME->getType().isPODType(S.Context)) 3673 AllPODFields = false; 3674 3675 Base = SubME->getBase(); 3676 } 3677 3678 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3679 Visit(Base); 3680 return; 3681 } 3682 3683 if (AddressOf && AllPODFields) 3684 return; 3685 3686 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3687 3688 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3689 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3690 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3691 } 3692 3693 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3694 QualType T = BaseCast->getType(); 3695 if (T->isPointerType() && 3696 BaseClasses.count(T->getPointeeType())) { 3697 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3698 << T->getPointeeType() << FoundVD; 3699 } 3700 } 3701 } 3702 3703 if (!Decls.count(FoundVD)) 3704 return; 3705 3706 const bool IsReference = FoundVD->getType()->isReferenceType(); 3707 3708 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3709 // Special checking for initializer lists. 3710 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3711 return; 3712 } 3713 } else { 3714 // Prevent double warnings on use of unbounded references. 3715 if (CheckReferenceOnly && !IsReference) 3716 return; 3717 } 3718 3719 unsigned diag = IsReference 3720 ? diag::warn_reference_field_is_uninit 3721 : diag::warn_field_is_uninit; 3722 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3723 if (Constructor) 3724 S.Diag(Constructor->getLocation(), 3725 diag::note_uninit_in_this_constructor) 3726 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3727 3728 } 3729 3730 void HandleValue(Expr *E, bool AddressOf) { 3731 E = E->IgnoreParens(); 3732 3733 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3734 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3735 AddressOf /*AddressOf*/); 3736 return; 3737 } 3738 3739 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3740 Visit(CO->getCond()); 3741 HandleValue(CO->getTrueExpr(), AddressOf); 3742 HandleValue(CO->getFalseExpr(), AddressOf); 3743 return; 3744 } 3745 3746 if (BinaryConditionalOperator *BCO = 3747 dyn_cast<BinaryConditionalOperator>(E)) { 3748 Visit(BCO->getCond()); 3749 HandleValue(BCO->getFalseExpr(), AddressOf); 3750 return; 3751 } 3752 3753 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3754 HandleValue(OVE->getSourceExpr(), AddressOf); 3755 return; 3756 } 3757 3758 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3759 switch (BO->getOpcode()) { 3760 default: 3761 break; 3762 case(BO_PtrMemD): 3763 case(BO_PtrMemI): 3764 HandleValue(BO->getLHS(), AddressOf); 3765 Visit(BO->getRHS()); 3766 return; 3767 case(BO_Comma): 3768 Visit(BO->getLHS()); 3769 HandleValue(BO->getRHS(), AddressOf); 3770 return; 3771 } 3772 } 3773 3774 Visit(E); 3775 } 3776 3777 void CheckInitListExpr(InitListExpr *ILE) { 3778 InitFieldIndex.push_back(0); 3779 for (auto Child : ILE->children()) { 3780 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3781 CheckInitListExpr(SubList); 3782 } else { 3783 Visit(Child); 3784 } 3785 ++InitFieldIndex.back(); 3786 } 3787 InitFieldIndex.pop_back(); 3788 } 3789 3790 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3791 FieldDecl *Field, const Type *BaseClass) { 3792 // Remove Decls that may have been initialized in the previous 3793 // initializer. 3794 for (ValueDecl* VD : DeclsToRemove) 3795 Decls.erase(VD); 3796 DeclsToRemove.clear(); 3797 3798 Constructor = FieldConstructor; 3799 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3800 3801 if (ILE && Field) { 3802 InitList = true; 3803 InitListFieldDecl = Field; 3804 InitFieldIndex.clear(); 3805 CheckInitListExpr(ILE); 3806 } else { 3807 InitList = false; 3808 Visit(E); 3809 } 3810 3811 if (Field) 3812 Decls.erase(Field); 3813 if (BaseClass) 3814 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3815 } 3816 3817 void VisitMemberExpr(MemberExpr *ME) { 3818 // All uses of unbounded reference fields will warn. 3819 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3820 } 3821 3822 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3823 if (E->getCastKind() == CK_LValueToRValue) { 3824 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3825 return; 3826 } 3827 3828 Inherited::VisitImplicitCastExpr(E); 3829 } 3830 3831 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3832 if (E->getConstructor()->isCopyConstructor()) { 3833 Expr *ArgExpr = E->getArg(0); 3834 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3835 if (ILE->getNumInits() == 1) 3836 ArgExpr = ILE->getInit(0); 3837 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3838 if (ICE->getCastKind() == CK_NoOp) 3839 ArgExpr = ICE->getSubExpr(); 3840 HandleValue(ArgExpr, false /*AddressOf*/); 3841 return; 3842 } 3843 Inherited::VisitCXXConstructExpr(E); 3844 } 3845 3846 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3847 Expr *Callee = E->getCallee(); 3848 if (isa<MemberExpr>(Callee)) { 3849 HandleValue(Callee, false /*AddressOf*/); 3850 for (auto Arg : E->arguments()) 3851 Visit(Arg); 3852 return; 3853 } 3854 3855 Inherited::VisitCXXMemberCallExpr(E); 3856 } 3857 3858 void VisitCallExpr(CallExpr *E) { 3859 // Treat std::move as a use. 3860 if (E->isCallToStdMove()) { 3861 HandleValue(E->getArg(0), /*AddressOf=*/false); 3862 return; 3863 } 3864 3865 Inherited::VisitCallExpr(E); 3866 } 3867 3868 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3869 Expr *Callee = E->getCallee(); 3870 3871 if (isa<UnresolvedLookupExpr>(Callee)) 3872 return Inherited::VisitCXXOperatorCallExpr(E); 3873 3874 Visit(Callee); 3875 for (auto Arg : E->arguments()) 3876 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3877 } 3878 3879 void VisitBinaryOperator(BinaryOperator *E) { 3880 // If a field assignment is detected, remove the field from the 3881 // uninitiailized field set. 3882 if (E->getOpcode() == BO_Assign) 3883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3884 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3885 if (!FD->getType()->isReferenceType()) 3886 DeclsToRemove.push_back(FD); 3887 3888 if (E->isCompoundAssignmentOp()) { 3889 HandleValue(E->getLHS(), false /*AddressOf*/); 3890 Visit(E->getRHS()); 3891 return; 3892 } 3893 3894 Inherited::VisitBinaryOperator(E); 3895 } 3896 3897 void VisitUnaryOperator(UnaryOperator *E) { 3898 if (E->isIncrementDecrementOp()) { 3899 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3900 return; 3901 } 3902 if (E->getOpcode() == UO_AddrOf) { 3903 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3904 HandleValue(ME->getBase(), true /*AddressOf*/); 3905 return; 3906 } 3907 } 3908 3909 Inherited::VisitUnaryOperator(E); 3910 } 3911 }; 3912 3913 // Diagnose value-uses of fields to initialize themselves, e.g. 3914 // foo(foo) 3915 // where foo is not also a parameter to the constructor. 3916 // Also diagnose across field uninitialized use such as 3917 // x(y), y(x) 3918 // TODO: implement -Wuninitialized and fold this into that framework. 3919 static void DiagnoseUninitializedFields( 3920 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3921 3922 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3923 Constructor->getLocation())) { 3924 return; 3925 } 3926 3927 if (Constructor->isInvalidDecl()) 3928 return; 3929 3930 const CXXRecordDecl *RD = Constructor->getParent(); 3931 3932 if (RD->isDependentContext()) 3933 return; 3934 3935 // Holds fields that are uninitialized. 3936 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3937 3938 // At the beginning, all fields are uninitialized. 3939 for (auto *I : RD->decls()) { 3940 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3941 UninitializedFields.insert(FD); 3942 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3943 UninitializedFields.insert(IFD->getAnonField()); 3944 } 3945 } 3946 3947 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3948 for (auto I : RD->bases()) 3949 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3950 3951 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3952 return; 3953 3954 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3955 UninitializedFields, 3956 UninitializedBaseClasses); 3957 3958 for (const auto *FieldInit : Constructor->inits()) { 3959 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3960 break; 3961 3962 Expr *InitExpr = FieldInit->getInit(); 3963 if (!InitExpr) 3964 continue; 3965 3966 if (CXXDefaultInitExpr *Default = 3967 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3968 InitExpr = Default->getExpr(); 3969 if (!InitExpr) 3970 continue; 3971 // In class initializers will point to the constructor. 3972 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3973 FieldInit->getAnyMember(), 3974 FieldInit->getBaseClass()); 3975 } else { 3976 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3977 FieldInit->getAnyMember(), 3978 FieldInit->getBaseClass()); 3979 } 3980 } 3981 } 3982 } // namespace 3983 3984 /// Enter a new C++ default initializer scope. After calling this, the 3985 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3986 /// parsing or instantiating the initializer failed. 3987 void Sema::ActOnStartCXXInClassMemberInitializer() { 3988 // Create a synthetic function scope to represent the call to the constructor 3989 // that notionally surrounds a use of this initializer. 3990 PushFunctionScope(); 3991 } 3992 3993 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3994 if (!D.isFunctionDeclarator()) 3995 return; 3996 auto &FTI = D.getFunctionTypeInfo(); 3997 if (!FTI.Params) 3998 return; 3999 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 4000 FTI.NumParams)) { 4001 auto *ParamDecl = cast<NamedDecl>(Param.Param); 4002 if (ParamDecl->getDeclName()) 4003 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 4004 } 4005 } 4006 4007 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 4008 return ActOnRequiresClause(ConstraintExpr); 4009 } 4010 4011 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 4012 if (ConstraintExpr.isInvalid()) 4013 return ExprError(); 4014 4015 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 4016 if (ConstraintExpr.isInvalid()) 4017 return ExprError(); 4018 4019 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 4020 UPPC_RequiresClause)) 4021 return ExprError(); 4022 4023 return ConstraintExpr; 4024 } 4025 4026 /// This is invoked after parsing an in-class initializer for a 4027 /// non-static C++ class member, and after instantiating an in-class initializer 4028 /// in a class template. Such actions are deferred until the class is complete. 4029 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 4030 SourceLocation InitLoc, 4031 Expr *InitExpr) { 4032 // Pop the notional constructor scope we created earlier. 4033 PopFunctionScopeInfo(nullptr, D); 4034 4035 FieldDecl *FD = dyn_cast<FieldDecl>(D); 4036 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 4037 "must set init style when field is created"); 4038 4039 if (!InitExpr) { 4040 D->setInvalidDecl(); 4041 if (FD) 4042 FD->removeInClassInitializer(); 4043 return; 4044 } 4045 4046 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4047 FD->setInvalidDecl(); 4048 FD->removeInClassInitializer(); 4049 return; 4050 } 4051 4052 ExprResult Init = InitExpr; 4053 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4054 InitializedEntity Entity = 4055 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4056 InitializationKind Kind = 4057 FD->getInClassInitStyle() == ICIS_ListInit 4058 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4059 InitExpr->getBeginLoc(), 4060 InitExpr->getEndLoc()) 4061 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4062 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4063 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4064 if (Init.isInvalid()) { 4065 FD->setInvalidDecl(); 4066 return; 4067 } 4068 } 4069 4070 // C++11 [class.base.init]p7: 4071 // The initialization of each base and member constitutes a 4072 // full-expression. 4073 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4074 if (Init.isInvalid()) { 4075 FD->setInvalidDecl(); 4076 return; 4077 } 4078 4079 InitExpr = Init.get(); 4080 4081 FD->setInClassInitializer(InitExpr); 4082 } 4083 4084 /// Find the direct and/or virtual base specifiers that 4085 /// correspond to the given base type, for use in base initialization 4086 /// within a constructor. 4087 static bool FindBaseInitializer(Sema &SemaRef, 4088 CXXRecordDecl *ClassDecl, 4089 QualType BaseType, 4090 const CXXBaseSpecifier *&DirectBaseSpec, 4091 const CXXBaseSpecifier *&VirtualBaseSpec) { 4092 // First, check for a direct base class. 4093 DirectBaseSpec = nullptr; 4094 for (const auto &Base : ClassDecl->bases()) { 4095 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4096 // We found a direct base of this type. That's what we're 4097 // initializing. 4098 DirectBaseSpec = &Base; 4099 break; 4100 } 4101 } 4102 4103 // Check for a virtual base class. 4104 // FIXME: We might be able to short-circuit this if we know in advance that 4105 // there are no virtual bases. 4106 VirtualBaseSpec = nullptr; 4107 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4108 // We haven't found a base yet; search the class hierarchy for a 4109 // virtual base class. 4110 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4111 /*DetectVirtual=*/false); 4112 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4113 SemaRef.Context.getTypeDeclType(ClassDecl), 4114 BaseType, Paths)) { 4115 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4116 Path != Paths.end(); ++Path) { 4117 if (Path->back().Base->isVirtual()) { 4118 VirtualBaseSpec = Path->back().Base; 4119 break; 4120 } 4121 } 4122 } 4123 } 4124 4125 return DirectBaseSpec || VirtualBaseSpec; 4126 } 4127 4128 /// Handle a C++ member initializer using braced-init-list syntax. 4129 MemInitResult 4130 Sema::ActOnMemInitializer(Decl *ConstructorD, 4131 Scope *S, 4132 CXXScopeSpec &SS, 4133 IdentifierInfo *MemberOrBase, 4134 ParsedType TemplateTypeTy, 4135 const DeclSpec &DS, 4136 SourceLocation IdLoc, 4137 Expr *InitList, 4138 SourceLocation EllipsisLoc) { 4139 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4140 DS, IdLoc, InitList, 4141 EllipsisLoc); 4142 } 4143 4144 /// Handle a C++ member initializer using parentheses syntax. 4145 MemInitResult 4146 Sema::ActOnMemInitializer(Decl *ConstructorD, 4147 Scope *S, 4148 CXXScopeSpec &SS, 4149 IdentifierInfo *MemberOrBase, 4150 ParsedType TemplateTypeTy, 4151 const DeclSpec &DS, 4152 SourceLocation IdLoc, 4153 SourceLocation LParenLoc, 4154 ArrayRef<Expr *> Args, 4155 SourceLocation RParenLoc, 4156 SourceLocation EllipsisLoc) { 4157 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4158 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4159 DS, IdLoc, List, EllipsisLoc); 4160 } 4161 4162 namespace { 4163 4164 // Callback to only accept typo corrections that can be a valid C++ member 4165 // initializer: either a non-static field member or a base class. 4166 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4167 public: 4168 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4169 : ClassDecl(ClassDecl) {} 4170 4171 bool ValidateCandidate(const TypoCorrection &candidate) override { 4172 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4173 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4174 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4175 return isa<TypeDecl>(ND); 4176 } 4177 return false; 4178 } 4179 4180 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4181 return std::make_unique<MemInitializerValidatorCCC>(*this); 4182 } 4183 4184 private: 4185 CXXRecordDecl *ClassDecl; 4186 }; 4187 4188 } 4189 4190 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4191 CXXScopeSpec &SS, 4192 ParsedType TemplateTypeTy, 4193 IdentifierInfo *MemberOrBase) { 4194 if (SS.getScopeRep() || TemplateTypeTy) 4195 return nullptr; 4196 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4197 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4198 return cast<ValueDecl>(D); 4199 return nullptr; 4200 } 4201 4202 /// Handle a C++ member initializer. 4203 MemInitResult 4204 Sema::BuildMemInitializer(Decl *ConstructorD, 4205 Scope *S, 4206 CXXScopeSpec &SS, 4207 IdentifierInfo *MemberOrBase, 4208 ParsedType TemplateTypeTy, 4209 const DeclSpec &DS, 4210 SourceLocation IdLoc, 4211 Expr *Init, 4212 SourceLocation EllipsisLoc) { 4213 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4214 /*RecoverUncorrectedTypos=*/true); 4215 if (!Res.isUsable()) 4216 return true; 4217 Init = Res.get(); 4218 4219 if (!ConstructorD) 4220 return true; 4221 4222 AdjustDeclIfTemplate(ConstructorD); 4223 4224 CXXConstructorDecl *Constructor 4225 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4226 if (!Constructor) { 4227 // The user wrote a constructor initializer on a function that is 4228 // not a C++ constructor. Ignore the error for now, because we may 4229 // have more member initializers coming; we'll diagnose it just 4230 // once in ActOnMemInitializers. 4231 return true; 4232 } 4233 4234 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4235 4236 // C++ [class.base.init]p2: 4237 // Names in a mem-initializer-id are looked up in the scope of the 4238 // constructor's class and, if not found in that scope, are looked 4239 // up in the scope containing the constructor's definition. 4240 // [Note: if the constructor's class contains a member with the 4241 // same name as a direct or virtual base class of the class, a 4242 // mem-initializer-id naming the member or base class and composed 4243 // of a single identifier refers to the class member. A 4244 // mem-initializer-id for the hidden base class may be specified 4245 // using a qualified name. ] 4246 4247 // Look for a member, first. 4248 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4249 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4250 if (EllipsisLoc.isValid()) 4251 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4252 << MemberOrBase 4253 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4254 4255 return BuildMemberInitializer(Member, Init, IdLoc); 4256 } 4257 // It didn't name a member, so see if it names a class. 4258 QualType BaseType; 4259 TypeSourceInfo *TInfo = nullptr; 4260 4261 if (TemplateTypeTy) { 4262 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4263 if (BaseType.isNull()) 4264 return true; 4265 } else if (DS.getTypeSpecType() == TST_decltype) { 4266 BaseType = BuildDecltypeType(DS.getRepAsExpr()); 4267 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4268 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4269 return true; 4270 } else { 4271 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4272 LookupParsedName(R, S, &SS); 4273 4274 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4275 if (!TyD) { 4276 if (R.isAmbiguous()) return true; 4277 4278 // We don't want access-control diagnostics here. 4279 R.suppressDiagnostics(); 4280 4281 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4282 bool NotUnknownSpecialization = false; 4283 DeclContext *DC = computeDeclContext(SS, false); 4284 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4285 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4286 4287 if (!NotUnknownSpecialization) { 4288 // When the scope specifier can refer to a member of an unknown 4289 // specialization, we take it as a type name. 4290 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4291 SS.getWithLocInContext(Context), 4292 *MemberOrBase, IdLoc); 4293 if (BaseType.isNull()) 4294 return true; 4295 4296 TInfo = Context.CreateTypeSourceInfo(BaseType); 4297 DependentNameTypeLoc TL = 4298 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4299 if (!TL.isNull()) { 4300 TL.setNameLoc(IdLoc); 4301 TL.setElaboratedKeywordLoc(SourceLocation()); 4302 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4303 } 4304 4305 R.clear(); 4306 R.setLookupName(MemberOrBase); 4307 } 4308 } 4309 4310 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) { 4311 auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>(); 4312 if (UnqualifiedBase) { 4313 Diag(IdLoc, diag::ext_unqualified_base_class) 4314 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4315 BaseType = UnqualifiedBase->getInjectedClassNameSpecialization(); 4316 } 4317 } 4318 4319 // If no results were found, try to correct typos. 4320 TypoCorrection Corr; 4321 MemInitializerValidatorCCC CCC(ClassDecl); 4322 if (R.empty() && BaseType.isNull() && 4323 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4324 CCC, CTK_ErrorRecovery, ClassDecl))) { 4325 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4326 // We have found a non-static data member with a similar 4327 // name to what was typed; complain and initialize that 4328 // member. 4329 diagnoseTypo(Corr, 4330 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4331 << MemberOrBase << true); 4332 return BuildMemberInitializer(Member, Init, IdLoc); 4333 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4334 const CXXBaseSpecifier *DirectBaseSpec; 4335 const CXXBaseSpecifier *VirtualBaseSpec; 4336 if (FindBaseInitializer(*this, ClassDecl, 4337 Context.getTypeDeclType(Type), 4338 DirectBaseSpec, VirtualBaseSpec)) { 4339 // We have found a direct or virtual base class with a 4340 // similar name to what was typed; complain and initialize 4341 // that base class. 4342 diagnoseTypo(Corr, 4343 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4344 << MemberOrBase << false, 4345 PDiag() /*Suppress note, we provide our own.*/); 4346 4347 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4348 : VirtualBaseSpec; 4349 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4350 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4351 4352 TyD = Type; 4353 } 4354 } 4355 } 4356 4357 if (!TyD && BaseType.isNull()) { 4358 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4359 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4360 return true; 4361 } 4362 } 4363 4364 if (BaseType.isNull()) { 4365 BaseType = Context.getTypeDeclType(TyD); 4366 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4367 if (SS.isSet()) { 4368 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4369 BaseType); 4370 TInfo = Context.CreateTypeSourceInfo(BaseType); 4371 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4372 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4373 TL.setElaboratedKeywordLoc(SourceLocation()); 4374 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4375 } 4376 } 4377 } 4378 4379 if (!TInfo) 4380 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4381 4382 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4383 } 4384 4385 MemInitResult 4386 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4387 SourceLocation IdLoc) { 4388 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4389 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4390 assert((DirectMember || IndirectMember) && 4391 "Member must be a FieldDecl or IndirectFieldDecl"); 4392 4393 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4394 return true; 4395 4396 if (Member->isInvalidDecl()) 4397 return true; 4398 4399 MultiExprArg Args; 4400 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4401 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4402 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4403 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4404 } else { 4405 // Template instantiation doesn't reconstruct ParenListExprs for us. 4406 Args = Init; 4407 } 4408 4409 SourceRange InitRange = Init->getSourceRange(); 4410 4411 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4412 // Can't check initialization for a member of dependent type or when 4413 // any of the arguments are type-dependent expressions. 4414 DiscardCleanupsInEvaluationContext(); 4415 } else { 4416 bool InitList = false; 4417 if (isa<InitListExpr>(Init)) { 4418 InitList = true; 4419 Args = Init; 4420 } 4421 4422 // Initialize the member. 4423 InitializedEntity MemberEntity = 4424 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4425 : InitializedEntity::InitializeMember(IndirectMember, 4426 nullptr); 4427 InitializationKind Kind = 4428 InitList ? InitializationKind::CreateDirectList( 4429 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4430 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4431 InitRange.getEnd()); 4432 4433 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4434 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4435 nullptr); 4436 if (!MemberInit.isInvalid()) { 4437 // C++11 [class.base.init]p7: 4438 // The initialization of each base and member constitutes a 4439 // full-expression. 4440 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4441 /*DiscardedValue*/ false); 4442 } 4443 4444 if (MemberInit.isInvalid()) { 4445 // Args were sensible expressions but we couldn't initialize the member 4446 // from them. Preserve them in a RecoveryExpr instead. 4447 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4448 Member->getType()) 4449 .get(); 4450 if (!Init) 4451 return true; 4452 } else { 4453 Init = MemberInit.get(); 4454 } 4455 } 4456 4457 if (DirectMember) { 4458 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4459 InitRange.getBegin(), Init, 4460 InitRange.getEnd()); 4461 } else { 4462 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4463 InitRange.getBegin(), Init, 4464 InitRange.getEnd()); 4465 } 4466 } 4467 4468 MemInitResult 4469 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4470 CXXRecordDecl *ClassDecl) { 4471 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4472 if (!LangOpts.CPlusPlus11) 4473 return Diag(NameLoc, diag::err_delegating_ctor) 4474 << TInfo->getTypeLoc().getLocalSourceRange(); 4475 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4476 4477 bool InitList = true; 4478 MultiExprArg Args = Init; 4479 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4480 InitList = false; 4481 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4482 } 4483 4484 SourceRange InitRange = Init->getSourceRange(); 4485 // Initialize the object. 4486 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4487 QualType(ClassDecl->getTypeForDecl(), 0)); 4488 InitializationKind Kind = 4489 InitList ? InitializationKind::CreateDirectList( 4490 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4491 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4492 InitRange.getEnd()); 4493 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4494 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4495 Args, nullptr); 4496 if (!DelegationInit.isInvalid()) { 4497 assert((DelegationInit.get()->containsErrors() || 4498 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4499 "Delegating constructor with no target?"); 4500 4501 // C++11 [class.base.init]p7: 4502 // The initialization of each base and member constitutes a 4503 // full-expression. 4504 DelegationInit = ActOnFinishFullExpr( 4505 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4506 } 4507 4508 if (DelegationInit.isInvalid()) { 4509 DelegationInit = 4510 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4511 QualType(ClassDecl->getTypeForDecl(), 0)); 4512 if (DelegationInit.isInvalid()) 4513 return true; 4514 } else { 4515 // If we are in a dependent context, template instantiation will 4516 // perform this type-checking again. Just save the arguments that we 4517 // received in a ParenListExpr. 4518 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4519 // of the information that we have about the base 4520 // initializer. However, deconstructing the ASTs is a dicey process, 4521 // and this approach is far more likely to get the corner cases right. 4522 if (CurContext->isDependentContext()) 4523 DelegationInit = Init; 4524 } 4525 4526 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4527 DelegationInit.getAs<Expr>(), 4528 InitRange.getEnd()); 4529 } 4530 4531 MemInitResult 4532 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4533 Expr *Init, CXXRecordDecl *ClassDecl, 4534 SourceLocation EllipsisLoc) { 4535 SourceLocation BaseLoc 4536 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4537 4538 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4539 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4540 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4541 4542 // C++ [class.base.init]p2: 4543 // [...] Unless the mem-initializer-id names a nonstatic data 4544 // member of the constructor's class or a direct or virtual base 4545 // of that class, the mem-initializer is ill-formed. A 4546 // mem-initializer-list can initialize a base class using any 4547 // name that denotes that base class type. 4548 4549 // We can store the initializers in "as-written" form and delay analysis until 4550 // instantiation if the constructor is dependent. But not for dependent 4551 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4552 bool Dependent = CurContext->isDependentContext() && 4553 (BaseType->isDependentType() || Init->isTypeDependent()); 4554 4555 SourceRange InitRange = Init->getSourceRange(); 4556 if (EllipsisLoc.isValid()) { 4557 // This is a pack expansion. 4558 if (!BaseType->containsUnexpandedParameterPack()) { 4559 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4560 << SourceRange(BaseLoc, InitRange.getEnd()); 4561 4562 EllipsisLoc = SourceLocation(); 4563 } 4564 } else { 4565 // Check for any unexpanded parameter packs. 4566 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4567 return true; 4568 4569 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4570 return true; 4571 } 4572 4573 // Check for direct and virtual base classes. 4574 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4575 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4576 if (!Dependent) { 4577 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4578 BaseType)) 4579 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4580 4581 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4582 VirtualBaseSpec); 4583 4584 // C++ [base.class.init]p2: 4585 // Unless the mem-initializer-id names a nonstatic data member of the 4586 // constructor's class or a direct or virtual base of that class, the 4587 // mem-initializer is ill-formed. 4588 if (!DirectBaseSpec && !VirtualBaseSpec) { 4589 // If the class has any dependent bases, then it's possible that 4590 // one of those types will resolve to the same type as 4591 // BaseType. Therefore, just treat this as a dependent base 4592 // class initialization. FIXME: Should we try to check the 4593 // initialization anyway? It seems odd. 4594 if (ClassDecl->hasAnyDependentBases()) 4595 Dependent = true; 4596 else 4597 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4598 << BaseType << Context.getTypeDeclType(ClassDecl) 4599 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4600 } 4601 } 4602 4603 if (Dependent) { 4604 DiscardCleanupsInEvaluationContext(); 4605 4606 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4607 /*IsVirtual=*/false, 4608 InitRange.getBegin(), Init, 4609 InitRange.getEnd(), EllipsisLoc); 4610 } 4611 4612 // C++ [base.class.init]p2: 4613 // If a mem-initializer-id is ambiguous because it designates both 4614 // a direct non-virtual base class and an inherited virtual base 4615 // class, the mem-initializer is ill-formed. 4616 if (DirectBaseSpec && VirtualBaseSpec) 4617 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4618 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4619 4620 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4621 if (!BaseSpec) 4622 BaseSpec = VirtualBaseSpec; 4623 4624 // Initialize the base. 4625 bool InitList = true; 4626 MultiExprArg Args = Init; 4627 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4628 InitList = false; 4629 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4630 } 4631 4632 InitializedEntity BaseEntity = 4633 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4634 InitializationKind Kind = 4635 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4636 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4637 InitRange.getEnd()); 4638 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4639 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4640 if (!BaseInit.isInvalid()) { 4641 // C++11 [class.base.init]p7: 4642 // The initialization of each base and member constitutes a 4643 // full-expression. 4644 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4645 /*DiscardedValue*/ false); 4646 } 4647 4648 if (BaseInit.isInvalid()) { 4649 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4650 Args, BaseType); 4651 if (BaseInit.isInvalid()) 4652 return true; 4653 } else { 4654 // If we are in a dependent context, template instantiation will 4655 // perform this type-checking again. Just save the arguments that we 4656 // received in a ParenListExpr. 4657 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4658 // of the information that we have about the base 4659 // initializer. However, deconstructing the ASTs is a dicey process, 4660 // and this approach is far more likely to get the corner cases right. 4661 if (CurContext->isDependentContext()) 4662 BaseInit = Init; 4663 } 4664 4665 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4666 BaseSpec->isVirtual(), 4667 InitRange.getBegin(), 4668 BaseInit.getAs<Expr>(), 4669 InitRange.getEnd(), EllipsisLoc); 4670 } 4671 4672 // Create a static_cast\<T&&>(expr). 4673 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4674 if (T.isNull()) T = E->getType(); 4675 QualType TargetType = SemaRef.BuildReferenceType( 4676 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4677 SourceLocation ExprLoc = E->getBeginLoc(); 4678 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4679 TargetType, ExprLoc); 4680 4681 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4682 SourceRange(ExprLoc, ExprLoc), 4683 E->getSourceRange()).get(); 4684 } 4685 4686 /// ImplicitInitializerKind - How an implicit base or member initializer should 4687 /// initialize its base or member. 4688 enum ImplicitInitializerKind { 4689 IIK_Default, 4690 IIK_Copy, 4691 IIK_Move, 4692 IIK_Inherit 4693 }; 4694 4695 static bool 4696 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4697 ImplicitInitializerKind ImplicitInitKind, 4698 CXXBaseSpecifier *BaseSpec, 4699 bool IsInheritedVirtualBase, 4700 CXXCtorInitializer *&CXXBaseInit) { 4701 InitializedEntity InitEntity 4702 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4703 IsInheritedVirtualBase); 4704 4705 ExprResult BaseInit; 4706 4707 switch (ImplicitInitKind) { 4708 case IIK_Inherit: 4709 case IIK_Default: { 4710 InitializationKind InitKind 4711 = InitializationKind::CreateDefault(Constructor->getLocation()); 4712 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4713 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4714 break; 4715 } 4716 4717 case IIK_Move: 4718 case IIK_Copy: { 4719 bool Moving = ImplicitInitKind == IIK_Move; 4720 ParmVarDecl *Param = Constructor->getParamDecl(0); 4721 QualType ParamType = Param->getType().getNonReferenceType(); 4722 4723 Expr *CopyCtorArg = 4724 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4725 SourceLocation(), Param, false, 4726 Constructor->getLocation(), ParamType, 4727 VK_LValue, nullptr); 4728 4729 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4730 4731 // Cast to the base class to avoid ambiguities. 4732 QualType ArgTy = 4733 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4734 ParamType.getQualifiers()); 4735 4736 if (Moving) { 4737 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4738 } 4739 4740 CXXCastPath BasePath; 4741 BasePath.push_back(BaseSpec); 4742 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4743 CK_UncheckedDerivedToBase, 4744 Moving ? VK_XValue : VK_LValue, 4745 &BasePath).get(); 4746 4747 InitializationKind InitKind 4748 = InitializationKind::CreateDirect(Constructor->getLocation(), 4749 SourceLocation(), SourceLocation()); 4750 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4751 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4752 break; 4753 } 4754 } 4755 4756 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4757 if (BaseInit.isInvalid()) 4758 return true; 4759 4760 CXXBaseInit = 4761 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4762 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4763 SourceLocation()), 4764 BaseSpec->isVirtual(), 4765 SourceLocation(), 4766 BaseInit.getAs<Expr>(), 4767 SourceLocation(), 4768 SourceLocation()); 4769 4770 return false; 4771 } 4772 4773 static bool RefersToRValueRef(Expr *MemRef) { 4774 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4775 return Referenced->getType()->isRValueReferenceType(); 4776 } 4777 4778 static bool 4779 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4780 ImplicitInitializerKind ImplicitInitKind, 4781 FieldDecl *Field, IndirectFieldDecl *Indirect, 4782 CXXCtorInitializer *&CXXMemberInit) { 4783 if (Field->isInvalidDecl()) 4784 return true; 4785 4786 SourceLocation Loc = Constructor->getLocation(); 4787 4788 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4789 bool Moving = ImplicitInitKind == IIK_Move; 4790 ParmVarDecl *Param = Constructor->getParamDecl(0); 4791 QualType ParamType = Param->getType().getNonReferenceType(); 4792 4793 // Suppress copying zero-width bitfields. 4794 if (Field->isZeroLengthBitField(SemaRef.Context)) 4795 return false; 4796 4797 Expr *MemberExprBase = 4798 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4799 SourceLocation(), Param, false, 4800 Loc, ParamType, VK_LValue, nullptr); 4801 4802 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4803 4804 if (Moving) { 4805 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4806 } 4807 4808 // Build a reference to this field within the parameter. 4809 CXXScopeSpec SS; 4810 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4811 Sema::LookupMemberName); 4812 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4813 : cast<ValueDecl>(Field), AS_public); 4814 MemberLookup.resolveKind(); 4815 ExprResult CtorArg 4816 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4817 ParamType, Loc, 4818 /*IsArrow=*/false, 4819 SS, 4820 /*TemplateKWLoc=*/SourceLocation(), 4821 /*FirstQualifierInScope=*/nullptr, 4822 MemberLookup, 4823 /*TemplateArgs=*/nullptr, 4824 /*S*/nullptr); 4825 if (CtorArg.isInvalid()) 4826 return true; 4827 4828 // C++11 [class.copy]p15: 4829 // - if a member m has rvalue reference type T&&, it is direct-initialized 4830 // with static_cast<T&&>(x.m); 4831 if (RefersToRValueRef(CtorArg.get())) { 4832 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4833 } 4834 4835 InitializedEntity Entity = 4836 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4837 /*Implicit*/ true) 4838 : InitializedEntity::InitializeMember(Field, nullptr, 4839 /*Implicit*/ true); 4840 4841 // Direct-initialize to use the copy constructor. 4842 InitializationKind InitKind = 4843 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4844 4845 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4846 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4847 ExprResult MemberInit = 4848 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4849 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4850 if (MemberInit.isInvalid()) 4851 return true; 4852 4853 if (Indirect) 4854 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4855 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4856 else 4857 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4858 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4859 return false; 4860 } 4861 4862 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4863 "Unhandled implicit init kind!"); 4864 4865 QualType FieldBaseElementType = 4866 SemaRef.Context.getBaseElementType(Field->getType()); 4867 4868 if (FieldBaseElementType->isRecordType()) { 4869 InitializedEntity InitEntity = 4870 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4871 /*Implicit*/ true) 4872 : InitializedEntity::InitializeMember(Field, nullptr, 4873 /*Implicit*/ true); 4874 InitializationKind InitKind = 4875 InitializationKind::CreateDefault(Loc); 4876 4877 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4878 ExprResult MemberInit = 4879 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4880 4881 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4882 if (MemberInit.isInvalid()) 4883 return true; 4884 4885 if (Indirect) 4886 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4887 Indirect, Loc, 4888 Loc, 4889 MemberInit.get(), 4890 Loc); 4891 else 4892 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4893 Field, Loc, Loc, 4894 MemberInit.get(), 4895 Loc); 4896 return false; 4897 } 4898 4899 if (!Field->getParent()->isUnion()) { 4900 if (FieldBaseElementType->isReferenceType()) { 4901 SemaRef.Diag(Constructor->getLocation(), 4902 diag::err_uninitialized_member_in_ctor) 4903 << (int)Constructor->isImplicit() 4904 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4905 << 0 << Field->getDeclName(); 4906 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4907 return true; 4908 } 4909 4910 if (FieldBaseElementType.isConstQualified()) { 4911 SemaRef.Diag(Constructor->getLocation(), 4912 diag::err_uninitialized_member_in_ctor) 4913 << (int)Constructor->isImplicit() 4914 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4915 << 1 << Field->getDeclName(); 4916 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4917 return true; 4918 } 4919 } 4920 4921 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4922 // ARC and Weak: 4923 // Default-initialize Objective-C pointers to NULL. 4924 CXXMemberInit 4925 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4926 Loc, Loc, 4927 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4928 Loc); 4929 return false; 4930 } 4931 4932 // Nothing to initialize. 4933 CXXMemberInit = nullptr; 4934 return false; 4935 } 4936 4937 namespace { 4938 struct BaseAndFieldInfo { 4939 Sema &S; 4940 CXXConstructorDecl *Ctor; 4941 bool AnyErrorsInInits; 4942 ImplicitInitializerKind IIK; 4943 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4944 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4945 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4946 4947 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4948 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4949 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4950 if (Ctor->getInheritedConstructor()) 4951 IIK = IIK_Inherit; 4952 else if (Generated && Ctor->isCopyConstructor()) 4953 IIK = IIK_Copy; 4954 else if (Generated && Ctor->isMoveConstructor()) 4955 IIK = IIK_Move; 4956 else 4957 IIK = IIK_Default; 4958 } 4959 4960 bool isImplicitCopyOrMove() const { 4961 switch (IIK) { 4962 case IIK_Copy: 4963 case IIK_Move: 4964 return true; 4965 4966 case IIK_Default: 4967 case IIK_Inherit: 4968 return false; 4969 } 4970 4971 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4972 } 4973 4974 bool addFieldInitializer(CXXCtorInitializer *Init) { 4975 AllToInit.push_back(Init); 4976 4977 // Check whether this initializer makes the field "used". 4978 if (Init->getInit()->HasSideEffects(S.Context)) 4979 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4980 4981 return false; 4982 } 4983 4984 bool isInactiveUnionMember(FieldDecl *Field) { 4985 RecordDecl *Record = Field->getParent(); 4986 if (!Record->isUnion()) 4987 return false; 4988 4989 if (FieldDecl *Active = 4990 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4991 return Active != Field->getCanonicalDecl(); 4992 4993 // In an implicit copy or move constructor, ignore any in-class initializer. 4994 if (isImplicitCopyOrMove()) 4995 return true; 4996 4997 // If there's no explicit initialization, the field is active only if it 4998 // has an in-class initializer... 4999 if (Field->hasInClassInitializer()) 5000 return false; 5001 // ... or it's an anonymous struct or union whose class has an in-class 5002 // initializer. 5003 if (!Field->isAnonymousStructOrUnion()) 5004 return true; 5005 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 5006 return !FieldRD->hasInClassInitializer(); 5007 } 5008 5009 /// Determine whether the given field is, or is within, a union member 5010 /// that is inactive (because there was an initializer given for a different 5011 /// member of the union, or because the union was not initialized at all). 5012 bool isWithinInactiveUnionMember(FieldDecl *Field, 5013 IndirectFieldDecl *Indirect) { 5014 if (!Indirect) 5015 return isInactiveUnionMember(Field); 5016 5017 for (auto *C : Indirect->chain()) { 5018 FieldDecl *Field = dyn_cast<FieldDecl>(C); 5019 if (Field && isInactiveUnionMember(Field)) 5020 return true; 5021 } 5022 return false; 5023 } 5024 }; 5025 } 5026 5027 /// Determine whether the given type is an incomplete or zero-lenfgth 5028 /// array type. 5029 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 5030 if (T->isIncompleteArrayType()) 5031 return true; 5032 5033 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 5034 if (!ArrayT->getSize()) 5035 return true; 5036 5037 T = ArrayT->getElementType(); 5038 } 5039 5040 return false; 5041 } 5042 5043 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 5044 FieldDecl *Field, 5045 IndirectFieldDecl *Indirect = nullptr) { 5046 if (Field->isInvalidDecl()) 5047 return false; 5048 5049 // Overwhelmingly common case: we have a direct initializer for this field. 5050 if (CXXCtorInitializer *Init = 5051 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 5052 return Info.addFieldInitializer(Init); 5053 5054 // C++11 [class.base.init]p8: 5055 // if the entity is a non-static data member that has a 5056 // brace-or-equal-initializer and either 5057 // -- the constructor's class is a union and no other variant member of that 5058 // union is designated by a mem-initializer-id or 5059 // -- the constructor's class is not a union, and, if the entity is a member 5060 // of an anonymous union, no other member of that union is designated by 5061 // a mem-initializer-id, 5062 // the entity is initialized as specified in [dcl.init]. 5063 // 5064 // We also apply the same rules to handle anonymous structs within anonymous 5065 // unions. 5066 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5067 return false; 5068 5069 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5070 ExprResult DIE = 5071 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5072 if (DIE.isInvalid()) 5073 return true; 5074 5075 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5076 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5077 5078 CXXCtorInitializer *Init; 5079 if (Indirect) 5080 Init = new (SemaRef.Context) 5081 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5082 SourceLocation(), DIE.get(), SourceLocation()); 5083 else 5084 Init = new (SemaRef.Context) 5085 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5086 SourceLocation(), DIE.get(), SourceLocation()); 5087 return Info.addFieldInitializer(Init); 5088 } 5089 5090 // Don't initialize incomplete or zero-length arrays. 5091 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5092 return false; 5093 5094 // Don't try to build an implicit initializer if there were semantic 5095 // errors in any of the initializers (and therefore we might be 5096 // missing some that the user actually wrote). 5097 if (Info.AnyErrorsInInits) 5098 return false; 5099 5100 CXXCtorInitializer *Init = nullptr; 5101 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5102 Indirect, Init)) 5103 return true; 5104 5105 if (!Init) 5106 return false; 5107 5108 return Info.addFieldInitializer(Init); 5109 } 5110 5111 bool 5112 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5113 CXXCtorInitializer *Initializer) { 5114 assert(Initializer->isDelegatingInitializer()); 5115 Constructor->setNumCtorInitializers(1); 5116 CXXCtorInitializer **initializer = 5117 new (Context) CXXCtorInitializer*[1]; 5118 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5119 Constructor->setCtorInitializers(initializer); 5120 5121 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5122 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5123 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5124 } 5125 5126 DelegatingCtorDecls.push_back(Constructor); 5127 5128 DiagnoseUninitializedFields(*this, Constructor); 5129 5130 return false; 5131 } 5132 5133 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5134 ArrayRef<CXXCtorInitializer *> Initializers) { 5135 if (Constructor->isDependentContext()) { 5136 // Just store the initializers as written, they will be checked during 5137 // instantiation. 5138 if (!Initializers.empty()) { 5139 Constructor->setNumCtorInitializers(Initializers.size()); 5140 CXXCtorInitializer **baseOrMemberInitializers = 5141 new (Context) CXXCtorInitializer*[Initializers.size()]; 5142 memcpy(baseOrMemberInitializers, Initializers.data(), 5143 Initializers.size() * sizeof(CXXCtorInitializer*)); 5144 Constructor->setCtorInitializers(baseOrMemberInitializers); 5145 } 5146 5147 // Let template instantiation know whether we had errors. 5148 if (AnyErrors) 5149 Constructor->setInvalidDecl(); 5150 5151 return false; 5152 } 5153 5154 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5155 5156 // We need to build the initializer AST according to order of construction 5157 // and not what user specified in the Initializers list. 5158 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5159 if (!ClassDecl) 5160 return true; 5161 5162 bool HadError = false; 5163 5164 for (unsigned i = 0; i < Initializers.size(); i++) { 5165 CXXCtorInitializer *Member = Initializers[i]; 5166 5167 if (Member->isBaseInitializer()) 5168 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5169 else { 5170 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5171 5172 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5173 for (auto *C : F->chain()) { 5174 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5175 if (FD && FD->getParent()->isUnion()) 5176 Info.ActiveUnionMember.insert(std::make_pair( 5177 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5178 } 5179 } else if (FieldDecl *FD = Member->getMember()) { 5180 if (FD->getParent()->isUnion()) 5181 Info.ActiveUnionMember.insert(std::make_pair( 5182 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5183 } 5184 } 5185 } 5186 5187 // Keep track of the direct virtual bases. 5188 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5189 for (auto &I : ClassDecl->bases()) { 5190 if (I.isVirtual()) 5191 DirectVBases.insert(&I); 5192 } 5193 5194 // Push virtual bases before others. 5195 for (auto &VBase : ClassDecl->vbases()) { 5196 if (CXXCtorInitializer *Value 5197 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5198 // [class.base.init]p7, per DR257: 5199 // A mem-initializer where the mem-initializer-id names a virtual base 5200 // class is ignored during execution of a constructor of any class that 5201 // is not the most derived class. 5202 if (ClassDecl->isAbstract()) { 5203 // FIXME: Provide a fixit to remove the base specifier. This requires 5204 // tracking the location of the associated comma for a base specifier. 5205 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5206 << VBase.getType() << ClassDecl; 5207 DiagnoseAbstractType(ClassDecl); 5208 } 5209 5210 Info.AllToInit.push_back(Value); 5211 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5212 // [class.base.init]p8, per DR257: 5213 // If a given [...] base class is not named by a mem-initializer-id 5214 // [...] and the entity is not a virtual base class of an abstract 5215 // class, then [...] the entity is default-initialized. 5216 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5217 CXXCtorInitializer *CXXBaseInit; 5218 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5219 &VBase, IsInheritedVirtualBase, 5220 CXXBaseInit)) { 5221 HadError = true; 5222 continue; 5223 } 5224 5225 Info.AllToInit.push_back(CXXBaseInit); 5226 } 5227 } 5228 5229 // Non-virtual bases. 5230 for (auto &Base : ClassDecl->bases()) { 5231 // Virtuals are in the virtual base list and already constructed. 5232 if (Base.isVirtual()) 5233 continue; 5234 5235 if (CXXCtorInitializer *Value 5236 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5237 Info.AllToInit.push_back(Value); 5238 } else if (!AnyErrors) { 5239 CXXCtorInitializer *CXXBaseInit; 5240 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5241 &Base, /*IsInheritedVirtualBase=*/false, 5242 CXXBaseInit)) { 5243 HadError = true; 5244 continue; 5245 } 5246 5247 Info.AllToInit.push_back(CXXBaseInit); 5248 } 5249 } 5250 5251 // Fields. 5252 for (auto *Mem : ClassDecl->decls()) { 5253 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5254 // C++ [class.bit]p2: 5255 // A declaration for a bit-field that omits the identifier declares an 5256 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5257 // initialized. 5258 if (F->isUnnamedBitfield()) 5259 continue; 5260 5261 // If we're not generating the implicit copy/move constructor, then we'll 5262 // handle anonymous struct/union fields based on their individual 5263 // indirect fields. 5264 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5265 continue; 5266 5267 if (CollectFieldInitializer(*this, Info, F)) 5268 HadError = true; 5269 continue; 5270 } 5271 5272 // Beyond this point, we only consider default initialization. 5273 if (Info.isImplicitCopyOrMove()) 5274 continue; 5275 5276 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5277 if (F->getType()->isIncompleteArrayType()) { 5278 assert(ClassDecl->hasFlexibleArrayMember() && 5279 "Incomplete array type is not valid"); 5280 continue; 5281 } 5282 5283 // Initialize each field of an anonymous struct individually. 5284 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5285 HadError = true; 5286 5287 continue; 5288 } 5289 } 5290 5291 unsigned NumInitializers = Info.AllToInit.size(); 5292 if (NumInitializers > 0) { 5293 Constructor->setNumCtorInitializers(NumInitializers); 5294 CXXCtorInitializer **baseOrMemberInitializers = 5295 new (Context) CXXCtorInitializer*[NumInitializers]; 5296 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5297 NumInitializers * sizeof(CXXCtorInitializer*)); 5298 Constructor->setCtorInitializers(baseOrMemberInitializers); 5299 5300 // Constructors implicitly reference the base and member 5301 // destructors. 5302 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5303 Constructor->getParent()); 5304 } 5305 5306 return HadError; 5307 } 5308 5309 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5310 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5311 const RecordDecl *RD = RT->getDecl(); 5312 if (RD->isAnonymousStructOrUnion()) { 5313 for (auto *Field : RD->fields()) 5314 PopulateKeysForFields(Field, IdealInits); 5315 return; 5316 } 5317 } 5318 IdealInits.push_back(Field->getCanonicalDecl()); 5319 } 5320 5321 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5322 return Context.getCanonicalType(BaseType).getTypePtr(); 5323 } 5324 5325 static const void *GetKeyForMember(ASTContext &Context, 5326 CXXCtorInitializer *Member) { 5327 if (!Member->isAnyMemberInitializer()) 5328 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5329 5330 return Member->getAnyMember()->getCanonicalDecl(); 5331 } 5332 5333 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5334 const CXXCtorInitializer *Previous, 5335 const CXXCtorInitializer *Current) { 5336 if (Previous->isAnyMemberInitializer()) 5337 Diag << 0 << Previous->getAnyMember(); 5338 else 5339 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5340 5341 if (Current->isAnyMemberInitializer()) 5342 Diag << 0 << Current->getAnyMember(); 5343 else 5344 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5345 } 5346 5347 static void DiagnoseBaseOrMemInitializerOrder( 5348 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5349 ArrayRef<CXXCtorInitializer *> Inits) { 5350 if (Constructor->getDeclContext()->isDependentContext()) 5351 return; 5352 5353 // Don't check initializers order unless the warning is enabled at the 5354 // location of at least one initializer. 5355 bool ShouldCheckOrder = false; 5356 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5357 CXXCtorInitializer *Init = Inits[InitIndex]; 5358 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5359 Init->getSourceLocation())) { 5360 ShouldCheckOrder = true; 5361 break; 5362 } 5363 } 5364 if (!ShouldCheckOrder) 5365 return; 5366 5367 // Build the list of bases and members in the order that they'll 5368 // actually be initialized. The explicit initializers should be in 5369 // this same order but may be missing things. 5370 SmallVector<const void*, 32> IdealInitKeys; 5371 5372 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5373 5374 // 1. Virtual bases. 5375 for (const auto &VBase : ClassDecl->vbases()) 5376 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5377 5378 // 2. Non-virtual bases. 5379 for (const auto &Base : ClassDecl->bases()) { 5380 if (Base.isVirtual()) 5381 continue; 5382 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5383 } 5384 5385 // 3. Direct fields. 5386 for (auto *Field : ClassDecl->fields()) { 5387 if (Field->isUnnamedBitfield()) 5388 continue; 5389 5390 PopulateKeysForFields(Field, IdealInitKeys); 5391 } 5392 5393 unsigned NumIdealInits = IdealInitKeys.size(); 5394 unsigned IdealIndex = 0; 5395 5396 // Track initializers that are in an incorrect order for either a warning or 5397 // note if multiple ones occur. 5398 SmallVector<unsigned> WarnIndexes; 5399 // Correlates the index of an initializer in the init-list to the index of 5400 // the field/base in the class. 5401 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5402 5403 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5404 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5405 5406 // Scan forward to try to find this initializer in the idealized 5407 // initializers list. 5408 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5409 if (InitKey == IdealInitKeys[IdealIndex]) 5410 break; 5411 5412 // If we didn't find this initializer, it must be because we 5413 // scanned past it on a previous iteration. That can only 5414 // happen if we're out of order; emit a warning. 5415 if (IdealIndex == NumIdealInits && InitIndex) { 5416 WarnIndexes.push_back(InitIndex); 5417 5418 // Move back to the initializer's location in the ideal list. 5419 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5420 if (InitKey == IdealInitKeys[IdealIndex]) 5421 break; 5422 5423 assert(IdealIndex < NumIdealInits && 5424 "initializer not found in initializer list"); 5425 } 5426 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5427 } 5428 5429 if (WarnIndexes.empty()) 5430 return; 5431 5432 // Sort based on the ideal order, first in the pair. 5433 llvm::sort(CorrelatedInitOrder, 5434 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5435 5436 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5437 // emit the diagnostic before we can try adding notes. 5438 { 5439 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5440 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5441 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5442 : diag::warn_some_initializers_out_of_order); 5443 5444 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5445 if (CorrelatedInitOrder[I].second == I) 5446 continue; 5447 // Ideally we would be using InsertFromRange here, but clang doesn't 5448 // appear to handle InsertFromRange correctly when the source range is 5449 // modified by another fix-it. 5450 D << FixItHint::CreateReplacement( 5451 Inits[I]->getSourceRange(), 5452 Lexer::getSourceText( 5453 CharSourceRange::getTokenRange( 5454 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5455 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5456 } 5457 5458 // If there is only 1 item out of order, the warning expects the name and 5459 // type of each being added to it. 5460 if (WarnIndexes.size() == 1) { 5461 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5462 Inits[WarnIndexes.front()]); 5463 return; 5464 } 5465 } 5466 // More than 1 item to warn, create notes letting the user know which ones 5467 // are bad. 5468 for (unsigned WarnIndex : WarnIndexes) { 5469 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5470 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5471 diag::note_initializer_out_of_order); 5472 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5473 D << PrevInit->getSourceRange(); 5474 } 5475 } 5476 5477 namespace { 5478 bool CheckRedundantInit(Sema &S, 5479 CXXCtorInitializer *Init, 5480 CXXCtorInitializer *&PrevInit) { 5481 if (!PrevInit) { 5482 PrevInit = Init; 5483 return false; 5484 } 5485 5486 if (FieldDecl *Field = Init->getAnyMember()) 5487 S.Diag(Init->getSourceLocation(), 5488 diag::err_multiple_mem_initialization) 5489 << Field->getDeclName() 5490 << Init->getSourceRange(); 5491 else { 5492 const Type *BaseClass = Init->getBaseClass(); 5493 assert(BaseClass && "neither field nor base"); 5494 S.Diag(Init->getSourceLocation(), 5495 diag::err_multiple_base_initialization) 5496 << QualType(BaseClass, 0) 5497 << Init->getSourceRange(); 5498 } 5499 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5500 << 0 << PrevInit->getSourceRange(); 5501 5502 return true; 5503 } 5504 5505 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5506 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5507 5508 bool CheckRedundantUnionInit(Sema &S, 5509 CXXCtorInitializer *Init, 5510 RedundantUnionMap &Unions) { 5511 FieldDecl *Field = Init->getAnyMember(); 5512 RecordDecl *Parent = Field->getParent(); 5513 NamedDecl *Child = Field; 5514 5515 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5516 if (Parent->isUnion()) { 5517 UnionEntry &En = Unions[Parent]; 5518 if (En.first && En.first != Child) { 5519 S.Diag(Init->getSourceLocation(), 5520 diag::err_multiple_mem_union_initialization) 5521 << Field->getDeclName() 5522 << Init->getSourceRange(); 5523 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5524 << 0 << En.second->getSourceRange(); 5525 return true; 5526 } 5527 if (!En.first) { 5528 En.first = Child; 5529 En.second = Init; 5530 } 5531 if (!Parent->isAnonymousStructOrUnion()) 5532 return false; 5533 } 5534 5535 Child = Parent; 5536 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5537 } 5538 5539 return false; 5540 } 5541 } // namespace 5542 5543 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5544 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5545 SourceLocation ColonLoc, 5546 ArrayRef<CXXCtorInitializer*> MemInits, 5547 bool AnyErrors) { 5548 if (!ConstructorDecl) 5549 return; 5550 5551 AdjustDeclIfTemplate(ConstructorDecl); 5552 5553 CXXConstructorDecl *Constructor 5554 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5555 5556 if (!Constructor) { 5557 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5558 return; 5559 } 5560 5561 // Mapping for the duplicate initializers check. 5562 // For member initializers, this is keyed with a FieldDecl*. 5563 // For base initializers, this is keyed with a Type*. 5564 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5565 5566 // Mapping for the inconsistent anonymous-union initializers check. 5567 RedundantUnionMap MemberUnions; 5568 5569 bool HadError = false; 5570 for (unsigned i = 0; i < MemInits.size(); i++) { 5571 CXXCtorInitializer *Init = MemInits[i]; 5572 5573 // Set the source order index. 5574 Init->setSourceOrder(i); 5575 5576 if (Init->isAnyMemberInitializer()) { 5577 const void *Key = GetKeyForMember(Context, Init); 5578 if (CheckRedundantInit(*this, Init, Members[Key]) || 5579 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5580 HadError = true; 5581 } else if (Init->isBaseInitializer()) { 5582 const void *Key = GetKeyForMember(Context, Init); 5583 if (CheckRedundantInit(*this, Init, Members[Key])) 5584 HadError = true; 5585 } else { 5586 assert(Init->isDelegatingInitializer()); 5587 // This must be the only initializer 5588 if (MemInits.size() != 1) { 5589 Diag(Init->getSourceLocation(), 5590 diag::err_delegating_initializer_alone) 5591 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5592 // We will treat this as being the only initializer. 5593 } 5594 SetDelegatingInitializer(Constructor, MemInits[i]); 5595 // Return immediately as the initializer is set. 5596 return; 5597 } 5598 } 5599 5600 if (HadError) 5601 return; 5602 5603 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5604 5605 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5606 5607 DiagnoseUninitializedFields(*this, Constructor); 5608 } 5609 5610 void 5611 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5612 CXXRecordDecl *ClassDecl) { 5613 // Ignore dependent contexts. Also ignore unions, since their members never 5614 // have destructors implicitly called. 5615 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5616 return; 5617 5618 // FIXME: all the access-control diagnostics are positioned on the 5619 // field/base declaration. That's probably good; that said, the 5620 // user might reasonably want to know why the destructor is being 5621 // emitted, and we currently don't say. 5622 5623 // Non-static data members. 5624 for (auto *Field : ClassDecl->fields()) { 5625 if (Field->isInvalidDecl()) 5626 continue; 5627 5628 // Don't destroy incomplete or zero-length arrays. 5629 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5630 continue; 5631 5632 QualType FieldType = Context.getBaseElementType(Field->getType()); 5633 5634 const RecordType* RT = FieldType->getAs<RecordType>(); 5635 if (!RT) 5636 continue; 5637 5638 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5639 if (FieldClassDecl->isInvalidDecl()) 5640 continue; 5641 if (FieldClassDecl->hasIrrelevantDestructor()) 5642 continue; 5643 // The destructor for an implicit anonymous union member is never invoked. 5644 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5645 continue; 5646 5647 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5648 assert(Dtor && "No dtor found for FieldClassDecl!"); 5649 CheckDestructorAccess(Field->getLocation(), Dtor, 5650 PDiag(diag::err_access_dtor_field) 5651 << Field->getDeclName() 5652 << FieldType); 5653 5654 MarkFunctionReferenced(Location, Dtor); 5655 DiagnoseUseOfDecl(Dtor, Location); 5656 } 5657 5658 // We only potentially invoke the destructors of potentially constructed 5659 // subobjects. 5660 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5661 5662 // If the destructor exists and has already been marked used in the MS ABI, 5663 // then virtual base destructors have already been checked and marked used. 5664 // Skip checking them again to avoid duplicate diagnostics. 5665 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5666 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5667 if (Dtor && Dtor->isUsed()) 5668 VisitVirtualBases = false; 5669 } 5670 5671 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5672 5673 // Bases. 5674 for (const auto &Base : ClassDecl->bases()) { 5675 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5676 if (!RT) 5677 continue; 5678 5679 // Remember direct virtual bases. 5680 if (Base.isVirtual()) { 5681 if (!VisitVirtualBases) 5682 continue; 5683 DirectVirtualBases.insert(RT); 5684 } 5685 5686 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5687 // If our base class is invalid, we probably can't get its dtor anyway. 5688 if (BaseClassDecl->isInvalidDecl()) 5689 continue; 5690 if (BaseClassDecl->hasIrrelevantDestructor()) 5691 continue; 5692 5693 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5694 assert(Dtor && "No dtor found for BaseClassDecl!"); 5695 5696 // FIXME: caret should be on the start of the class name 5697 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5698 PDiag(diag::err_access_dtor_base) 5699 << Base.getType() << Base.getSourceRange(), 5700 Context.getTypeDeclType(ClassDecl)); 5701 5702 MarkFunctionReferenced(Location, Dtor); 5703 DiagnoseUseOfDecl(Dtor, Location); 5704 } 5705 5706 if (VisitVirtualBases) 5707 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5708 &DirectVirtualBases); 5709 } 5710 5711 void Sema::MarkVirtualBaseDestructorsReferenced( 5712 SourceLocation Location, CXXRecordDecl *ClassDecl, 5713 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5714 // Virtual bases. 5715 for (const auto &VBase : ClassDecl->vbases()) { 5716 // Bases are always records in a well-formed non-dependent class. 5717 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5718 5719 // Ignore already visited direct virtual bases. 5720 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5721 continue; 5722 5723 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5724 // If our base class is invalid, we probably can't get its dtor anyway. 5725 if (BaseClassDecl->isInvalidDecl()) 5726 continue; 5727 if (BaseClassDecl->hasIrrelevantDestructor()) 5728 continue; 5729 5730 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5731 assert(Dtor && "No dtor found for BaseClassDecl!"); 5732 if (CheckDestructorAccess( 5733 ClassDecl->getLocation(), Dtor, 5734 PDiag(diag::err_access_dtor_vbase) 5735 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5736 Context.getTypeDeclType(ClassDecl)) == 5737 AR_accessible) { 5738 CheckDerivedToBaseConversion( 5739 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5740 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5741 SourceRange(), DeclarationName(), nullptr); 5742 } 5743 5744 MarkFunctionReferenced(Location, Dtor); 5745 DiagnoseUseOfDecl(Dtor, Location); 5746 } 5747 } 5748 5749 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5750 if (!CDtorDecl) 5751 return; 5752 5753 if (CXXConstructorDecl *Constructor 5754 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5755 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5756 DiagnoseUninitializedFields(*this, Constructor); 5757 } 5758 } 5759 5760 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5761 if (!getLangOpts().CPlusPlus) 5762 return false; 5763 5764 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5765 if (!RD) 5766 return false; 5767 5768 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5769 // class template specialization here, but doing so breaks a lot of code. 5770 5771 // We can't answer whether something is abstract until it has a 5772 // definition. If it's currently being defined, we'll walk back 5773 // over all the declarations when we have a full definition. 5774 const CXXRecordDecl *Def = RD->getDefinition(); 5775 if (!Def || Def->isBeingDefined()) 5776 return false; 5777 5778 return RD->isAbstract(); 5779 } 5780 5781 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5782 TypeDiagnoser &Diagnoser) { 5783 if (!isAbstractType(Loc, T)) 5784 return false; 5785 5786 T = Context.getBaseElementType(T); 5787 Diagnoser.diagnose(*this, Loc, T); 5788 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5789 return true; 5790 } 5791 5792 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5793 // Check if we've already emitted the list of pure virtual functions 5794 // for this class. 5795 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5796 return; 5797 5798 // If the diagnostic is suppressed, don't emit the notes. We're only 5799 // going to emit them once, so try to attach them to a diagnostic we're 5800 // actually going to show. 5801 if (Diags.isLastDiagnosticIgnored()) 5802 return; 5803 5804 CXXFinalOverriderMap FinalOverriders; 5805 RD->getFinalOverriders(FinalOverriders); 5806 5807 // Keep a set of seen pure methods so we won't diagnose the same method 5808 // more than once. 5809 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5810 5811 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5812 MEnd = FinalOverriders.end(); 5813 M != MEnd; 5814 ++M) { 5815 for (OverridingMethods::iterator SO = M->second.begin(), 5816 SOEnd = M->second.end(); 5817 SO != SOEnd; ++SO) { 5818 // C++ [class.abstract]p4: 5819 // A class is abstract if it contains or inherits at least one 5820 // pure virtual function for which the final overrider is pure 5821 // virtual. 5822 5823 // 5824 if (SO->second.size() != 1) 5825 continue; 5826 5827 if (!SO->second.front().Method->isPure()) 5828 continue; 5829 5830 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5831 continue; 5832 5833 Diag(SO->second.front().Method->getLocation(), 5834 diag::note_pure_virtual_function) 5835 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5836 } 5837 } 5838 5839 if (!PureVirtualClassDiagSet) 5840 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5841 PureVirtualClassDiagSet->insert(RD); 5842 } 5843 5844 namespace { 5845 struct AbstractUsageInfo { 5846 Sema &S; 5847 CXXRecordDecl *Record; 5848 CanQualType AbstractType; 5849 bool Invalid; 5850 5851 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5852 : S(S), Record(Record), 5853 AbstractType(S.Context.getCanonicalType( 5854 S.Context.getTypeDeclType(Record))), 5855 Invalid(false) {} 5856 5857 void DiagnoseAbstractType() { 5858 if (Invalid) return; 5859 S.DiagnoseAbstractType(Record); 5860 Invalid = true; 5861 } 5862 5863 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5864 }; 5865 5866 struct CheckAbstractUsage { 5867 AbstractUsageInfo &Info; 5868 const NamedDecl *Ctx; 5869 5870 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5871 : Info(Info), Ctx(Ctx) {} 5872 5873 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5874 switch (TL.getTypeLocClass()) { 5875 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5876 #define TYPELOC(CLASS, PARENT) \ 5877 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5878 #include "clang/AST/TypeLocNodes.def" 5879 } 5880 } 5881 5882 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5883 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5884 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5885 if (!TL.getParam(I)) 5886 continue; 5887 5888 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5889 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5890 } 5891 } 5892 5893 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5894 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5895 } 5896 5897 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5898 // Visit the type parameters from a permissive context. 5899 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5900 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5901 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5902 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5903 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5904 // TODO: other template argument types? 5905 } 5906 } 5907 5908 // Visit pointee types from a permissive context. 5909 #define CheckPolymorphic(Type) \ 5910 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5911 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5912 } 5913 CheckPolymorphic(PointerTypeLoc) 5914 CheckPolymorphic(ReferenceTypeLoc) 5915 CheckPolymorphic(MemberPointerTypeLoc) 5916 CheckPolymorphic(BlockPointerTypeLoc) 5917 CheckPolymorphic(AtomicTypeLoc) 5918 5919 /// Handle all the types we haven't given a more specific 5920 /// implementation for above. 5921 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5922 // Every other kind of type that we haven't called out already 5923 // that has an inner type is either (1) sugar or (2) contains that 5924 // inner type in some way as a subobject. 5925 if (TypeLoc Next = TL.getNextTypeLoc()) 5926 return Visit(Next, Sel); 5927 5928 // If there's no inner type and we're in a permissive context, 5929 // don't diagnose. 5930 if (Sel == Sema::AbstractNone) return; 5931 5932 // Check whether the type matches the abstract type. 5933 QualType T = TL.getType(); 5934 if (T->isArrayType()) { 5935 Sel = Sema::AbstractArrayType; 5936 T = Info.S.Context.getBaseElementType(T); 5937 } 5938 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5939 if (CT != Info.AbstractType) return; 5940 5941 // It matched; do some magic. 5942 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5943 if (Sel == Sema::AbstractArrayType) { 5944 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5945 << T << TL.getSourceRange(); 5946 } else { 5947 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5948 << Sel << T << TL.getSourceRange(); 5949 } 5950 Info.DiagnoseAbstractType(); 5951 } 5952 }; 5953 5954 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5955 Sema::AbstractDiagSelID Sel) { 5956 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5957 } 5958 5959 } 5960 5961 /// Check for invalid uses of an abstract type in a function declaration. 5962 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5963 FunctionDecl *FD) { 5964 // No need to do the check on definitions, which require that 5965 // the return/param types be complete. 5966 if (FD->doesThisDeclarationHaveABody()) 5967 return; 5968 5969 // For safety's sake, just ignore it if we don't have type source 5970 // information. This should never happen for non-implicit methods, 5971 // but... 5972 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5973 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 5974 } 5975 5976 /// Check for invalid uses of an abstract type in a variable0 declaration. 5977 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5978 VarDecl *VD) { 5979 // No need to do the check on definitions, which require that 5980 // the type is complete. 5981 if (VD->isThisDeclarationADefinition()) 5982 return; 5983 5984 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 5985 Sema::AbstractVariableType); 5986 } 5987 5988 /// Check for invalid uses of an abstract type within a class definition. 5989 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5990 CXXRecordDecl *RD) { 5991 for (auto *D : RD->decls()) { 5992 if (D->isImplicit()) continue; 5993 5994 // Step through friends to the befriended declaration. 5995 if (auto *FD = dyn_cast<FriendDecl>(D)) { 5996 D = FD->getFriendDecl(); 5997 if (!D) continue; 5998 } 5999 6000 // Functions and function templates. 6001 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 6002 CheckAbstractClassUsage(Info, FD); 6003 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 6004 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 6005 6006 // Fields and static variables. 6007 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 6008 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 6009 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 6010 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 6011 CheckAbstractClassUsage(Info, VD); 6012 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 6013 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 6014 6015 // Nested classes and class templates. 6016 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6017 CheckAbstractClassUsage(Info, RD); 6018 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 6019 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 6020 } 6021 } 6022 } 6023 6024 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 6025 Attr *ClassAttr = getDLLAttr(Class); 6026 if (!ClassAttr) 6027 return; 6028 6029 assert(ClassAttr->getKind() == attr::DLLExport); 6030 6031 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6032 6033 if (TSK == TSK_ExplicitInstantiationDeclaration) 6034 // Don't go any further if this is just an explicit instantiation 6035 // declaration. 6036 return; 6037 6038 // Add a context note to explain how we got to any diagnostics produced below. 6039 struct MarkingClassDllexported { 6040 Sema &S; 6041 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 6042 SourceLocation AttrLoc) 6043 : S(S) { 6044 Sema::CodeSynthesisContext Ctx; 6045 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 6046 Ctx.PointOfInstantiation = AttrLoc; 6047 Ctx.Entity = Class; 6048 S.pushCodeSynthesisContext(Ctx); 6049 } 6050 ~MarkingClassDllexported() { 6051 S.popCodeSynthesisContext(); 6052 } 6053 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 6054 6055 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6056 S.MarkVTableUsed(Class->getLocation(), Class, true); 6057 6058 for (Decl *Member : Class->decls()) { 6059 // Skip members that were not marked exported. 6060 if (!Member->hasAttr<DLLExportAttr>()) 6061 continue; 6062 6063 // Defined static variables that are members of an exported base 6064 // class must be marked export too. 6065 auto *VD = dyn_cast<VarDecl>(Member); 6066 if (VD && VD->getStorageClass() == SC_Static && 6067 TSK == TSK_ImplicitInstantiation) 6068 S.MarkVariableReferenced(VD->getLocation(), VD); 6069 6070 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6071 if (!MD) 6072 continue; 6073 6074 if (MD->isUserProvided()) { 6075 // Instantiate non-default class member functions ... 6076 6077 // .. except for certain kinds of template specializations. 6078 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6079 continue; 6080 6081 // If this is an MS ABI dllexport default constructor, instantiate any 6082 // default arguments. 6083 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6084 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6085 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6086 S.InstantiateDefaultCtorDefaultArgs(CD); 6087 } 6088 } 6089 6090 S.MarkFunctionReferenced(Class->getLocation(), MD); 6091 6092 // The function will be passed to the consumer when its definition is 6093 // encountered. 6094 } else if (MD->isExplicitlyDefaulted()) { 6095 // Synthesize and instantiate explicitly defaulted methods. 6096 S.MarkFunctionReferenced(Class->getLocation(), MD); 6097 6098 if (TSK != TSK_ExplicitInstantiationDefinition) { 6099 // Except for explicit instantiation defs, we will not see the 6100 // definition again later, so pass it to the consumer now. 6101 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6102 } 6103 } else if (!MD->isTrivial() || 6104 MD->isCopyAssignmentOperator() || 6105 MD->isMoveAssignmentOperator()) { 6106 // Synthesize and instantiate non-trivial implicit methods, and the copy 6107 // and move assignment operators. The latter are exported even if they 6108 // are trivial, because the address of an operator can be taken and 6109 // should compare equal across libraries. 6110 S.MarkFunctionReferenced(Class->getLocation(), MD); 6111 6112 // There is no later point when we will see the definition of this 6113 // function, so pass it to the consumer now. 6114 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6115 } 6116 } 6117 } 6118 6119 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6120 CXXRecordDecl *Class) { 6121 // Only the MS ABI has default constructor closures, so we don't need to do 6122 // this semantic checking anywhere else. 6123 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6124 return; 6125 6126 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6127 for (Decl *Member : Class->decls()) { 6128 // Look for exported default constructors. 6129 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6130 if (!CD || !CD->isDefaultConstructor()) 6131 continue; 6132 auto *Attr = CD->getAttr<DLLExportAttr>(); 6133 if (!Attr) 6134 continue; 6135 6136 // If the class is non-dependent, mark the default arguments as ODR-used so 6137 // that we can properly codegen the constructor closure. 6138 if (!Class->isDependentContext()) { 6139 for (ParmVarDecl *PD : CD->parameters()) { 6140 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6141 S.DiscardCleanupsInEvaluationContext(); 6142 } 6143 } 6144 6145 if (LastExportedDefaultCtor) { 6146 S.Diag(LastExportedDefaultCtor->getLocation(), 6147 diag::err_attribute_dll_ambiguous_default_ctor) 6148 << Class; 6149 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6150 << CD->getDeclName(); 6151 return; 6152 } 6153 LastExportedDefaultCtor = CD; 6154 } 6155 } 6156 6157 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6158 CXXRecordDecl *Class) { 6159 bool ErrorReported = false; 6160 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6161 ClassTemplateDecl *TD) { 6162 if (ErrorReported) 6163 return; 6164 S.Diag(TD->getLocation(), 6165 diag::err_cuda_device_builtin_surftex_cls_template) 6166 << /*surface*/ 0 << TD; 6167 ErrorReported = true; 6168 }; 6169 6170 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6171 if (!TD) { 6172 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6173 if (!SD) { 6174 S.Diag(Class->getLocation(), 6175 diag::err_cuda_device_builtin_surftex_ref_decl) 6176 << /*surface*/ 0 << Class; 6177 S.Diag(Class->getLocation(), 6178 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6179 << Class; 6180 return; 6181 } 6182 TD = SD->getSpecializedTemplate(); 6183 } 6184 6185 TemplateParameterList *Params = TD->getTemplateParameters(); 6186 unsigned N = Params->size(); 6187 6188 if (N != 2) { 6189 reportIllegalClassTemplate(S, TD); 6190 S.Diag(TD->getLocation(), 6191 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6192 << TD << 2; 6193 } 6194 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6195 reportIllegalClassTemplate(S, TD); 6196 S.Diag(TD->getLocation(), 6197 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6198 << TD << /*1st*/ 0 << /*type*/ 0; 6199 } 6200 if (N > 1) { 6201 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6202 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6203 reportIllegalClassTemplate(S, TD); 6204 S.Diag(TD->getLocation(), 6205 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6206 << TD << /*2nd*/ 1 << /*integer*/ 1; 6207 } 6208 } 6209 } 6210 6211 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6212 CXXRecordDecl *Class) { 6213 bool ErrorReported = false; 6214 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6215 ClassTemplateDecl *TD) { 6216 if (ErrorReported) 6217 return; 6218 S.Diag(TD->getLocation(), 6219 diag::err_cuda_device_builtin_surftex_cls_template) 6220 << /*texture*/ 1 << TD; 6221 ErrorReported = true; 6222 }; 6223 6224 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6225 if (!TD) { 6226 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6227 if (!SD) { 6228 S.Diag(Class->getLocation(), 6229 diag::err_cuda_device_builtin_surftex_ref_decl) 6230 << /*texture*/ 1 << Class; 6231 S.Diag(Class->getLocation(), 6232 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6233 << Class; 6234 return; 6235 } 6236 TD = SD->getSpecializedTemplate(); 6237 } 6238 6239 TemplateParameterList *Params = TD->getTemplateParameters(); 6240 unsigned N = Params->size(); 6241 6242 if (N != 3) { 6243 reportIllegalClassTemplate(S, TD); 6244 S.Diag(TD->getLocation(), 6245 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6246 << TD << 3; 6247 } 6248 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6249 reportIllegalClassTemplate(S, TD); 6250 S.Diag(TD->getLocation(), 6251 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6252 << TD << /*1st*/ 0 << /*type*/ 0; 6253 } 6254 if (N > 1) { 6255 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6256 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6257 reportIllegalClassTemplate(S, TD); 6258 S.Diag(TD->getLocation(), 6259 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6260 << TD << /*2nd*/ 1 << /*integer*/ 1; 6261 } 6262 } 6263 if (N > 2) { 6264 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6265 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6266 reportIllegalClassTemplate(S, TD); 6267 S.Diag(TD->getLocation(), 6268 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6269 << TD << /*3rd*/ 2 << /*integer*/ 1; 6270 } 6271 } 6272 } 6273 6274 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6275 // Mark any compiler-generated routines with the implicit code_seg attribute. 6276 for (auto *Method : Class->methods()) { 6277 if (Method->isUserProvided()) 6278 continue; 6279 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6280 Method->addAttr(A); 6281 } 6282 } 6283 6284 /// Check class-level dllimport/dllexport attribute. 6285 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6286 Attr *ClassAttr = getDLLAttr(Class); 6287 6288 // MSVC inherits DLL attributes to partial class template specializations. 6289 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6290 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6291 if (Attr *TemplateAttr = 6292 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6293 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6294 A->setInherited(true); 6295 ClassAttr = A; 6296 } 6297 } 6298 } 6299 6300 if (!ClassAttr) 6301 return; 6302 6303 if (!Class->isExternallyVisible()) { 6304 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6305 << Class << ClassAttr; 6306 return; 6307 } 6308 6309 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6310 !ClassAttr->isInherited()) { 6311 // Diagnose dll attributes on members of class with dll attribute. 6312 for (Decl *Member : Class->decls()) { 6313 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6314 continue; 6315 InheritableAttr *MemberAttr = getDLLAttr(Member); 6316 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6317 continue; 6318 6319 Diag(MemberAttr->getLocation(), 6320 diag::err_attribute_dll_member_of_dll_class) 6321 << MemberAttr << ClassAttr; 6322 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6323 Member->setInvalidDecl(); 6324 } 6325 } 6326 6327 if (Class->getDescribedClassTemplate()) 6328 // Don't inherit dll attribute until the template is instantiated. 6329 return; 6330 6331 // The class is either imported or exported. 6332 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6333 6334 // Check if this was a dllimport attribute propagated from a derived class to 6335 // a base class template specialization. We don't apply these attributes to 6336 // static data members. 6337 const bool PropagatedImport = 6338 !ClassExported && 6339 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6340 6341 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6342 6343 // Ignore explicit dllexport on explicit class template instantiation 6344 // declarations, except in MinGW mode. 6345 if (ClassExported && !ClassAttr->isInherited() && 6346 TSK == TSK_ExplicitInstantiationDeclaration && 6347 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6348 Class->dropAttr<DLLExportAttr>(); 6349 return; 6350 } 6351 6352 // Force declaration of implicit members so they can inherit the attribute. 6353 ForceDeclarationOfImplicitMembers(Class); 6354 6355 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6356 // seem to be true in practice? 6357 6358 for (Decl *Member : Class->decls()) { 6359 VarDecl *VD = dyn_cast<VarDecl>(Member); 6360 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6361 6362 // Only methods and static fields inherit the attributes. 6363 if (!VD && !MD) 6364 continue; 6365 6366 if (MD) { 6367 // Don't process deleted methods. 6368 if (MD->isDeleted()) 6369 continue; 6370 6371 if (MD->isInlined()) { 6372 // MinGW does not import or export inline methods. But do it for 6373 // template instantiations. 6374 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6375 TSK != TSK_ExplicitInstantiationDeclaration && 6376 TSK != TSK_ExplicitInstantiationDefinition) 6377 continue; 6378 6379 // MSVC versions before 2015 don't export the move assignment operators 6380 // and move constructor, so don't attempt to import/export them if 6381 // we have a definition. 6382 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6383 if ((MD->isMoveAssignmentOperator() || 6384 (Ctor && Ctor->isMoveConstructor())) && 6385 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6386 continue; 6387 6388 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6389 // operator is exported anyway. 6390 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6391 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6392 continue; 6393 } 6394 } 6395 6396 // Don't apply dllimport attributes to static data members of class template 6397 // instantiations when the attribute is propagated from a derived class. 6398 if (VD && PropagatedImport) 6399 continue; 6400 6401 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6402 continue; 6403 6404 if (!getDLLAttr(Member)) { 6405 InheritableAttr *NewAttr = nullptr; 6406 6407 // Do not export/import inline function when -fno-dllexport-inlines is 6408 // passed. But add attribute for later local static var check. 6409 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6410 TSK != TSK_ExplicitInstantiationDeclaration && 6411 TSK != TSK_ExplicitInstantiationDefinition) { 6412 if (ClassExported) { 6413 NewAttr = ::new (getASTContext()) 6414 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6415 } else { 6416 NewAttr = ::new (getASTContext()) 6417 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6418 } 6419 } else { 6420 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6421 } 6422 6423 NewAttr->setInherited(true); 6424 Member->addAttr(NewAttr); 6425 6426 if (MD) { 6427 // Propagate DLLAttr to friend re-declarations of MD that have already 6428 // been constructed. 6429 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6430 FD = FD->getPreviousDecl()) { 6431 if (FD->getFriendObjectKind() == Decl::FOK_None) 6432 continue; 6433 assert(!getDLLAttr(FD) && 6434 "friend re-decl should not already have a DLLAttr"); 6435 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6436 NewAttr->setInherited(true); 6437 FD->addAttr(NewAttr); 6438 } 6439 } 6440 } 6441 } 6442 6443 if (ClassExported) 6444 DelayedDllExportClasses.push_back(Class); 6445 } 6446 6447 /// Perform propagation of DLL attributes from a derived class to a 6448 /// templated base class for MS compatibility. 6449 void Sema::propagateDLLAttrToBaseClassTemplate( 6450 CXXRecordDecl *Class, Attr *ClassAttr, 6451 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6452 if (getDLLAttr( 6453 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6454 // If the base class template has a DLL attribute, don't try to change it. 6455 return; 6456 } 6457 6458 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6459 if (!getDLLAttr(BaseTemplateSpec) && 6460 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6461 TSK == TSK_ImplicitInstantiation)) { 6462 // The template hasn't been instantiated yet (or it has, but only as an 6463 // explicit instantiation declaration or implicit instantiation, which means 6464 // we haven't codegenned any members yet), so propagate the attribute. 6465 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6466 NewAttr->setInherited(true); 6467 BaseTemplateSpec->addAttr(NewAttr); 6468 6469 // If this was an import, mark that we propagated it from a derived class to 6470 // a base class template specialization. 6471 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6472 ImportAttr->setPropagatedToBaseTemplate(); 6473 6474 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6475 // needs to be run again to work see the new attribute. Otherwise this will 6476 // get run whenever the template is instantiated. 6477 if (TSK != TSK_Undeclared) 6478 checkClassLevelDLLAttribute(BaseTemplateSpec); 6479 6480 return; 6481 } 6482 6483 if (getDLLAttr(BaseTemplateSpec)) { 6484 // The template has already been specialized or instantiated with an 6485 // attribute, explicitly or through propagation. We should not try to change 6486 // it. 6487 return; 6488 } 6489 6490 // The template was previously instantiated or explicitly specialized without 6491 // a dll attribute, It's too late for us to add an attribute, so warn that 6492 // this is unsupported. 6493 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6494 << BaseTemplateSpec->isExplicitSpecialization(); 6495 Diag(ClassAttr->getLocation(), diag::note_attribute); 6496 if (BaseTemplateSpec->isExplicitSpecialization()) { 6497 Diag(BaseTemplateSpec->getLocation(), 6498 diag::note_template_class_explicit_specialization_was_here) 6499 << BaseTemplateSpec; 6500 } else { 6501 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6502 diag::note_template_class_instantiation_was_here) 6503 << BaseTemplateSpec; 6504 } 6505 } 6506 6507 /// Determine the kind of defaulting that would be done for a given function. 6508 /// 6509 /// If the function is both a default constructor and a copy / move constructor 6510 /// (due to having a default argument for the first parameter), this picks 6511 /// CXXDefaultConstructor. 6512 /// 6513 /// FIXME: Check that case is properly handled by all callers. 6514 Sema::DefaultedFunctionKind 6515 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6516 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6517 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6518 if (Ctor->isDefaultConstructor()) 6519 return Sema::CXXDefaultConstructor; 6520 6521 if (Ctor->isCopyConstructor()) 6522 return Sema::CXXCopyConstructor; 6523 6524 if (Ctor->isMoveConstructor()) 6525 return Sema::CXXMoveConstructor; 6526 } 6527 6528 if (MD->isCopyAssignmentOperator()) 6529 return Sema::CXXCopyAssignment; 6530 6531 if (MD->isMoveAssignmentOperator()) 6532 return Sema::CXXMoveAssignment; 6533 6534 if (isa<CXXDestructorDecl>(FD)) 6535 return Sema::CXXDestructor; 6536 } 6537 6538 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6539 case OO_EqualEqual: 6540 return DefaultedComparisonKind::Equal; 6541 6542 case OO_ExclaimEqual: 6543 return DefaultedComparisonKind::NotEqual; 6544 6545 case OO_Spaceship: 6546 // No point allowing this if <=> doesn't exist in the current language mode. 6547 if (!getLangOpts().CPlusPlus20) 6548 break; 6549 return DefaultedComparisonKind::ThreeWay; 6550 6551 case OO_Less: 6552 case OO_LessEqual: 6553 case OO_Greater: 6554 case OO_GreaterEqual: 6555 // No point allowing this if <=> doesn't exist in the current language mode. 6556 if (!getLangOpts().CPlusPlus20) 6557 break; 6558 return DefaultedComparisonKind::Relational; 6559 6560 default: 6561 break; 6562 } 6563 6564 // Not defaultable. 6565 return DefaultedFunctionKind(); 6566 } 6567 6568 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6569 SourceLocation DefaultLoc) { 6570 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6571 if (DFK.isComparison()) 6572 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6573 6574 switch (DFK.asSpecialMember()) { 6575 case Sema::CXXDefaultConstructor: 6576 S.DefineImplicitDefaultConstructor(DefaultLoc, 6577 cast<CXXConstructorDecl>(FD)); 6578 break; 6579 case Sema::CXXCopyConstructor: 6580 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6581 break; 6582 case Sema::CXXCopyAssignment: 6583 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6584 break; 6585 case Sema::CXXDestructor: 6586 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6587 break; 6588 case Sema::CXXMoveConstructor: 6589 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6590 break; 6591 case Sema::CXXMoveAssignment: 6592 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6593 break; 6594 case Sema::CXXInvalid: 6595 llvm_unreachable("Invalid special member."); 6596 } 6597 } 6598 6599 /// Determine whether a type is permitted to be passed or returned in 6600 /// registers, per C++ [class.temporary]p3. 6601 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6602 TargetInfo::CallingConvKind CCK) { 6603 if (D->isDependentType() || D->isInvalidDecl()) 6604 return false; 6605 6606 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6607 // The PS4 platform ABI follows the behavior of Clang 3.2. 6608 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6609 return !D->hasNonTrivialDestructorForCall() && 6610 !D->hasNonTrivialCopyConstructorForCall(); 6611 6612 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6613 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6614 bool DtorIsTrivialForCall = false; 6615 6616 // If a class has at least one non-deleted, trivial copy constructor, it 6617 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6618 // 6619 // Note: This permits classes with non-trivial copy or move ctors to be 6620 // passed in registers, so long as they *also* have a trivial copy ctor, 6621 // which is non-conforming. 6622 if (D->needsImplicitCopyConstructor()) { 6623 if (!D->defaultedCopyConstructorIsDeleted()) { 6624 if (D->hasTrivialCopyConstructor()) 6625 CopyCtorIsTrivial = true; 6626 if (D->hasTrivialCopyConstructorForCall()) 6627 CopyCtorIsTrivialForCall = true; 6628 } 6629 } else { 6630 for (const CXXConstructorDecl *CD : D->ctors()) { 6631 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6632 if (CD->isTrivial()) 6633 CopyCtorIsTrivial = true; 6634 if (CD->isTrivialForCall()) 6635 CopyCtorIsTrivialForCall = true; 6636 } 6637 } 6638 } 6639 6640 if (D->needsImplicitDestructor()) { 6641 if (!D->defaultedDestructorIsDeleted() && 6642 D->hasTrivialDestructorForCall()) 6643 DtorIsTrivialForCall = true; 6644 } else if (const auto *DD = D->getDestructor()) { 6645 if (!DD->isDeleted() && DD->isTrivialForCall()) 6646 DtorIsTrivialForCall = true; 6647 } 6648 6649 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6650 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6651 return true; 6652 6653 // If a class has a destructor, we'd really like to pass it indirectly 6654 // because it allows us to elide copies. Unfortunately, MSVC makes that 6655 // impossible for small types, which it will pass in a single register or 6656 // stack slot. Most objects with dtors are large-ish, so handle that early. 6657 // We can't call out all large objects as being indirect because there are 6658 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6659 // how we pass large POD types. 6660 6661 // Note: This permits small classes with nontrivial destructors to be 6662 // passed in registers, which is non-conforming. 6663 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6664 uint64_t TypeSize = isAArch64 ? 128 : 64; 6665 6666 if (CopyCtorIsTrivial && 6667 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6668 return true; 6669 return false; 6670 } 6671 6672 // Per C++ [class.temporary]p3, the relevant condition is: 6673 // each copy constructor, move constructor, and destructor of X is 6674 // either trivial or deleted, and X has at least one non-deleted copy 6675 // or move constructor 6676 bool HasNonDeletedCopyOrMove = false; 6677 6678 if (D->needsImplicitCopyConstructor() && 6679 !D->defaultedCopyConstructorIsDeleted()) { 6680 if (!D->hasTrivialCopyConstructorForCall()) 6681 return false; 6682 HasNonDeletedCopyOrMove = true; 6683 } 6684 6685 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6686 !D->defaultedMoveConstructorIsDeleted()) { 6687 if (!D->hasTrivialMoveConstructorForCall()) 6688 return false; 6689 HasNonDeletedCopyOrMove = true; 6690 } 6691 6692 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6693 !D->hasTrivialDestructorForCall()) 6694 return false; 6695 6696 for (const CXXMethodDecl *MD : D->methods()) { 6697 if (MD->isDeleted()) 6698 continue; 6699 6700 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6701 if (CD && CD->isCopyOrMoveConstructor()) 6702 HasNonDeletedCopyOrMove = true; 6703 else if (!isa<CXXDestructorDecl>(MD)) 6704 continue; 6705 6706 if (!MD->isTrivialForCall()) 6707 return false; 6708 } 6709 6710 return HasNonDeletedCopyOrMove; 6711 } 6712 6713 /// Report an error regarding overriding, along with any relevant 6714 /// overridden methods. 6715 /// 6716 /// \param DiagID the primary error to report. 6717 /// \param MD the overriding method. 6718 static bool 6719 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6720 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6721 bool IssuedDiagnostic = false; 6722 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6723 if (Report(O)) { 6724 if (!IssuedDiagnostic) { 6725 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6726 IssuedDiagnostic = true; 6727 } 6728 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6729 } 6730 } 6731 return IssuedDiagnostic; 6732 } 6733 6734 /// Perform semantic checks on a class definition that has been 6735 /// completing, introducing implicitly-declared members, checking for 6736 /// abstract types, etc. 6737 /// 6738 /// \param S The scope in which the class was parsed. Null if we didn't just 6739 /// parse a class definition. 6740 /// \param Record The completed class. 6741 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6742 if (!Record) 6743 return; 6744 6745 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6746 AbstractUsageInfo Info(*this, Record); 6747 CheckAbstractClassUsage(Info, Record); 6748 } 6749 6750 // If this is not an aggregate type and has no user-declared constructor, 6751 // complain about any non-static data members of reference or const scalar 6752 // type, since they will never get initializers. 6753 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6754 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6755 !Record->isLambda()) { 6756 bool Complained = false; 6757 for (const auto *F : Record->fields()) { 6758 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6759 continue; 6760 6761 if (F->getType()->isReferenceType() || 6762 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6763 if (!Complained) { 6764 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6765 << Record->getTagKind() << Record; 6766 Complained = true; 6767 } 6768 6769 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6770 << F->getType()->isReferenceType() 6771 << F->getDeclName(); 6772 } 6773 } 6774 } 6775 6776 if (Record->getIdentifier()) { 6777 // C++ [class.mem]p13: 6778 // If T is the name of a class, then each of the following shall have a 6779 // name different from T: 6780 // - every member of every anonymous union that is a member of class T. 6781 // 6782 // C++ [class.mem]p14: 6783 // In addition, if class T has a user-declared constructor (12.1), every 6784 // non-static data member of class T shall have a name different from T. 6785 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6786 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6787 ++I) { 6788 NamedDecl *D = (*I)->getUnderlyingDecl(); 6789 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6790 Record->hasUserDeclaredConstructor()) || 6791 isa<IndirectFieldDecl>(D)) { 6792 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6793 << D->getDeclName(); 6794 break; 6795 } 6796 } 6797 } 6798 6799 // Warn if the class has virtual methods but non-virtual public destructor. 6800 if (Record->isPolymorphic() && !Record->isDependentType()) { 6801 CXXDestructorDecl *dtor = Record->getDestructor(); 6802 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6803 !Record->hasAttr<FinalAttr>()) 6804 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6805 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6806 } 6807 6808 if (Record->isAbstract()) { 6809 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6810 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6811 << FA->isSpelledAsSealed(); 6812 DiagnoseAbstractType(Record); 6813 } 6814 } 6815 6816 // Warn if the class has a final destructor but is not itself marked final. 6817 if (!Record->hasAttr<FinalAttr>()) { 6818 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6819 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6820 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6821 << FA->isSpelledAsSealed() 6822 << FixItHint::CreateInsertion( 6823 getLocForEndOfToken(Record->getLocation()), 6824 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6825 Diag(Record->getLocation(), 6826 diag::note_final_dtor_non_final_class_silence) 6827 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6828 } 6829 } 6830 } 6831 6832 // See if trivial_abi has to be dropped. 6833 if (Record->hasAttr<TrivialABIAttr>()) 6834 checkIllFormedTrivialABIStruct(*Record); 6835 6836 // Set HasTrivialSpecialMemberForCall if the record has attribute 6837 // "trivial_abi". 6838 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6839 6840 if (HasTrivialABI) 6841 Record->setHasTrivialSpecialMemberForCall(); 6842 6843 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6844 // We check these last because they can depend on the properties of the 6845 // primary comparison functions (==, <=>). 6846 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6847 6848 // Perform checks that can't be done until we know all the properties of a 6849 // member function (whether it's defaulted, deleted, virtual, overriding, 6850 // ...). 6851 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6852 // A static function cannot override anything. 6853 if (MD->getStorageClass() == SC_Static) { 6854 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6855 [](const CXXMethodDecl *) { return true; })) 6856 return; 6857 } 6858 6859 // A deleted function cannot override a non-deleted function and vice 6860 // versa. 6861 if (ReportOverrides(*this, 6862 MD->isDeleted() ? diag::err_deleted_override 6863 : diag::err_non_deleted_override, 6864 MD, [&](const CXXMethodDecl *V) { 6865 return MD->isDeleted() != V->isDeleted(); 6866 })) { 6867 if (MD->isDefaulted() && MD->isDeleted()) 6868 // Explain why this defaulted function was deleted. 6869 DiagnoseDeletedDefaultedFunction(MD); 6870 return; 6871 } 6872 6873 // A consteval function cannot override a non-consteval function and vice 6874 // versa. 6875 if (ReportOverrides(*this, 6876 MD->isConsteval() ? diag::err_consteval_override 6877 : diag::err_non_consteval_override, 6878 MD, [&](const CXXMethodDecl *V) { 6879 return MD->isConsteval() != V->isConsteval(); 6880 })) { 6881 if (MD->isDefaulted() && MD->isDeleted()) 6882 // Explain why this defaulted function was deleted. 6883 DiagnoseDeletedDefaultedFunction(MD); 6884 return; 6885 } 6886 }; 6887 6888 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6889 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6890 return false; 6891 6892 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6893 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6894 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6895 DefaultedSecondaryComparisons.push_back(FD); 6896 return true; 6897 } 6898 6899 CheckExplicitlyDefaultedFunction(S, FD); 6900 return false; 6901 }; 6902 6903 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6904 // Check whether the explicitly-defaulted members are valid. 6905 bool Incomplete = CheckForDefaultedFunction(M); 6906 6907 // Skip the rest of the checks for a member of a dependent class. 6908 if (Record->isDependentType()) 6909 return; 6910 6911 // For an explicitly defaulted or deleted special member, we defer 6912 // determining triviality until the class is complete. That time is now! 6913 CXXSpecialMember CSM = getSpecialMember(M); 6914 if (!M->isImplicit() && !M->isUserProvided()) { 6915 if (CSM != CXXInvalid) { 6916 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6917 // Inform the class that we've finished declaring this member. 6918 Record->finishedDefaultedOrDeletedMember(M); 6919 M->setTrivialForCall( 6920 HasTrivialABI || 6921 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6922 Record->setTrivialForCallFlags(M); 6923 } 6924 } 6925 6926 // Set triviality for the purpose of calls if this is a user-provided 6927 // copy/move constructor or destructor. 6928 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6929 CSM == CXXDestructor) && M->isUserProvided()) { 6930 M->setTrivialForCall(HasTrivialABI); 6931 Record->setTrivialForCallFlags(M); 6932 } 6933 6934 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6935 M->hasAttr<DLLExportAttr>()) { 6936 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6937 M->isTrivial() && 6938 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6939 CSM == CXXDestructor)) 6940 M->dropAttr<DLLExportAttr>(); 6941 6942 if (M->hasAttr<DLLExportAttr>()) { 6943 // Define after any fields with in-class initializers have been parsed. 6944 DelayedDllExportMemberFunctions.push_back(M); 6945 } 6946 } 6947 6948 // Define defaulted constexpr virtual functions that override a base class 6949 // function right away. 6950 // FIXME: We can defer doing this until the vtable is marked as used. 6951 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6952 DefineDefaultedFunction(*this, M, M->getLocation()); 6953 6954 if (!Incomplete) 6955 CheckCompletedMemberFunction(M); 6956 }; 6957 6958 // Check the destructor before any other member function. We need to 6959 // determine whether it's trivial in order to determine whether the claas 6960 // type is a literal type, which is a prerequisite for determining whether 6961 // other special member functions are valid and whether they're implicitly 6962 // 'constexpr'. 6963 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6964 CompleteMemberFunction(Dtor); 6965 6966 bool HasMethodWithOverrideControl = false, 6967 HasOverridingMethodWithoutOverrideControl = false; 6968 for (auto *D : Record->decls()) { 6969 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6970 // FIXME: We could do this check for dependent types with non-dependent 6971 // bases. 6972 if (!Record->isDependentType()) { 6973 // See if a method overloads virtual methods in a base 6974 // class without overriding any. 6975 if (!M->isStatic()) 6976 DiagnoseHiddenVirtualMethods(M); 6977 if (M->hasAttr<OverrideAttr>()) 6978 HasMethodWithOverrideControl = true; 6979 else if (M->size_overridden_methods() > 0) 6980 HasOverridingMethodWithoutOverrideControl = true; 6981 } 6982 6983 if (!isa<CXXDestructorDecl>(M)) 6984 CompleteMemberFunction(M); 6985 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6986 CheckForDefaultedFunction( 6987 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6988 } 6989 } 6990 6991 if (HasOverridingMethodWithoutOverrideControl) { 6992 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6993 for (auto *M : Record->methods()) 6994 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6995 } 6996 6997 // Check the defaulted secondary comparisons after any other member functions. 6998 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6999 CheckExplicitlyDefaultedFunction(S, FD); 7000 7001 // If this is a member function, we deferred checking it until now. 7002 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 7003 CheckCompletedMemberFunction(MD); 7004 } 7005 7006 // ms_struct is a request to use the same ABI rules as MSVC. Check 7007 // whether this class uses any C++ features that are implemented 7008 // completely differently in MSVC, and if so, emit a diagnostic. 7009 // That diagnostic defaults to an error, but we allow projects to 7010 // map it down to a warning (or ignore it). It's a fairly common 7011 // practice among users of the ms_struct pragma to mass-annotate 7012 // headers, sweeping up a bunch of types that the project doesn't 7013 // really rely on MSVC-compatible layout for. We must therefore 7014 // support "ms_struct except for C++ stuff" as a secondary ABI. 7015 // Don't emit this diagnostic if the feature was enabled as a 7016 // language option (as opposed to via a pragma or attribute), as 7017 // the option -mms-bitfields otherwise essentially makes it impossible 7018 // to build C++ code, unless this diagnostic is turned off. 7019 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 7020 (Record->isPolymorphic() || Record->getNumBases())) { 7021 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 7022 } 7023 7024 checkClassLevelDLLAttribute(Record); 7025 checkClassLevelCodeSegAttribute(Record); 7026 7027 bool ClangABICompat4 = 7028 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 7029 TargetInfo::CallingConvKind CCK = 7030 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 7031 bool CanPass = canPassInRegisters(*this, Record, CCK); 7032 7033 // Do not change ArgPassingRestrictions if it has already been set to 7034 // APK_CanNeverPassInRegs. 7035 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 7036 Record->setArgPassingRestrictions(CanPass 7037 ? RecordDecl::APK_CanPassInRegs 7038 : RecordDecl::APK_CannotPassInRegs); 7039 7040 // If canPassInRegisters returns true despite the record having a non-trivial 7041 // destructor, the record is destructed in the callee. This happens only when 7042 // the record or one of its subobjects has a field annotated with trivial_abi 7043 // or a field qualified with ObjC __strong/__weak. 7044 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 7045 Record->setParamDestroyedInCallee(true); 7046 else if (Record->hasNonTrivialDestructor()) 7047 Record->setParamDestroyedInCallee(CanPass); 7048 7049 if (getLangOpts().ForceEmitVTables) { 7050 // If we want to emit all the vtables, we need to mark it as used. This 7051 // is especially required for cases like vtable assumption loads. 7052 MarkVTableUsed(Record->getInnerLocStart(), Record); 7053 } 7054 7055 if (getLangOpts().CUDA) { 7056 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7057 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7058 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7059 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7060 } 7061 } 7062 7063 /// Look up the special member function that would be called by a special 7064 /// member function for a subobject of class type. 7065 /// 7066 /// \param Class The class type of the subobject. 7067 /// \param CSM The kind of special member function. 7068 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7069 /// \param ConstRHS True if this is a copy operation with a const object 7070 /// on its RHS, that is, if the argument to the outer special member 7071 /// function is 'const' and this is not a field marked 'mutable'. 7072 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7073 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7074 unsigned FieldQuals, bool ConstRHS) { 7075 unsigned LHSQuals = 0; 7076 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7077 LHSQuals = FieldQuals; 7078 7079 unsigned RHSQuals = FieldQuals; 7080 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7081 RHSQuals = 0; 7082 else if (ConstRHS) 7083 RHSQuals |= Qualifiers::Const; 7084 7085 return S.LookupSpecialMember(Class, CSM, 7086 RHSQuals & Qualifiers::Const, 7087 RHSQuals & Qualifiers::Volatile, 7088 false, 7089 LHSQuals & Qualifiers::Const, 7090 LHSQuals & Qualifiers::Volatile); 7091 } 7092 7093 class Sema::InheritedConstructorInfo { 7094 Sema &S; 7095 SourceLocation UseLoc; 7096 7097 /// A mapping from the base classes through which the constructor was 7098 /// inherited to the using shadow declaration in that base class (or a null 7099 /// pointer if the constructor was declared in that base class). 7100 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7101 InheritedFromBases; 7102 7103 public: 7104 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7105 ConstructorUsingShadowDecl *Shadow) 7106 : S(S), UseLoc(UseLoc) { 7107 bool DiagnosedMultipleConstructedBases = false; 7108 CXXRecordDecl *ConstructedBase = nullptr; 7109 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7110 7111 // Find the set of such base class subobjects and check that there's a 7112 // unique constructed subobject. 7113 for (auto *D : Shadow->redecls()) { 7114 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7115 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7116 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7117 7118 InheritedFromBases.insert( 7119 std::make_pair(DNominatedBase->getCanonicalDecl(), 7120 DShadow->getNominatedBaseClassShadowDecl())); 7121 if (DShadow->constructsVirtualBase()) 7122 InheritedFromBases.insert( 7123 std::make_pair(DConstructedBase->getCanonicalDecl(), 7124 DShadow->getConstructedBaseClassShadowDecl())); 7125 else 7126 assert(DNominatedBase == DConstructedBase); 7127 7128 // [class.inhctor.init]p2: 7129 // If the constructor was inherited from multiple base class subobjects 7130 // of type B, the program is ill-formed. 7131 if (!ConstructedBase) { 7132 ConstructedBase = DConstructedBase; 7133 ConstructedBaseIntroducer = D->getIntroducer(); 7134 } else if (ConstructedBase != DConstructedBase && 7135 !Shadow->isInvalidDecl()) { 7136 if (!DiagnosedMultipleConstructedBases) { 7137 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7138 << Shadow->getTargetDecl(); 7139 S.Diag(ConstructedBaseIntroducer->getLocation(), 7140 diag::note_ambiguous_inherited_constructor_using) 7141 << ConstructedBase; 7142 DiagnosedMultipleConstructedBases = true; 7143 } 7144 S.Diag(D->getIntroducer()->getLocation(), 7145 diag::note_ambiguous_inherited_constructor_using) 7146 << DConstructedBase; 7147 } 7148 } 7149 7150 if (DiagnosedMultipleConstructedBases) 7151 Shadow->setInvalidDecl(); 7152 } 7153 7154 /// Find the constructor to use for inherited construction of a base class, 7155 /// and whether that base class constructor inherits the constructor from a 7156 /// virtual base class (in which case it won't actually invoke it). 7157 std::pair<CXXConstructorDecl *, bool> 7158 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7159 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7160 if (It == InheritedFromBases.end()) 7161 return std::make_pair(nullptr, false); 7162 7163 // This is an intermediary class. 7164 if (It->second) 7165 return std::make_pair( 7166 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7167 It->second->constructsVirtualBase()); 7168 7169 // This is the base class from which the constructor was inherited. 7170 return std::make_pair(Ctor, false); 7171 } 7172 }; 7173 7174 /// Is the special member function which would be selected to perform the 7175 /// specified operation on the specified class type a constexpr constructor? 7176 static bool 7177 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7178 Sema::CXXSpecialMember CSM, unsigned Quals, 7179 bool ConstRHS, 7180 CXXConstructorDecl *InheritedCtor = nullptr, 7181 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7182 // If we're inheriting a constructor, see if we need to call it for this base 7183 // class. 7184 if (InheritedCtor) { 7185 assert(CSM == Sema::CXXDefaultConstructor); 7186 auto BaseCtor = 7187 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7188 if (BaseCtor) 7189 return BaseCtor->isConstexpr(); 7190 } 7191 7192 if (CSM == Sema::CXXDefaultConstructor) 7193 return ClassDecl->hasConstexprDefaultConstructor(); 7194 if (CSM == Sema::CXXDestructor) 7195 return ClassDecl->hasConstexprDestructor(); 7196 7197 Sema::SpecialMemberOverloadResult SMOR = 7198 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7199 if (!SMOR.getMethod()) 7200 // A constructor we wouldn't select can't be "involved in initializing" 7201 // anything. 7202 return true; 7203 return SMOR.getMethod()->isConstexpr(); 7204 } 7205 7206 /// Determine whether the specified special member function would be constexpr 7207 /// if it were implicitly defined. 7208 static bool defaultedSpecialMemberIsConstexpr( 7209 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7210 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7211 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7212 if (!S.getLangOpts().CPlusPlus11) 7213 return false; 7214 7215 // C++11 [dcl.constexpr]p4: 7216 // In the definition of a constexpr constructor [...] 7217 bool Ctor = true; 7218 switch (CSM) { 7219 case Sema::CXXDefaultConstructor: 7220 if (Inherited) 7221 break; 7222 // Since default constructor lookup is essentially trivial (and cannot 7223 // involve, for instance, template instantiation), we compute whether a 7224 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7225 // 7226 // This is important for performance; we need to know whether the default 7227 // constructor is constexpr to determine whether the type is a literal type. 7228 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7229 7230 case Sema::CXXCopyConstructor: 7231 case Sema::CXXMoveConstructor: 7232 // For copy or move constructors, we need to perform overload resolution. 7233 break; 7234 7235 case Sema::CXXCopyAssignment: 7236 case Sema::CXXMoveAssignment: 7237 if (!S.getLangOpts().CPlusPlus14) 7238 return false; 7239 // In C++1y, we need to perform overload resolution. 7240 Ctor = false; 7241 break; 7242 7243 case Sema::CXXDestructor: 7244 return ClassDecl->defaultedDestructorIsConstexpr(); 7245 7246 case Sema::CXXInvalid: 7247 return false; 7248 } 7249 7250 // -- if the class is a non-empty union, or for each non-empty anonymous 7251 // union member of a non-union class, exactly one non-static data member 7252 // shall be initialized; [DR1359] 7253 // 7254 // If we squint, this is guaranteed, since exactly one non-static data member 7255 // will be initialized (if the constructor isn't deleted), we just don't know 7256 // which one. 7257 if (Ctor && ClassDecl->isUnion()) 7258 return CSM == Sema::CXXDefaultConstructor 7259 ? ClassDecl->hasInClassInitializer() || 7260 !ClassDecl->hasVariantMembers() 7261 : true; 7262 7263 // -- the class shall not have any virtual base classes; 7264 if (Ctor && ClassDecl->getNumVBases()) 7265 return false; 7266 7267 // C++1y [class.copy]p26: 7268 // -- [the class] is a literal type, and 7269 if (!Ctor && !ClassDecl->isLiteral()) 7270 return false; 7271 7272 // -- every constructor involved in initializing [...] base class 7273 // sub-objects shall be a constexpr constructor; 7274 // -- the assignment operator selected to copy/move each direct base 7275 // class is a constexpr function, and 7276 for (const auto &B : ClassDecl->bases()) { 7277 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7278 if (!BaseType) continue; 7279 7280 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7281 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7282 InheritedCtor, Inherited)) 7283 return false; 7284 } 7285 7286 // -- every constructor involved in initializing non-static data members 7287 // [...] shall be a constexpr constructor; 7288 // -- every non-static data member and base class sub-object shall be 7289 // initialized 7290 // -- for each non-static data member of X that is of class type (or array 7291 // thereof), the assignment operator selected to copy/move that member is 7292 // a constexpr function 7293 for (const auto *F : ClassDecl->fields()) { 7294 if (F->isInvalidDecl()) 7295 continue; 7296 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7297 continue; 7298 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7299 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7300 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7301 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7302 BaseType.getCVRQualifiers(), 7303 ConstArg && !F->isMutable())) 7304 return false; 7305 } else if (CSM == Sema::CXXDefaultConstructor) { 7306 return false; 7307 } 7308 } 7309 7310 // All OK, it's constexpr! 7311 return true; 7312 } 7313 7314 namespace { 7315 /// RAII object to register a defaulted function as having its exception 7316 /// specification computed. 7317 struct ComputingExceptionSpec { 7318 Sema &S; 7319 7320 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7321 : S(S) { 7322 Sema::CodeSynthesisContext Ctx; 7323 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7324 Ctx.PointOfInstantiation = Loc; 7325 Ctx.Entity = FD; 7326 S.pushCodeSynthesisContext(Ctx); 7327 } 7328 ~ComputingExceptionSpec() { 7329 S.popCodeSynthesisContext(); 7330 } 7331 }; 7332 } 7333 7334 static Sema::ImplicitExceptionSpecification 7335 ComputeDefaultedSpecialMemberExceptionSpec( 7336 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7337 Sema::InheritedConstructorInfo *ICI); 7338 7339 static Sema::ImplicitExceptionSpecification 7340 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7341 FunctionDecl *FD, 7342 Sema::DefaultedComparisonKind DCK); 7343 7344 static Sema::ImplicitExceptionSpecification 7345 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7346 auto DFK = S.getDefaultedFunctionKind(FD); 7347 if (DFK.isSpecialMember()) 7348 return ComputeDefaultedSpecialMemberExceptionSpec( 7349 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7350 if (DFK.isComparison()) 7351 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7352 DFK.asComparison()); 7353 7354 auto *CD = cast<CXXConstructorDecl>(FD); 7355 assert(CD->getInheritedConstructor() && 7356 "only defaulted functions and inherited constructors have implicit " 7357 "exception specs"); 7358 Sema::InheritedConstructorInfo ICI( 7359 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7360 return ComputeDefaultedSpecialMemberExceptionSpec( 7361 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7362 } 7363 7364 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7365 CXXMethodDecl *MD) { 7366 FunctionProtoType::ExtProtoInfo EPI; 7367 7368 // Build an exception specification pointing back at this member. 7369 EPI.ExceptionSpec.Type = EST_Unevaluated; 7370 EPI.ExceptionSpec.SourceDecl = MD; 7371 7372 // Set the calling convention to the default for C++ instance methods. 7373 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7374 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7375 /*IsCXXMethod=*/true)); 7376 return EPI; 7377 } 7378 7379 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7380 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7381 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7382 return; 7383 7384 // Evaluate the exception specification. 7385 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7386 auto ESI = IES.getExceptionSpec(); 7387 7388 // Update the type of the special member to use it. 7389 UpdateExceptionSpec(FD, ESI); 7390 } 7391 7392 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7393 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7394 7395 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7396 if (!DefKind) { 7397 assert(FD->getDeclContext()->isDependentContext()); 7398 return; 7399 } 7400 7401 if (DefKind.isComparison()) 7402 UnusedPrivateFields.clear(); 7403 7404 if (DefKind.isSpecialMember() 7405 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7406 DefKind.asSpecialMember()) 7407 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7408 FD->setInvalidDecl(); 7409 } 7410 7411 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7412 CXXSpecialMember CSM) { 7413 CXXRecordDecl *RD = MD->getParent(); 7414 7415 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7416 "not an explicitly-defaulted special member"); 7417 7418 // Defer all checking for special members of a dependent type. 7419 if (RD->isDependentType()) 7420 return false; 7421 7422 // Whether this was the first-declared instance of the constructor. 7423 // This affects whether we implicitly add an exception spec and constexpr. 7424 bool First = MD == MD->getCanonicalDecl(); 7425 7426 bool HadError = false; 7427 7428 // C++11 [dcl.fct.def.default]p1: 7429 // A function that is explicitly defaulted shall 7430 // -- be a special member function [...] (checked elsewhere), 7431 // -- have the same type (except for ref-qualifiers, and except that a 7432 // copy operation can take a non-const reference) as an implicit 7433 // declaration, and 7434 // -- not have default arguments. 7435 // C++2a changes the second bullet to instead delete the function if it's 7436 // defaulted on its first declaration, unless it's "an assignment operator, 7437 // and its return type differs or its parameter type is not a reference". 7438 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7439 bool ShouldDeleteForTypeMismatch = false; 7440 unsigned ExpectedParams = 1; 7441 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7442 ExpectedParams = 0; 7443 if (MD->getNumParams() != ExpectedParams) { 7444 // This checks for default arguments: a copy or move constructor with a 7445 // default argument is classified as a default constructor, and assignment 7446 // operations and destructors can't have default arguments. 7447 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7448 << CSM << MD->getSourceRange(); 7449 HadError = true; 7450 } else if (MD->isVariadic()) { 7451 if (DeleteOnTypeMismatch) 7452 ShouldDeleteForTypeMismatch = true; 7453 else { 7454 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7455 << CSM << MD->getSourceRange(); 7456 HadError = true; 7457 } 7458 } 7459 7460 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7461 7462 bool CanHaveConstParam = false; 7463 if (CSM == CXXCopyConstructor) 7464 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7465 else if (CSM == CXXCopyAssignment) 7466 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7467 7468 QualType ReturnType = Context.VoidTy; 7469 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7470 // Check for return type matching. 7471 ReturnType = Type->getReturnType(); 7472 7473 QualType DeclType = Context.getTypeDeclType(RD); 7474 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7475 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7476 7477 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7478 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7479 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7480 HadError = true; 7481 } 7482 7483 // A defaulted special member cannot have cv-qualifiers. 7484 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7485 if (DeleteOnTypeMismatch) 7486 ShouldDeleteForTypeMismatch = true; 7487 else { 7488 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7489 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7490 HadError = true; 7491 } 7492 } 7493 } 7494 7495 // Check for parameter type matching. 7496 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7497 bool HasConstParam = false; 7498 if (ExpectedParams && ArgType->isReferenceType()) { 7499 // Argument must be reference to possibly-const T. 7500 QualType ReferentType = ArgType->getPointeeType(); 7501 HasConstParam = ReferentType.isConstQualified(); 7502 7503 if (ReferentType.isVolatileQualified()) { 7504 if (DeleteOnTypeMismatch) 7505 ShouldDeleteForTypeMismatch = true; 7506 else { 7507 Diag(MD->getLocation(), 7508 diag::err_defaulted_special_member_volatile_param) << CSM; 7509 HadError = true; 7510 } 7511 } 7512 7513 if (HasConstParam && !CanHaveConstParam) { 7514 if (DeleteOnTypeMismatch) 7515 ShouldDeleteForTypeMismatch = true; 7516 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7517 Diag(MD->getLocation(), 7518 diag::err_defaulted_special_member_copy_const_param) 7519 << (CSM == CXXCopyAssignment); 7520 // FIXME: Explain why this special member can't be const. 7521 HadError = true; 7522 } else { 7523 Diag(MD->getLocation(), 7524 diag::err_defaulted_special_member_move_const_param) 7525 << (CSM == CXXMoveAssignment); 7526 HadError = true; 7527 } 7528 } 7529 } else if (ExpectedParams) { 7530 // A copy assignment operator can take its argument by value, but a 7531 // defaulted one cannot. 7532 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7533 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7534 HadError = true; 7535 } 7536 7537 // C++11 [dcl.fct.def.default]p2: 7538 // An explicitly-defaulted function may be declared constexpr only if it 7539 // would have been implicitly declared as constexpr, 7540 // Do not apply this rule to members of class templates, since core issue 1358 7541 // makes such functions always instantiate to constexpr functions. For 7542 // functions which cannot be constexpr (for non-constructors in C++11 and for 7543 // destructors in C++14 and C++17), this is checked elsewhere. 7544 // 7545 // FIXME: This should not apply if the member is deleted. 7546 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7547 HasConstParam); 7548 if ((getLangOpts().CPlusPlus20 || 7549 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7550 : isa<CXXConstructorDecl>(MD))) && 7551 MD->isConstexpr() && !Constexpr && 7552 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7553 Diag(MD->getBeginLoc(), MD->isConsteval() 7554 ? diag::err_incorrect_defaulted_consteval 7555 : diag::err_incorrect_defaulted_constexpr) 7556 << CSM; 7557 // FIXME: Explain why the special member can't be constexpr. 7558 HadError = true; 7559 } 7560 7561 if (First) { 7562 // C++2a [dcl.fct.def.default]p3: 7563 // If a function is explicitly defaulted on its first declaration, it is 7564 // implicitly considered to be constexpr if the implicit declaration 7565 // would be. 7566 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7567 ? ConstexprSpecKind::Consteval 7568 : ConstexprSpecKind::Constexpr) 7569 : ConstexprSpecKind::Unspecified); 7570 7571 if (!Type->hasExceptionSpec()) { 7572 // C++2a [except.spec]p3: 7573 // If a declaration of a function does not have a noexcept-specifier 7574 // [and] is defaulted on its first declaration, [...] the exception 7575 // specification is as specified below 7576 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7577 EPI.ExceptionSpec.Type = EST_Unevaluated; 7578 EPI.ExceptionSpec.SourceDecl = MD; 7579 MD->setType(Context.getFunctionType(ReturnType, 7580 llvm::makeArrayRef(&ArgType, 7581 ExpectedParams), 7582 EPI)); 7583 } 7584 } 7585 7586 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7587 if (First) { 7588 SetDeclDeleted(MD, MD->getLocation()); 7589 if (!inTemplateInstantiation() && !HadError) { 7590 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7591 if (ShouldDeleteForTypeMismatch) { 7592 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7593 } else { 7594 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7595 } 7596 } 7597 if (ShouldDeleteForTypeMismatch && !HadError) { 7598 Diag(MD->getLocation(), 7599 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7600 } 7601 } else { 7602 // C++11 [dcl.fct.def.default]p4: 7603 // [For a] user-provided explicitly-defaulted function [...] if such a 7604 // function is implicitly defined as deleted, the program is ill-formed. 7605 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7606 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7607 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7608 HadError = true; 7609 } 7610 } 7611 7612 return HadError; 7613 } 7614 7615 namespace { 7616 /// Helper class for building and checking a defaulted comparison. 7617 /// 7618 /// Defaulted functions are built in two phases: 7619 /// 7620 /// * First, the set of operations that the function will perform are 7621 /// identified, and some of them are checked. If any of the checked 7622 /// operations is invalid in certain ways, the comparison function is 7623 /// defined as deleted and no body is built. 7624 /// * Then, if the function is not defined as deleted, the body is built. 7625 /// 7626 /// This is accomplished by performing two visitation steps over the eventual 7627 /// body of the function. 7628 template<typename Derived, typename ResultList, typename Result, 7629 typename Subobject> 7630 class DefaultedComparisonVisitor { 7631 public: 7632 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7633 7634 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7635 DefaultedComparisonKind DCK) 7636 : S(S), RD(RD), FD(FD), DCK(DCK) { 7637 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7638 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7639 // UnresolvedSet to avoid this copy. 7640 Fns.assign(Info->getUnqualifiedLookups().begin(), 7641 Info->getUnqualifiedLookups().end()); 7642 } 7643 } 7644 7645 ResultList visit() { 7646 // The type of an lvalue naming a parameter of this function. 7647 QualType ParamLvalType = 7648 FD->getParamDecl(0)->getType().getNonReferenceType(); 7649 7650 ResultList Results; 7651 7652 switch (DCK) { 7653 case DefaultedComparisonKind::None: 7654 llvm_unreachable("not a defaulted comparison"); 7655 7656 case DefaultedComparisonKind::Equal: 7657 case DefaultedComparisonKind::ThreeWay: 7658 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7659 return Results; 7660 7661 case DefaultedComparisonKind::NotEqual: 7662 case DefaultedComparisonKind::Relational: 7663 Results.add(getDerived().visitExpandedSubobject( 7664 ParamLvalType, getDerived().getCompleteObject())); 7665 return Results; 7666 } 7667 llvm_unreachable(""); 7668 } 7669 7670 protected: 7671 Derived &getDerived() { return static_cast<Derived&>(*this); } 7672 7673 /// Visit the expanded list of subobjects of the given type, as specified in 7674 /// C++2a [class.compare.default]. 7675 /// 7676 /// \return \c true if the ResultList object said we're done, \c false if not. 7677 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7678 Qualifiers Quals) { 7679 // C++2a [class.compare.default]p4: 7680 // The direct base class subobjects of C 7681 for (CXXBaseSpecifier &Base : Record->bases()) 7682 if (Results.add(getDerived().visitSubobject( 7683 S.Context.getQualifiedType(Base.getType(), Quals), 7684 getDerived().getBase(&Base)))) 7685 return true; 7686 7687 // followed by the non-static data members of C 7688 for (FieldDecl *Field : Record->fields()) { 7689 // Recursively expand anonymous structs. 7690 if (Field->isAnonymousStructOrUnion()) { 7691 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7692 Quals)) 7693 return true; 7694 continue; 7695 } 7696 7697 // Figure out the type of an lvalue denoting this field. 7698 Qualifiers FieldQuals = Quals; 7699 if (Field->isMutable()) 7700 FieldQuals.removeConst(); 7701 QualType FieldType = 7702 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7703 7704 if (Results.add(getDerived().visitSubobject( 7705 FieldType, getDerived().getField(Field)))) 7706 return true; 7707 } 7708 7709 // form a list of subobjects. 7710 return false; 7711 } 7712 7713 Result visitSubobject(QualType Type, Subobject Subobj) { 7714 // In that list, any subobject of array type is recursively expanded 7715 const ArrayType *AT = S.Context.getAsArrayType(Type); 7716 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7717 return getDerived().visitSubobjectArray(CAT->getElementType(), 7718 CAT->getSize(), Subobj); 7719 return getDerived().visitExpandedSubobject(Type, Subobj); 7720 } 7721 7722 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7723 Subobject Subobj) { 7724 return getDerived().visitSubobject(Type, Subobj); 7725 } 7726 7727 protected: 7728 Sema &S; 7729 CXXRecordDecl *RD; 7730 FunctionDecl *FD; 7731 DefaultedComparisonKind DCK; 7732 UnresolvedSet<16> Fns; 7733 }; 7734 7735 /// Information about a defaulted comparison, as determined by 7736 /// DefaultedComparisonAnalyzer. 7737 struct DefaultedComparisonInfo { 7738 bool Deleted = false; 7739 bool Constexpr = true; 7740 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7741 7742 static DefaultedComparisonInfo deleted() { 7743 DefaultedComparisonInfo Deleted; 7744 Deleted.Deleted = true; 7745 return Deleted; 7746 } 7747 7748 bool add(const DefaultedComparisonInfo &R) { 7749 Deleted |= R.Deleted; 7750 Constexpr &= R.Constexpr; 7751 Category = commonComparisonType(Category, R.Category); 7752 return Deleted; 7753 } 7754 }; 7755 7756 /// An element in the expanded list of subobjects of a defaulted comparison, as 7757 /// specified in C++2a [class.compare.default]p4. 7758 struct DefaultedComparisonSubobject { 7759 enum { CompleteObject, Member, Base } Kind; 7760 NamedDecl *Decl; 7761 SourceLocation Loc; 7762 }; 7763 7764 /// A visitor over the notional body of a defaulted comparison that determines 7765 /// whether that body would be deleted or constexpr. 7766 class DefaultedComparisonAnalyzer 7767 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7768 DefaultedComparisonInfo, 7769 DefaultedComparisonInfo, 7770 DefaultedComparisonSubobject> { 7771 public: 7772 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7773 7774 private: 7775 DiagnosticKind Diagnose; 7776 7777 public: 7778 using Base = DefaultedComparisonVisitor; 7779 using Result = DefaultedComparisonInfo; 7780 using Subobject = DefaultedComparisonSubobject; 7781 7782 friend Base; 7783 7784 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7785 DefaultedComparisonKind DCK, 7786 DiagnosticKind Diagnose = NoDiagnostics) 7787 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7788 7789 Result visit() { 7790 if ((DCK == DefaultedComparisonKind::Equal || 7791 DCK == DefaultedComparisonKind::ThreeWay) && 7792 RD->hasVariantMembers()) { 7793 // C++2a [class.compare.default]p2 [P2002R0]: 7794 // A defaulted comparison operator function for class C is defined as 7795 // deleted if [...] C has variant members. 7796 if (Diagnose == ExplainDeleted) { 7797 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7798 << FD << RD->isUnion() << RD; 7799 } 7800 return Result::deleted(); 7801 } 7802 7803 return Base::visit(); 7804 } 7805 7806 private: 7807 Subobject getCompleteObject() { 7808 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7809 } 7810 7811 Subobject getBase(CXXBaseSpecifier *Base) { 7812 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7813 Base->getBaseTypeLoc()}; 7814 } 7815 7816 Subobject getField(FieldDecl *Field) { 7817 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7818 } 7819 7820 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7821 // C++2a [class.compare.default]p2 [P2002R0]: 7822 // A defaulted <=> or == operator function for class C is defined as 7823 // deleted if any non-static data member of C is of reference type 7824 if (Type->isReferenceType()) { 7825 if (Diagnose == ExplainDeleted) { 7826 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7827 << FD << RD; 7828 } 7829 return Result::deleted(); 7830 } 7831 7832 // [...] Let xi be an lvalue denoting the ith element [...] 7833 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7834 Expr *Args[] = {&Xi, &Xi}; 7835 7836 // All operators start by trying to apply that same operator recursively. 7837 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7838 assert(OO != OO_None && "not an overloaded operator!"); 7839 return visitBinaryOperator(OO, Args, Subobj); 7840 } 7841 7842 Result 7843 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7844 Subobject Subobj, 7845 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7846 // Note that there is no need to consider rewritten candidates here if 7847 // we've already found there is no viable 'operator<=>' candidate (and are 7848 // considering synthesizing a '<=>' from '==' and '<'). 7849 OverloadCandidateSet CandidateSet( 7850 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7851 OverloadCandidateSet::OperatorRewriteInfo( 7852 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7853 7854 /// C++2a [class.compare.default]p1 [P2002R0]: 7855 /// [...] the defaulted function itself is never a candidate for overload 7856 /// resolution [...] 7857 CandidateSet.exclude(FD); 7858 7859 if (Args[0]->getType()->isOverloadableType()) 7860 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7861 else 7862 // FIXME: We determine whether this is a valid expression by checking to 7863 // see if there's a viable builtin operator candidate for it. That isn't 7864 // really what the rules ask us to do, but should give the right results. 7865 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7866 7867 Result R; 7868 7869 OverloadCandidateSet::iterator Best; 7870 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7871 case OR_Success: { 7872 // C++2a [class.compare.secondary]p2 [P2002R0]: 7873 // The operator function [...] is defined as deleted if [...] the 7874 // candidate selected by overload resolution is not a rewritten 7875 // candidate. 7876 if ((DCK == DefaultedComparisonKind::NotEqual || 7877 DCK == DefaultedComparisonKind::Relational) && 7878 !Best->RewriteKind) { 7879 if (Diagnose == ExplainDeleted) { 7880 if (Best->Function) { 7881 S.Diag(Best->Function->getLocation(), 7882 diag::note_defaulted_comparison_not_rewritten_callee) 7883 << FD; 7884 } else { 7885 assert(Best->Conversions.size() == 2 && 7886 Best->Conversions[0].isUserDefined() && 7887 "non-user-defined conversion from class to built-in " 7888 "comparison"); 7889 S.Diag(Best->Conversions[0] 7890 .UserDefined.FoundConversionFunction.getDecl() 7891 ->getLocation(), 7892 diag::note_defaulted_comparison_not_rewritten_conversion) 7893 << FD; 7894 } 7895 } 7896 return Result::deleted(); 7897 } 7898 7899 // Throughout C++2a [class.compare]: if overload resolution does not 7900 // result in a usable function, the candidate function is defined as 7901 // deleted. This requires that we selected an accessible function. 7902 // 7903 // Note that this only considers the access of the function when named 7904 // within the type of the subobject, and not the access path for any 7905 // derived-to-base conversion. 7906 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7907 if (ArgClass && Best->FoundDecl.getDecl() && 7908 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7909 QualType ObjectType = Subobj.Kind == Subobject::Member 7910 ? Args[0]->getType() 7911 : S.Context.getRecordType(RD); 7912 if (!S.isMemberAccessibleForDeletion( 7913 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7914 Diagnose == ExplainDeleted 7915 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7916 << FD << Subobj.Kind << Subobj.Decl 7917 : S.PDiag())) 7918 return Result::deleted(); 7919 } 7920 7921 bool NeedsDeducing = 7922 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7923 7924 if (FunctionDecl *BestFD = Best->Function) { 7925 // C++2a [class.compare.default]p3 [P2002R0]: 7926 // A defaulted comparison function is constexpr-compatible if 7927 // [...] no overlod resolution performed [...] results in a 7928 // non-constexpr function. 7929 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7930 // If it's not constexpr, explain why not. 7931 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7932 if (Subobj.Kind != Subobject::CompleteObject) 7933 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7934 << Subobj.Kind << Subobj.Decl; 7935 S.Diag(BestFD->getLocation(), 7936 diag::note_defaulted_comparison_not_constexpr_here); 7937 // Bail out after explaining; we don't want any more notes. 7938 return Result::deleted(); 7939 } 7940 R.Constexpr &= BestFD->isConstexpr(); 7941 7942 if (NeedsDeducing) { 7943 // If any callee has an undeduced return type, deduce it now. 7944 // FIXME: It's not clear how a failure here should be handled. For 7945 // now, we produce an eager diagnostic, because that is forward 7946 // compatible with most (all?) other reasonable options. 7947 if (BestFD->getReturnType()->isUndeducedType() && 7948 S.DeduceReturnType(BestFD, FD->getLocation(), 7949 /*Diagnose=*/false)) { 7950 // Don't produce a duplicate error when asked to explain why the 7951 // comparison is deleted: we diagnosed that when initially checking 7952 // the defaulted operator. 7953 if (Diagnose == NoDiagnostics) { 7954 S.Diag( 7955 FD->getLocation(), 7956 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7957 << Subobj.Kind << Subobj.Decl; 7958 S.Diag( 7959 Subobj.Loc, 7960 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7961 << Subobj.Kind << Subobj.Decl; 7962 S.Diag(BestFD->getLocation(), 7963 diag::note_defaulted_comparison_cannot_deduce_callee) 7964 << Subobj.Kind << Subobj.Decl; 7965 } 7966 return Result::deleted(); 7967 } 7968 auto *Info = S.Context.CompCategories.lookupInfoForType( 7969 BestFD->getCallResultType()); 7970 if (!Info) { 7971 if (Diagnose == ExplainDeleted) { 7972 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7973 << Subobj.Kind << Subobj.Decl 7974 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7975 S.Diag(BestFD->getLocation(), 7976 diag::note_defaulted_comparison_cannot_deduce_callee) 7977 << Subobj.Kind << Subobj.Decl; 7978 } 7979 return Result::deleted(); 7980 } 7981 R.Category = Info->Kind; 7982 } 7983 } else { 7984 QualType T = Best->BuiltinParamTypes[0]; 7985 assert(T == Best->BuiltinParamTypes[1] && 7986 "builtin comparison for different types?"); 7987 assert(Best->BuiltinParamTypes[2].isNull() && 7988 "invalid builtin comparison"); 7989 7990 if (NeedsDeducing) { 7991 Optional<ComparisonCategoryType> Cat = 7992 getComparisonCategoryForBuiltinCmp(T); 7993 assert(Cat && "no category for builtin comparison?"); 7994 R.Category = *Cat; 7995 } 7996 } 7997 7998 // Note that we might be rewriting to a different operator. That call is 7999 // not considered until we come to actually build the comparison function. 8000 break; 8001 } 8002 8003 case OR_Ambiguous: 8004 if (Diagnose == ExplainDeleted) { 8005 unsigned Kind = 0; 8006 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 8007 Kind = OO == OO_EqualEqual ? 1 : 2; 8008 CandidateSet.NoteCandidates( 8009 PartialDiagnosticAt( 8010 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 8011 << FD << Kind << Subobj.Kind << Subobj.Decl), 8012 S, OCD_AmbiguousCandidates, Args); 8013 } 8014 R = Result::deleted(); 8015 break; 8016 8017 case OR_Deleted: 8018 if (Diagnose == ExplainDeleted) { 8019 if ((DCK == DefaultedComparisonKind::NotEqual || 8020 DCK == DefaultedComparisonKind::Relational) && 8021 !Best->RewriteKind) { 8022 S.Diag(Best->Function->getLocation(), 8023 diag::note_defaulted_comparison_not_rewritten_callee) 8024 << FD; 8025 } else { 8026 S.Diag(Subobj.Loc, 8027 diag::note_defaulted_comparison_calls_deleted) 8028 << FD << Subobj.Kind << Subobj.Decl; 8029 S.NoteDeletedFunction(Best->Function); 8030 } 8031 } 8032 R = Result::deleted(); 8033 break; 8034 8035 case OR_No_Viable_Function: 8036 // If there's no usable candidate, we're done unless we can rewrite a 8037 // '<=>' in terms of '==' and '<'. 8038 if (OO == OO_Spaceship && 8039 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 8040 // For any kind of comparison category return type, we need a usable 8041 // '==' and a usable '<'. 8042 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 8043 &CandidateSet))) 8044 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 8045 break; 8046 } 8047 8048 if (Diagnose == ExplainDeleted) { 8049 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 8050 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 8051 8052 // For a three-way comparison, list both the candidates for the 8053 // original operator and the candidates for the synthesized operator. 8054 if (SpaceshipCandidates) { 8055 SpaceshipCandidates->NoteCandidates( 8056 S, Args, 8057 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8058 Args, FD->getLocation())); 8059 S.Diag(Subobj.Loc, 8060 diag::note_defaulted_comparison_no_viable_function_synthesized) 8061 << (OO == OO_EqualEqual ? 0 : 1); 8062 } 8063 8064 CandidateSet.NoteCandidates( 8065 S, Args, 8066 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8067 FD->getLocation())); 8068 } 8069 R = Result::deleted(); 8070 break; 8071 } 8072 8073 return R; 8074 } 8075 }; 8076 8077 /// A list of statements. 8078 struct StmtListResult { 8079 bool IsInvalid = false; 8080 llvm::SmallVector<Stmt*, 16> Stmts; 8081 8082 bool add(const StmtResult &S) { 8083 IsInvalid |= S.isInvalid(); 8084 if (IsInvalid) 8085 return true; 8086 Stmts.push_back(S.get()); 8087 return false; 8088 } 8089 }; 8090 8091 /// A visitor over the notional body of a defaulted comparison that synthesizes 8092 /// the actual body. 8093 class DefaultedComparisonSynthesizer 8094 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8095 StmtListResult, StmtResult, 8096 std::pair<ExprResult, ExprResult>> { 8097 SourceLocation Loc; 8098 unsigned ArrayDepth = 0; 8099 8100 public: 8101 using Base = DefaultedComparisonVisitor; 8102 using ExprPair = std::pair<ExprResult, ExprResult>; 8103 8104 friend Base; 8105 8106 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8107 DefaultedComparisonKind DCK, 8108 SourceLocation BodyLoc) 8109 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8110 8111 /// Build a suitable function body for this defaulted comparison operator. 8112 StmtResult build() { 8113 Sema::CompoundScopeRAII CompoundScope(S); 8114 8115 StmtListResult Stmts = visit(); 8116 if (Stmts.IsInvalid) 8117 return StmtError(); 8118 8119 ExprResult RetVal; 8120 switch (DCK) { 8121 case DefaultedComparisonKind::None: 8122 llvm_unreachable("not a defaulted comparison"); 8123 8124 case DefaultedComparisonKind::Equal: { 8125 // C++2a [class.eq]p3: 8126 // [...] compar[e] the corresponding elements [...] until the first 8127 // index i where xi == yi yields [...] false. If no such index exists, 8128 // V is true. Otherwise, V is false. 8129 // 8130 // Join the comparisons with '&&'s and return the result. Use a right 8131 // fold (traversing the conditions right-to-left), because that 8132 // short-circuits more naturally. 8133 auto OldStmts = std::move(Stmts.Stmts); 8134 Stmts.Stmts.clear(); 8135 ExprResult CmpSoFar; 8136 // Finish a particular comparison chain. 8137 auto FinishCmp = [&] { 8138 if (Expr *Prior = CmpSoFar.get()) { 8139 // Convert the last expression to 'return ...;' 8140 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8141 RetVal = CmpSoFar; 8142 // Convert any prior comparison to 'if (!(...)) return false;' 8143 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8144 return true; 8145 CmpSoFar = ExprResult(); 8146 } 8147 return false; 8148 }; 8149 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8150 Expr *E = dyn_cast<Expr>(EAsStmt); 8151 if (!E) { 8152 // Found an array comparison. 8153 if (FinishCmp() || Stmts.add(EAsStmt)) 8154 return StmtError(); 8155 continue; 8156 } 8157 8158 if (CmpSoFar.isUnset()) { 8159 CmpSoFar = E; 8160 continue; 8161 } 8162 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8163 if (CmpSoFar.isInvalid()) 8164 return StmtError(); 8165 } 8166 if (FinishCmp()) 8167 return StmtError(); 8168 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8169 // If no such index exists, V is true. 8170 if (RetVal.isUnset()) 8171 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8172 break; 8173 } 8174 8175 case DefaultedComparisonKind::ThreeWay: { 8176 // Per C++2a [class.spaceship]p3, as a fallback add: 8177 // return static_cast<R>(std::strong_ordering::equal); 8178 QualType StrongOrdering = S.CheckComparisonCategoryType( 8179 ComparisonCategoryType::StrongOrdering, Loc, 8180 Sema::ComparisonCategoryUsage::DefaultedOperator); 8181 if (StrongOrdering.isNull()) 8182 return StmtError(); 8183 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8184 .getValueInfo(ComparisonCategoryResult::Equal) 8185 ->VD; 8186 RetVal = getDecl(EqualVD); 8187 if (RetVal.isInvalid()) 8188 return StmtError(); 8189 RetVal = buildStaticCastToR(RetVal.get()); 8190 break; 8191 } 8192 8193 case DefaultedComparisonKind::NotEqual: 8194 case DefaultedComparisonKind::Relational: 8195 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8196 break; 8197 } 8198 8199 // Build the final return statement. 8200 if (RetVal.isInvalid()) 8201 return StmtError(); 8202 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8203 if (ReturnStmt.isInvalid()) 8204 return StmtError(); 8205 Stmts.Stmts.push_back(ReturnStmt.get()); 8206 8207 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8208 } 8209 8210 private: 8211 ExprResult getDecl(ValueDecl *VD) { 8212 return S.BuildDeclarationNameExpr( 8213 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8214 } 8215 8216 ExprResult getParam(unsigned I) { 8217 ParmVarDecl *PD = FD->getParamDecl(I); 8218 return getDecl(PD); 8219 } 8220 8221 ExprPair getCompleteObject() { 8222 unsigned Param = 0; 8223 ExprResult LHS; 8224 if (isa<CXXMethodDecl>(FD)) { 8225 // LHS is '*this'. 8226 LHS = S.ActOnCXXThis(Loc); 8227 if (!LHS.isInvalid()) 8228 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8229 } else { 8230 LHS = getParam(Param++); 8231 } 8232 ExprResult RHS = getParam(Param++); 8233 assert(Param == FD->getNumParams()); 8234 return {LHS, RHS}; 8235 } 8236 8237 ExprPair getBase(CXXBaseSpecifier *Base) { 8238 ExprPair Obj = getCompleteObject(); 8239 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8240 return {ExprError(), ExprError()}; 8241 CXXCastPath Path = {Base}; 8242 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8243 CK_DerivedToBase, VK_LValue, &Path), 8244 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8245 CK_DerivedToBase, VK_LValue, &Path)}; 8246 } 8247 8248 ExprPair getField(FieldDecl *Field) { 8249 ExprPair Obj = getCompleteObject(); 8250 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8251 return {ExprError(), ExprError()}; 8252 8253 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8254 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8255 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8256 CXXScopeSpec(), Field, Found, NameInfo), 8257 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8258 CXXScopeSpec(), Field, Found, NameInfo)}; 8259 } 8260 8261 // FIXME: When expanding a subobject, register a note in the code synthesis 8262 // stack to say which subobject we're comparing. 8263 8264 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8265 if (Cond.isInvalid()) 8266 return StmtError(); 8267 8268 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8269 if (NotCond.isInvalid()) 8270 return StmtError(); 8271 8272 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8273 assert(!False.isInvalid() && "should never fail"); 8274 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8275 if (ReturnFalse.isInvalid()) 8276 return StmtError(); 8277 8278 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8279 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8280 Sema::ConditionKind::Boolean), 8281 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8282 } 8283 8284 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8285 ExprPair Subobj) { 8286 QualType SizeType = S.Context.getSizeType(); 8287 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8288 8289 // Build 'size_t i$n = 0'. 8290 IdentifierInfo *IterationVarName = nullptr; 8291 { 8292 SmallString<8> Str; 8293 llvm::raw_svector_ostream OS(Str); 8294 OS << "i" << ArrayDepth; 8295 IterationVarName = &S.Context.Idents.get(OS.str()); 8296 } 8297 VarDecl *IterationVar = VarDecl::Create( 8298 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8299 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8300 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8301 IterationVar->setInit( 8302 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8303 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8304 8305 auto IterRef = [&] { 8306 ExprResult Ref = S.BuildDeclarationNameExpr( 8307 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8308 IterationVar); 8309 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8310 return Ref.get(); 8311 }; 8312 8313 // Build 'i$n != Size'. 8314 ExprResult Cond = S.CreateBuiltinBinOp( 8315 Loc, BO_NE, IterRef(), 8316 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8317 assert(!Cond.isInvalid() && "should never fail"); 8318 8319 // Build '++i$n'. 8320 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8321 assert(!Inc.isInvalid() && "should never fail"); 8322 8323 // Build 'a[i$n]' and 'b[i$n]'. 8324 auto Index = [&](ExprResult E) { 8325 if (E.isInvalid()) 8326 return ExprError(); 8327 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8328 }; 8329 Subobj.first = Index(Subobj.first); 8330 Subobj.second = Index(Subobj.second); 8331 8332 // Compare the array elements. 8333 ++ArrayDepth; 8334 StmtResult Substmt = visitSubobject(Type, Subobj); 8335 --ArrayDepth; 8336 8337 if (Substmt.isInvalid()) 8338 return StmtError(); 8339 8340 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8341 // For outer levels or for an 'operator<=>' we already have a suitable 8342 // statement that returns as necessary. 8343 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8344 assert(DCK == DefaultedComparisonKind::Equal && 8345 "should have non-expression statement"); 8346 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8347 if (Substmt.isInvalid()) 8348 return StmtError(); 8349 } 8350 8351 // Build 'for (...) ...' 8352 return S.ActOnForStmt(Loc, Loc, Init, 8353 S.ActOnCondition(nullptr, Loc, Cond.get(), 8354 Sema::ConditionKind::Boolean), 8355 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8356 Substmt.get()); 8357 } 8358 8359 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8360 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8361 return StmtError(); 8362 8363 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8364 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8365 ExprResult Op; 8366 if (Type->isOverloadableType()) 8367 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8368 Obj.second.get(), /*PerformADL=*/true, 8369 /*AllowRewrittenCandidates=*/true, FD); 8370 else 8371 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8372 if (Op.isInvalid()) 8373 return StmtError(); 8374 8375 switch (DCK) { 8376 case DefaultedComparisonKind::None: 8377 llvm_unreachable("not a defaulted comparison"); 8378 8379 case DefaultedComparisonKind::Equal: 8380 // Per C++2a [class.eq]p2, each comparison is individually contextually 8381 // converted to bool. 8382 Op = S.PerformContextuallyConvertToBool(Op.get()); 8383 if (Op.isInvalid()) 8384 return StmtError(); 8385 return Op.get(); 8386 8387 case DefaultedComparisonKind::ThreeWay: { 8388 // Per C++2a [class.spaceship]p3, form: 8389 // if (R cmp = static_cast<R>(op); cmp != 0) 8390 // return cmp; 8391 QualType R = FD->getReturnType(); 8392 Op = buildStaticCastToR(Op.get()); 8393 if (Op.isInvalid()) 8394 return StmtError(); 8395 8396 // R cmp = ...; 8397 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8398 VarDecl *VD = 8399 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8400 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8401 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8402 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8403 8404 // cmp != 0 8405 ExprResult VDRef = getDecl(VD); 8406 if (VDRef.isInvalid()) 8407 return StmtError(); 8408 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8409 Expr *Zero = 8410 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8411 ExprResult Comp; 8412 if (VDRef.get()->getType()->isOverloadableType()) 8413 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8414 true, FD); 8415 else 8416 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8417 if (Comp.isInvalid()) 8418 return StmtError(); 8419 Sema::ConditionResult Cond = S.ActOnCondition( 8420 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8421 if (Cond.isInvalid()) 8422 return StmtError(); 8423 8424 // return cmp; 8425 VDRef = getDecl(VD); 8426 if (VDRef.isInvalid()) 8427 return StmtError(); 8428 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8429 if (ReturnStmt.isInvalid()) 8430 return StmtError(); 8431 8432 // if (...) 8433 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8434 Loc, ReturnStmt.get(), 8435 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8436 } 8437 8438 case DefaultedComparisonKind::NotEqual: 8439 case DefaultedComparisonKind::Relational: 8440 // C++2a [class.compare.secondary]p2: 8441 // Otherwise, the operator function yields x @ y. 8442 return Op.get(); 8443 } 8444 llvm_unreachable(""); 8445 } 8446 8447 /// Build "static_cast<R>(E)". 8448 ExprResult buildStaticCastToR(Expr *E) { 8449 QualType R = FD->getReturnType(); 8450 assert(!R->isUndeducedType() && "type should have been deduced already"); 8451 8452 // Don't bother forming a no-op cast in the common case. 8453 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8454 return E; 8455 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8456 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8457 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8458 } 8459 }; 8460 } 8461 8462 /// Perform the unqualified lookups that might be needed to form a defaulted 8463 /// comparison function for the given operator. 8464 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8465 UnresolvedSetImpl &Operators, 8466 OverloadedOperatorKind Op) { 8467 auto Lookup = [&](OverloadedOperatorKind OO) { 8468 Self.LookupOverloadedOperatorName(OO, S, Operators); 8469 }; 8470 8471 // Every defaulted operator looks up itself. 8472 Lookup(Op); 8473 // ... and the rewritten form of itself, if any. 8474 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8475 Lookup(ExtraOp); 8476 8477 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8478 // synthesize a three-way comparison from '<' and '=='. In a dependent 8479 // context, we also need to look up '==' in case we implicitly declare a 8480 // defaulted 'operator=='. 8481 if (Op == OO_Spaceship) { 8482 Lookup(OO_ExclaimEqual); 8483 Lookup(OO_Less); 8484 Lookup(OO_EqualEqual); 8485 } 8486 } 8487 8488 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8489 DefaultedComparisonKind DCK) { 8490 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8491 8492 // Perform any unqualified lookups we're going to need to default this 8493 // function. 8494 if (S) { 8495 UnresolvedSet<32> Operators; 8496 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8497 FD->getOverloadedOperator()); 8498 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8499 Context, Operators.pairs())); 8500 } 8501 8502 // C++2a [class.compare.default]p1: 8503 // A defaulted comparison operator function for some class C shall be a 8504 // non-template function declared in the member-specification of C that is 8505 // -- a non-static const member of C having one parameter of type 8506 // const C&, or 8507 // -- a friend of C having two parameters of type const C& or two 8508 // parameters of type C. 8509 8510 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8511 bool IsMethod = isa<CXXMethodDecl>(FD); 8512 if (IsMethod) { 8513 auto *MD = cast<CXXMethodDecl>(FD); 8514 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8515 8516 // If we're out-of-class, this is the class we're comparing. 8517 if (!RD) 8518 RD = MD->getParent(); 8519 8520 if (!MD->isConst()) { 8521 SourceLocation InsertLoc; 8522 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8523 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8524 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8525 // corresponding defaulted 'operator<=>' already. 8526 if (!MD->isImplicit()) { 8527 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8528 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8529 } 8530 8531 // Add the 'const' to the type to recover. 8532 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8533 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8534 EPI.TypeQuals.addConst(); 8535 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8536 FPT->getParamTypes(), EPI)); 8537 } 8538 } 8539 8540 if (FD->getNumParams() != (IsMethod ? 1 : 2)) { 8541 // Let's not worry about using a variadic template pack here -- who would do 8542 // such a thing? 8543 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args) 8544 << int(IsMethod) << int(DCK); 8545 return true; 8546 } 8547 8548 const ParmVarDecl *KnownParm = nullptr; 8549 for (const ParmVarDecl *Param : FD->parameters()) { 8550 QualType ParmTy = Param->getType(); 8551 if (ParmTy->isDependentType()) 8552 continue; 8553 if (!KnownParm) { 8554 auto CTy = ParmTy; 8555 // Is it `T const &`? 8556 bool Ok = !IsMethod; 8557 QualType ExpectedTy; 8558 if (RD) 8559 ExpectedTy = Context.getRecordType(RD); 8560 if (auto *Ref = CTy->getAs<ReferenceType>()) { 8561 CTy = Ref->getPointeeType(); 8562 if (RD) 8563 ExpectedTy.addConst(); 8564 Ok = true; 8565 } 8566 8567 // Is T a class? 8568 if (!Ok) { 8569 } else if (RD) { 8570 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy)) 8571 Ok = false; 8572 } else if (auto *CRD = CTy->getAsRecordDecl()) { 8573 RD = cast<CXXRecordDecl>(CRD); 8574 } else { 8575 Ok = false; 8576 } 8577 8578 if (Ok) { 8579 KnownParm = Param; 8580 } else { 8581 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8582 // corresponding defaulted 'operator<=>' already. 8583 if (!FD->isImplicit()) { 8584 if (RD) { 8585 QualType PlainTy = Context.getRecordType(RD); 8586 QualType RefTy = 8587 Context.getLValueReferenceType(PlainTy.withConst()); 8588 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8589 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy 8590 << Param->getSourceRange(); 8591 } else { 8592 assert(!IsMethod && "should know expected type for method"); 8593 Diag(FD->getLocation(), 8594 diag::err_defaulted_comparison_param_unknown) 8595 << int(DCK) << ParmTy << Param->getSourceRange(); 8596 } 8597 } 8598 return true; 8599 } 8600 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) { 8601 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8602 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange() 8603 << ParmTy << Param->getSourceRange(); 8604 return true; 8605 } 8606 } 8607 8608 assert(RD && "must have determined class"); 8609 if (IsMethod) { 8610 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 8611 // In-class, must be a friend decl. 8612 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8613 } else { 8614 // Out of class, require the defaulted comparison to be a friend (of a 8615 // complete type). 8616 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD), 8617 diag::err_defaulted_comparison_not_friend, int(DCK), 8618 int(1))) 8619 return true; 8620 8621 if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) { 8622 return FD->getCanonicalDecl() == 8623 F->getFriendDecl()->getCanonicalDecl(); 8624 }) == RD->friends().end()) { 8625 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend) 8626 << int(DCK) << int(0) << RD; 8627 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at); 8628 return true; 8629 } 8630 } 8631 8632 // C++2a [class.eq]p1, [class.rel]p1: 8633 // A [defaulted comparison other than <=>] shall have a declared return 8634 // type bool. 8635 if (DCK != DefaultedComparisonKind::ThreeWay && 8636 !FD->getDeclaredReturnType()->isDependentType() && 8637 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8638 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8639 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8640 << FD->getReturnTypeSourceRange(); 8641 return true; 8642 } 8643 // C++2a [class.spaceship]p2 [P2002R0]: 8644 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8645 // R shall not contain a placeholder type. 8646 if (DCK == DefaultedComparisonKind::ThreeWay && 8647 FD->getDeclaredReturnType()->getContainedDeducedType() && 8648 !Context.hasSameType(FD->getDeclaredReturnType(), 8649 Context.getAutoDeductType())) { 8650 Diag(FD->getLocation(), 8651 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8652 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8653 << FD->getReturnTypeSourceRange(); 8654 return true; 8655 } 8656 8657 // For a defaulted function in a dependent class, defer all remaining checks 8658 // until instantiation. 8659 if (RD->isDependentType()) 8660 return false; 8661 8662 // Determine whether the function should be defined as deleted. 8663 DefaultedComparisonInfo Info = 8664 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8665 8666 bool First = FD == FD->getCanonicalDecl(); 8667 8668 // If we want to delete the function, then do so; there's nothing else to 8669 // check in that case. 8670 if (Info.Deleted) { 8671 if (!First) { 8672 // C++11 [dcl.fct.def.default]p4: 8673 // [For a] user-provided explicitly-defaulted function [...] if such a 8674 // function is implicitly defined as deleted, the program is ill-formed. 8675 // 8676 // This is really just a consequence of the general rule that you can 8677 // only delete a function on its first declaration. 8678 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8679 << FD->isImplicit() << (int)DCK; 8680 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8681 DefaultedComparisonAnalyzer::ExplainDeleted) 8682 .visit(); 8683 return true; 8684 } 8685 8686 SetDeclDeleted(FD, FD->getLocation()); 8687 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8688 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8689 << (int)DCK; 8690 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8691 DefaultedComparisonAnalyzer::ExplainDeleted) 8692 .visit(); 8693 } 8694 return false; 8695 } 8696 8697 // C++2a [class.spaceship]p2: 8698 // The return type is deduced as the common comparison type of R0, R1, ... 8699 if (DCK == DefaultedComparisonKind::ThreeWay && 8700 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8701 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8702 if (RetLoc.isInvalid()) 8703 RetLoc = FD->getBeginLoc(); 8704 // FIXME: Should we really care whether we have the complete type and the 8705 // 'enumerator' constants here? A forward declaration seems sufficient. 8706 QualType Cat = CheckComparisonCategoryType( 8707 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8708 if (Cat.isNull()) 8709 return true; 8710 Context.adjustDeducedFunctionResultType( 8711 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8712 } 8713 8714 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8715 // An explicitly-defaulted function that is not defined as deleted may be 8716 // declared constexpr or consteval only if it is constexpr-compatible. 8717 // C++2a [class.compare.default]p3 [P2002R0]: 8718 // A defaulted comparison function is constexpr-compatible if it satisfies 8719 // the requirements for a constexpr function [...] 8720 // The only relevant requirements are that the parameter and return types are 8721 // literal types. The remaining conditions are checked by the analyzer. 8722 if (FD->isConstexpr()) { 8723 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8724 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8725 !Info.Constexpr) { 8726 Diag(FD->getBeginLoc(), 8727 diag::err_incorrect_defaulted_comparison_constexpr) 8728 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8729 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8730 DefaultedComparisonAnalyzer::ExplainConstexpr) 8731 .visit(); 8732 } 8733 } 8734 8735 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8736 // If a constexpr-compatible function is explicitly defaulted on its first 8737 // declaration, it is implicitly considered to be constexpr. 8738 // FIXME: Only applying this to the first declaration seems problematic, as 8739 // simple reorderings can affect the meaning of the program. 8740 if (First && !FD->isConstexpr() && Info.Constexpr) 8741 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8742 8743 // C++2a [except.spec]p3: 8744 // If a declaration of a function does not have a noexcept-specifier 8745 // [and] is defaulted on its first declaration, [...] the exception 8746 // specification is as specified below 8747 if (FD->getExceptionSpecType() == EST_None) { 8748 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8749 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8750 EPI.ExceptionSpec.Type = EST_Unevaluated; 8751 EPI.ExceptionSpec.SourceDecl = FD; 8752 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8753 FPT->getParamTypes(), EPI)); 8754 } 8755 8756 return false; 8757 } 8758 8759 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8760 FunctionDecl *Spaceship) { 8761 Sema::CodeSynthesisContext Ctx; 8762 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8763 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8764 Ctx.Entity = Spaceship; 8765 pushCodeSynthesisContext(Ctx); 8766 8767 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8768 EqualEqual->setImplicit(); 8769 8770 popCodeSynthesisContext(); 8771 } 8772 8773 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8774 DefaultedComparisonKind DCK) { 8775 assert(FD->isDefaulted() && !FD->isDeleted() && 8776 !FD->doesThisDeclarationHaveABody()); 8777 if (FD->willHaveBody() || FD->isInvalidDecl()) 8778 return; 8779 8780 SynthesizedFunctionScope Scope(*this, FD); 8781 8782 // Add a context note for diagnostics produced after this point. 8783 Scope.addContextNote(UseLoc); 8784 8785 { 8786 // Build and set up the function body. 8787 // The first parameter has type maybe-ref-to maybe-const T, use that to get 8788 // the type of the class being compared. 8789 auto PT = FD->getParamDecl(0)->getType(); 8790 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl(); 8791 SourceLocation BodyLoc = 8792 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8793 StmtResult Body = 8794 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8795 if (Body.isInvalid()) { 8796 FD->setInvalidDecl(); 8797 return; 8798 } 8799 FD->setBody(Body.get()); 8800 FD->markUsed(Context); 8801 } 8802 8803 // The exception specification is needed because we are defining the 8804 // function. Note that this will reuse the body we just built. 8805 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8806 8807 if (ASTMutationListener *L = getASTMutationListener()) 8808 L->CompletedImplicitDefinition(FD); 8809 } 8810 8811 static Sema::ImplicitExceptionSpecification 8812 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8813 FunctionDecl *FD, 8814 Sema::DefaultedComparisonKind DCK) { 8815 ComputingExceptionSpec CES(S, FD, Loc); 8816 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8817 8818 if (FD->isInvalidDecl()) 8819 return ExceptSpec; 8820 8821 // The common case is that we just defined the comparison function. In that 8822 // case, just look at whether the body can throw. 8823 if (FD->hasBody()) { 8824 ExceptSpec.CalledStmt(FD->getBody()); 8825 } else { 8826 // Otherwise, build a body so we can check it. This should ideally only 8827 // happen when we're not actually marking the function referenced. (This is 8828 // only really important for efficiency: we don't want to build and throw 8829 // away bodies for comparison functions more than we strictly need to.) 8830 8831 // Pretend to synthesize the function body in an unevaluated context. 8832 // Note that we can't actually just go ahead and define the function here: 8833 // we are not permitted to mark its callees as referenced. 8834 Sema::SynthesizedFunctionScope Scope(S, FD); 8835 EnterExpressionEvaluationContext Context( 8836 S, Sema::ExpressionEvaluationContext::Unevaluated); 8837 8838 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8839 SourceLocation BodyLoc = 8840 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8841 StmtResult Body = 8842 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8843 if (!Body.isInvalid()) 8844 ExceptSpec.CalledStmt(Body.get()); 8845 8846 // FIXME: Can we hold onto this body and just transform it to potentially 8847 // evaluated when we're asked to define the function rather than rebuilding 8848 // it? Either that, or we should only build the bits of the body that we 8849 // need (the expressions, not the statements). 8850 } 8851 8852 return ExceptSpec; 8853 } 8854 8855 void Sema::CheckDelayedMemberExceptionSpecs() { 8856 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8857 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8858 8859 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8860 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8861 8862 // Perform any deferred checking of exception specifications for virtual 8863 // destructors. 8864 for (auto &Check : Overriding) 8865 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8866 8867 // Perform any deferred checking of exception specifications for befriended 8868 // special members. 8869 for (auto &Check : Equivalent) 8870 CheckEquivalentExceptionSpec(Check.second, Check.first); 8871 } 8872 8873 namespace { 8874 /// CRTP base class for visiting operations performed by a special member 8875 /// function (or inherited constructor). 8876 template<typename Derived> 8877 struct SpecialMemberVisitor { 8878 Sema &S; 8879 CXXMethodDecl *MD; 8880 Sema::CXXSpecialMember CSM; 8881 Sema::InheritedConstructorInfo *ICI; 8882 8883 // Properties of the special member, computed for convenience. 8884 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8885 8886 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8887 Sema::InheritedConstructorInfo *ICI) 8888 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8889 switch (CSM) { 8890 case Sema::CXXDefaultConstructor: 8891 case Sema::CXXCopyConstructor: 8892 case Sema::CXXMoveConstructor: 8893 IsConstructor = true; 8894 break; 8895 case Sema::CXXCopyAssignment: 8896 case Sema::CXXMoveAssignment: 8897 IsAssignment = true; 8898 break; 8899 case Sema::CXXDestructor: 8900 break; 8901 case Sema::CXXInvalid: 8902 llvm_unreachable("invalid special member kind"); 8903 } 8904 8905 if (MD->getNumParams()) { 8906 if (const ReferenceType *RT = 8907 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8908 ConstArg = RT->getPointeeType().isConstQualified(); 8909 } 8910 } 8911 8912 Derived &getDerived() { return static_cast<Derived&>(*this); } 8913 8914 /// Is this a "move" special member? 8915 bool isMove() const { 8916 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8917 } 8918 8919 /// Look up the corresponding special member in the given class. 8920 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8921 unsigned Quals, bool IsMutable) { 8922 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8923 ConstArg && !IsMutable); 8924 } 8925 8926 /// Look up the constructor for the specified base class to see if it's 8927 /// overridden due to this being an inherited constructor. 8928 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8929 if (!ICI) 8930 return {}; 8931 assert(CSM == Sema::CXXDefaultConstructor); 8932 auto *BaseCtor = 8933 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8934 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8935 return MD; 8936 return {}; 8937 } 8938 8939 /// A base or member subobject. 8940 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8941 8942 /// Get the location to use for a subobject in diagnostics. 8943 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8944 // FIXME: For an indirect virtual base, the direct base leading to 8945 // the indirect virtual base would be a more useful choice. 8946 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8947 return B->getBaseTypeLoc(); 8948 else 8949 return Subobj.get<FieldDecl*>()->getLocation(); 8950 } 8951 8952 enum BasesToVisit { 8953 /// Visit all non-virtual (direct) bases. 8954 VisitNonVirtualBases, 8955 /// Visit all direct bases, virtual or not. 8956 VisitDirectBases, 8957 /// Visit all non-virtual bases, and all virtual bases if the class 8958 /// is not abstract. 8959 VisitPotentiallyConstructedBases, 8960 /// Visit all direct or virtual bases. 8961 VisitAllBases 8962 }; 8963 8964 // Visit the bases and members of the class. 8965 bool visit(BasesToVisit Bases) { 8966 CXXRecordDecl *RD = MD->getParent(); 8967 8968 if (Bases == VisitPotentiallyConstructedBases) 8969 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8970 8971 for (auto &B : RD->bases()) 8972 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8973 getDerived().visitBase(&B)) 8974 return true; 8975 8976 if (Bases == VisitAllBases) 8977 for (auto &B : RD->vbases()) 8978 if (getDerived().visitBase(&B)) 8979 return true; 8980 8981 for (auto *F : RD->fields()) 8982 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8983 getDerived().visitField(F)) 8984 return true; 8985 8986 return false; 8987 } 8988 }; 8989 } 8990 8991 namespace { 8992 struct SpecialMemberDeletionInfo 8993 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8994 bool Diagnose; 8995 8996 SourceLocation Loc; 8997 8998 bool AllFieldsAreConst; 8999 9000 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 9001 Sema::CXXSpecialMember CSM, 9002 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 9003 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 9004 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 9005 9006 bool inUnion() const { return MD->getParent()->isUnion(); } 9007 9008 Sema::CXXSpecialMember getEffectiveCSM() { 9009 return ICI ? Sema::CXXInvalid : CSM; 9010 } 9011 9012 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 9013 9014 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 9015 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 9016 9017 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 9018 bool shouldDeleteForField(FieldDecl *FD); 9019 bool shouldDeleteForAllConstMembers(); 9020 9021 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 9022 unsigned Quals); 9023 bool shouldDeleteForSubobjectCall(Subobject Subobj, 9024 Sema::SpecialMemberOverloadResult SMOR, 9025 bool IsDtorCallInCtor); 9026 9027 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 9028 }; 9029 } 9030 9031 /// Is the given special member inaccessible when used on the given 9032 /// sub-object. 9033 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 9034 CXXMethodDecl *target) { 9035 /// If we're operating on a base class, the object type is the 9036 /// type of this special member. 9037 QualType objectTy; 9038 AccessSpecifier access = target->getAccess(); 9039 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 9040 objectTy = S.Context.getTypeDeclType(MD->getParent()); 9041 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 9042 9043 // If we're operating on a field, the object type is the type of the field. 9044 } else { 9045 objectTy = S.Context.getTypeDeclType(target->getParent()); 9046 } 9047 9048 return S.isMemberAccessibleForDeletion( 9049 target->getParent(), DeclAccessPair::make(target, access), objectTy); 9050 } 9051 9052 /// Check whether we should delete a special member due to the implicit 9053 /// definition containing a call to a special member of a subobject. 9054 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 9055 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 9056 bool IsDtorCallInCtor) { 9057 CXXMethodDecl *Decl = SMOR.getMethod(); 9058 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9059 9060 int DiagKind = -1; 9061 9062 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 9063 DiagKind = !Decl ? 0 : 1; 9064 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9065 DiagKind = 2; 9066 else if (!isAccessible(Subobj, Decl)) 9067 DiagKind = 3; 9068 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 9069 !Decl->isTrivial()) { 9070 // A member of a union must have a trivial corresponding special member. 9071 // As a weird special case, a destructor call from a union's constructor 9072 // must be accessible and non-deleted, but need not be trivial. Such a 9073 // destructor is never actually called, but is semantically checked as 9074 // if it were. 9075 DiagKind = 4; 9076 } 9077 9078 if (DiagKind == -1) 9079 return false; 9080 9081 if (Diagnose) { 9082 if (Field) { 9083 S.Diag(Field->getLocation(), 9084 diag::note_deleted_special_member_class_subobject) 9085 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 9086 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 9087 } else { 9088 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 9089 S.Diag(Base->getBeginLoc(), 9090 diag::note_deleted_special_member_class_subobject) 9091 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9092 << Base->getType() << DiagKind << IsDtorCallInCtor 9093 << /*IsObjCPtr*/false; 9094 } 9095 9096 if (DiagKind == 1) 9097 S.NoteDeletedFunction(Decl); 9098 // FIXME: Explain inaccessibility if DiagKind == 3. 9099 } 9100 9101 return true; 9102 } 9103 9104 /// Check whether we should delete a special member function due to having a 9105 /// direct or virtual base class or non-static data member of class type M. 9106 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 9107 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 9108 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9109 bool IsMutable = Field && Field->isMutable(); 9110 9111 // C++11 [class.ctor]p5: 9112 // -- any direct or virtual base class, or non-static data member with no 9113 // brace-or-equal-initializer, has class type M (or array thereof) and 9114 // either M has no default constructor or overload resolution as applied 9115 // to M's default constructor results in an ambiguity or in a function 9116 // that is deleted or inaccessible 9117 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9118 // -- a direct or virtual base class B that cannot be copied/moved because 9119 // overload resolution, as applied to B's corresponding special member, 9120 // results in an ambiguity or a function that is deleted or inaccessible 9121 // from the defaulted special member 9122 // C++11 [class.dtor]p5: 9123 // -- any direct or virtual base class [...] has a type with a destructor 9124 // that is deleted or inaccessible 9125 if (!(CSM == Sema::CXXDefaultConstructor && 9126 Field && Field->hasInClassInitializer()) && 9127 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9128 false)) 9129 return true; 9130 9131 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9132 // -- any direct or virtual base class or non-static data member has a 9133 // type with a destructor that is deleted or inaccessible 9134 if (IsConstructor) { 9135 Sema::SpecialMemberOverloadResult SMOR = 9136 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9137 false, false, false, false, false); 9138 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9139 return true; 9140 } 9141 9142 return false; 9143 } 9144 9145 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9146 FieldDecl *FD, QualType FieldType) { 9147 // The defaulted special functions are defined as deleted if this is a variant 9148 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9149 // type under ARC. 9150 if (!FieldType.hasNonTrivialObjCLifetime()) 9151 return false; 9152 9153 // Don't make the defaulted default constructor defined as deleted if the 9154 // member has an in-class initializer. 9155 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9156 return false; 9157 9158 if (Diagnose) { 9159 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9160 S.Diag(FD->getLocation(), 9161 diag::note_deleted_special_member_class_subobject) 9162 << getEffectiveCSM() << ParentClass << /*IsField*/true 9163 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9164 } 9165 9166 return true; 9167 } 9168 9169 /// Check whether we should delete a special member function due to the class 9170 /// having a particular direct or virtual base class. 9171 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9172 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9173 // If program is correct, BaseClass cannot be null, but if it is, the error 9174 // must be reported elsewhere. 9175 if (!BaseClass) 9176 return false; 9177 // If we have an inheriting constructor, check whether we're calling an 9178 // inherited constructor instead of a default constructor. 9179 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9180 if (auto *BaseCtor = SMOR.getMethod()) { 9181 // Note that we do not check access along this path; other than that, 9182 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9183 // FIXME: Check that the base has a usable destructor! Sink this into 9184 // shouldDeleteForClassSubobject. 9185 if (BaseCtor->isDeleted() && Diagnose) { 9186 S.Diag(Base->getBeginLoc(), 9187 diag::note_deleted_special_member_class_subobject) 9188 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9189 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9190 << /*IsObjCPtr*/false; 9191 S.NoteDeletedFunction(BaseCtor); 9192 } 9193 return BaseCtor->isDeleted(); 9194 } 9195 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9196 } 9197 9198 /// Check whether we should delete a special member function due to the class 9199 /// having a particular non-static data member. 9200 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9201 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9202 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9203 9204 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9205 return true; 9206 9207 if (CSM == Sema::CXXDefaultConstructor) { 9208 // For a default constructor, all references must be initialized in-class 9209 // and, if a union, it must have a non-const member. 9210 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9211 if (Diagnose) 9212 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9213 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9214 return true; 9215 } 9216 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static 9217 // data member of const-qualified type (or array thereof) with no 9218 // brace-or-equal-initializer is not const-default-constructible. 9219 if (!inUnion() && FieldType.isConstQualified() && 9220 !FD->hasInClassInitializer() && 9221 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) { 9222 if (Diagnose) 9223 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9224 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9225 return true; 9226 } 9227 9228 if (inUnion() && !FieldType.isConstQualified()) 9229 AllFieldsAreConst = false; 9230 } else if (CSM == Sema::CXXCopyConstructor) { 9231 // For a copy constructor, data members must not be of rvalue reference 9232 // type. 9233 if (FieldType->isRValueReferenceType()) { 9234 if (Diagnose) 9235 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9236 << MD->getParent() << FD << FieldType; 9237 return true; 9238 } 9239 } else if (IsAssignment) { 9240 // For an assignment operator, data members must not be of reference type. 9241 if (FieldType->isReferenceType()) { 9242 if (Diagnose) 9243 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9244 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9245 return true; 9246 } 9247 if (!FieldRecord && FieldType.isConstQualified()) { 9248 // C++11 [class.copy]p23: 9249 // -- a non-static data member of const non-class type (or array thereof) 9250 if (Diagnose) 9251 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9252 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9253 return true; 9254 } 9255 } 9256 9257 if (FieldRecord) { 9258 // Some additional restrictions exist on the variant members. 9259 if (!inUnion() && FieldRecord->isUnion() && 9260 FieldRecord->isAnonymousStructOrUnion()) { 9261 bool AllVariantFieldsAreConst = true; 9262 9263 // FIXME: Handle anonymous unions declared within anonymous unions. 9264 for (auto *UI : FieldRecord->fields()) { 9265 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9266 9267 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9268 return true; 9269 9270 if (!UnionFieldType.isConstQualified()) 9271 AllVariantFieldsAreConst = false; 9272 9273 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9274 if (UnionFieldRecord && 9275 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9276 UnionFieldType.getCVRQualifiers())) 9277 return true; 9278 } 9279 9280 // At least one member in each anonymous union must be non-const 9281 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9282 !FieldRecord->field_empty()) { 9283 if (Diagnose) 9284 S.Diag(FieldRecord->getLocation(), 9285 diag::note_deleted_default_ctor_all_const) 9286 << !!ICI << MD->getParent() << /*anonymous union*/1; 9287 return true; 9288 } 9289 9290 // Don't check the implicit member of the anonymous union type. 9291 // This is technically non-conformant but supported, and we have a 9292 // diagnostic for this elsewhere. 9293 return false; 9294 } 9295 9296 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9297 FieldType.getCVRQualifiers())) 9298 return true; 9299 } 9300 9301 return false; 9302 } 9303 9304 /// C++11 [class.ctor] p5: 9305 /// A defaulted default constructor for a class X is defined as deleted if 9306 /// X is a union and all of its variant members are of const-qualified type. 9307 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9308 // This is a silly definition, because it gives an empty union a deleted 9309 // default constructor. Don't do that. 9310 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9311 bool AnyFields = false; 9312 for (auto *F : MD->getParent()->fields()) 9313 if ((AnyFields = !F->isUnnamedBitfield())) 9314 break; 9315 if (!AnyFields) 9316 return false; 9317 if (Diagnose) 9318 S.Diag(MD->getParent()->getLocation(), 9319 diag::note_deleted_default_ctor_all_const) 9320 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9321 return true; 9322 } 9323 return false; 9324 } 9325 9326 /// Determine whether a defaulted special member function should be defined as 9327 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9328 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9329 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9330 InheritedConstructorInfo *ICI, 9331 bool Diagnose) { 9332 if (MD->isInvalidDecl()) 9333 return false; 9334 CXXRecordDecl *RD = MD->getParent(); 9335 assert(!RD->isDependentType() && "do deletion after instantiation"); 9336 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9337 return false; 9338 9339 // C++11 [expr.lambda.prim]p19: 9340 // The closure type associated with a lambda-expression has a 9341 // deleted (8.4.3) default constructor and a deleted copy 9342 // assignment operator. 9343 // C++2a adds back these operators if the lambda has no lambda-capture. 9344 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9345 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9346 if (Diagnose) 9347 Diag(RD->getLocation(), diag::note_lambda_decl); 9348 return true; 9349 } 9350 9351 // For an anonymous struct or union, the copy and assignment special members 9352 // will never be used, so skip the check. For an anonymous union declared at 9353 // namespace scope, the constructor and destructor are used. 9354 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9355 RD->isAnonymousStructOrUnion()) 9356 return false; 9357 9358 // C++11 [class.copy]p7, p18: 9359 // If the class definition declares a move constructor or move assignment 9360 // operator, an implicitly declared copy constructor or copy assignment 9361 // operator is defined as deleted. 9362 if (MD->isImplicit() && 9363 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9364 CXXMethodDecl *UserDeclaredMove = nullptr; 9365 9366 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9367 // deletion of the corresponding copy operation, not both copy operations. 9368 // MSVC 2015 has adopted the standards conforming behavior. 9369 bool DeletesOnlyMatchingCopy = 9370 getLangOpts().MSVCCompat && 9371 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9372 9373 if (RD->hasUserDeclaredMoveConstructor() && 9374 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9375 if (!Diagnose) return true; 9376 9377 // Find any user-declared move constructor. 9378 for (auto *I : RD->ctors()) { 9379 if (I->isMoveConstructor()) { 9380 UserDeclaredMove = I; 9381 break; 9382 } 9383 } 9384 assert(UserDeclaredMove); 9385 } else if (RD->hasUserDeclaredMoveAssignment() && 9386 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9387 if (!Diagnose) return true; 9388 9389 // Find any user-declared move assignment operator. 9390 for (auto *I : RD->methods()) { 9391 if (I->isMoveAssignmentOperator()) { 9392 UserDeclaredMove = I; 9393 break; 9394 } 9395 } 9396 assert(UserDeclaredMove); 9397 } 9398 9399 if (UserDeclaredMove) { 9400 Diag(UserDeclaredMove->getLocation(), 9401 diag::note_deleted_copy_user_declared_move) 9402 << (CSM == CXXCopyAssignment) << RD 9403 << UserDeclaredMove->isMoveAssignmentOperator(); 9404 return true; 9405 } 9406 } 9407 9408 // Do access control from the special member function 9409 ContextRAII MethodContext(*this, MD); 9410 9411 // C++11 [class.dtor]p5: 9412 // -- for a virtual destructor, lookup of the non-array deallocation function 9413 // results in an ambiguity or in a function that is deleted or inaccessible 9414 if (CSM == CXXDestructor && MD->isVirtual()) { 9415 FunctionDecl *OperatorDelete = nullptr; 9416 DeclarationName Name = 9417 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9418 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9419 OperatorDelete, /*Diagnose*/false)) { 9420 if (Diagnose) 9421 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9422 return true; 9423 } 9424 } 9425 9426 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9427 9428 // Per DR1611, do not consider virtual bases of constructors of abstract 9429 // classes, since we are not going to construct them. 9430 // Per DR1658, do not consider virtual bases of destructors of abstract 9431 // classes either. 9432 // Per DR2180, for assignment operators we only assign (and thus only 9433 // consider) direct bases. 9434 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9435 : SMI.VisitPotentiallyConstructedBases)) 9436 return true; 9437 9438 if (SMI.shouldDeleteForAllConstMembers()) 9439 return true; 9440 9441 if (getLangOpts().CUDA) { 9442 // We should delete the special member in CUDA mode if target inference 9443 // failed. 9444 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9445 // is treated as certain special member, which may not reflect what special 9446 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9447 // expects CSM to match MD, therefore recalculate CSM. 9448 assert(ICI || CSM == getSpecialMember(MD)); 9449 auto RealCSM = CSM; 9450 if (ICI) 9451 RealCSM = getSpecialMember(MD); 9452 9453 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9454 SMI.ConstArg, Diagnose); 9455 } 9456 9457 return false; 9458 } 9459 9460 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9461 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9462 assert(DFK && "not a defaultable function"); 9463 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9464 9465 if (DFK.isSpecialMember()) { 9466 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9467 nullptr, /*Diagnose=*/true); 9468 } else { 9469 DefaultedComparisonAnalyzer( 9470 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9471 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9472 .visit(); 9473 } 9474 } 9475 9476 /// Perform lookup for a special member of the specified kind, and determine 9477 /// whether it is trivial. If the triviality can be determined without the 9478 /// lookup, skip it. This is intended for use when determining whether a 9479 /// special member of a containing object is trivial, and thus does not ever 9480 /// perform overload resolution for default constructors. 9481 /// 9482 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9483 /// member that was most likely to be intended to be trivial, if any. 9484 /// 9485 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9486 /// determine whether the special member is trivial. 9487 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9488 Sema::CXXSpecialMember CSM, unsigned Quals, 9489 bool ConstRHS, 9490 Sema::TrivialABIHandling TAH, 9491 CXXMethodDecl **Selected) { 9492 if (Selected) 9493 *Selected = nullptr; 9494 9495 switch (CSM) { 9496 case Sema::CXXInvalid: 9497 llvm_unreachable("not a special member"); 9498 9499 case Sema::CXXDefaultConstructor: 9500 // C++11 [class.ctor]p5: 9501 // A default constructor is trivial if: 9502 // - all the [direct subobjects] have trivial default constructors 9503 // 9504 // Note, no overload resolution is performed in this case. 9505 if (RD->hasTrivialDefaultConstructor()) 9506 return true; 9507 9508 if (Selected) { 9509 // If there's a default constructor which could have been trivial, dig it 9510 // out. Otherwise, if there's any user-provided default constructor, point 9511 // to that as an example of why there's not a trivial one. 9512 CXXConstructorDecl *DefCtor = nullptr; 9513 if (RD->needsImplicitDefaultConstructor()) 9514 S.DeclareImplicitDefaultConstructor(RD); 9515 for (auto *CI : RD->ctors()) { 9516 if (!CI->isDefaultConstructor()) 9517 continue; 9518 DefCtor = CI; 9519 if (!DefCtor->isUserProvided()) 9520 break; 9521 } 9522 9523 *Selected = DefCtor; 9524 } 9525 9526 return false; 9527 9528 case Sema::CXXDestructor: 9529 // C++11 [class.dtor]p5: 9530 // A destructor is trivial if: 9531 // - all the direct [subobjects] have trivial destructors 9532 if (RD->hasTrivialDestructor() || 9533 (TAH == Sema::TAH_ConsiderTrivialABI && 9534 RD->hasTrivialDestructorForCall())) 9535 return true; 9536 9537 if (Selected) { 9538 if (RD->needsImplicitDestructor()) 9539 S.DeclareImplicitDestructor(RD); 9540 *Selected = RD->getDestructor(); 9541 } 9542 9543 return false; 9544 9545 case Sema::CXXCopyConstructor: 9546 // C++11 [class.copy]p12: 9547 // A copy constructor is trivial if: 9548 // - the constructor selected to copy each direct [subobject] is trivial 9549 if (RD->hasTrivialCopyConstructor() || 9550 (TAH == Sema::TAH_ConsiderTrivialABI && 9551 RD->hasTrivialCopyConstructorForCall())) { 9552 if (Quals == Qualifiers::Const) 9553 // We must either select the trivial copy constructor or reach an 9554 // ambiguity; no need to actually perform overload resolution. 9555 return true; 9556 } else if (!Selected) { 9557 return false; 9558 } 9559 // In C++98, we are not supposed to perform overload resolution here, but we 9560 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9561 // cases like B as having a non-trivial copy constructor: 9562 // struct A { template<typename T> A(T&); }; 9563 // struct B { mutable A a; }; 9564 goto NeedOverloadResolution; 9565 9566 case Sema::CXXCopyAssignment: 9567 // C++11 [class.copy]p25: 9568 // A copy assignment operator is trivial if: 9569 // - the assignment operator selected to copy each direct [subobject] is 9570 // trivial 9571 if (RD->hasTrivialCopyAssignment()) { 9572 if (Quals == Qualifiers::Const) 9573 return true; 9574 } else if (!Selected) { 9575 return false; 9576 } 9577 // In C++98, we are not supposed to perform overload resolution here, but we 9578 // treat that as a language defect. 9579 goto NeedOverloadResolution; 9580 9581 case Sema::CXXMoveConstructor: 9582 case Sema::CXXMoveAssignment: 9583 NeedOverloadResolution: 9584 Sema::SpecialMemberOverloadResult SMOR = 9585 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9586 9587 // The standard doesn't describe how to behave if the lookup is ambiguous. 9588 // We treat it as not making the member non-trivial, just like the standard 9589 // mandates for the default constructor. This should rarely matter, because 9590 // the member will also be deleted. 9591 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9592 return true; 9593 9594 if (!SMOR.getMethod()) { 9595 assert(SMOR.getKind() == 9596 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9597 return false; 9598 } 9599 9600 // We deliberately don't check if we found a deleted special member. We're 9601 // not supposed to! 9602 if (Selected) 9603 *Selected = SMOR.getMethod(); 9604 9605 if (TAH == Sema::TAH_ConsiderTrivialABI && 9606 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9607 return SMOR.getMethod()->isTrivialForCall(); 9608 return SMOR.getMethod()->isTrivial(); 9609 } 9610 9611 llvm_unreachable("unknown special method kind"); 9612 } 9613 9614 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9615 for (auto *CI : RD->ctors()) 9616 if (!CI->isImplicit()) 9617 return CI; 9618 9619 // Look for constructor templates. 9620 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9621 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9622 if (CXXConstructorDecl *CD = 9623 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9624 return CD; 9625 } 9626 9627 return nullptr; 9628 } 9629 9630 /// The kind of subobject we are checking for triviality. The values of this 9631 /// enumeration are used in diagnostics. 9632 enum TrivialSubobjectKind { 9633 /// The subobject is a base class. 9634 TSK_BaseClass, 9635 /// The subobject is a non-static data member. 9636 TSK_Field, 9637 /// The object is actually the complete object. 9638 TSK_CompleteObject 9639 }; 9640 9641 /// Check whether the special member selected for a given type would be trivial. 9642 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9643 QualType SubType, bool ConstRHS, 9644 Sema::CXXSpecialMember CSM, 9645 TrivialSubobjectKind Kind, 9646 Sema::TrivialABIHandling TAH, bool Diagnose) { 9647 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9648 if (!SubRD) 9649 return true; 9650 9651 CXXMethodDecl *Selected; 9652 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9653 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9654 return true; 9655 9656 if (Diagnose) { 9657 if (ConstRHS) 9658 SubType.addConst(); 9659 9660 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9661 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9662 << Kind << SubType.getUnqualifiedType(); 9663 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9664 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9665 } else if (!Selected) 9666 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9667 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9668 else if (Selected->isUserProvided()) { 9669 if (Kind == TSK_CompleteObject) 9670 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9671 << Kind << SubType.getUnqualifiedType() << CSM; 9672 else { 9673 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9674 << Kind << SubType.getUnqualifiedType() << CSM; 9675 S.Diag(Selected->getLocation(), diag::note_declared_at); 9676 } 9677 } else { 9678 if (Kind != TSK_CompleteObject) 9679 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9680 << Kind << SubType.getUnqualifiedType() << CSM; 9681 9682 // Explain why the defaulted or deleted special member isn't trivial. 9683 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9684 Diagnose); 9685 } 9686 } 9687 9688 return false; 9689 } 9690 9691 /// Check whether the members of a class type allow a special member to be 9692 /// trivial. 9693 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9694 Sema::CXXSpecialMember CSM, 9695 bool ConstArg, 9696 Sema::TrivialABIHandling TAH, 9697 bool Diagnose) { 9698 for (const auto *FI : RD->fields()) { 9699 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9700 continue; 9701 9702 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9703 9704 // Pretend anonymous struct or union members are members of this class. 9705 if (FI->isAnonymousStructOrUnion()) { 9706 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9707 CSM, ConstArg, TAH, Diagnose)) 9708 return false; 9709 continue; 9710 } 9711 9712 // C++11 [class.ctor]p5: 9713 // A default constructor is trivial if [...] 9714 // -- no non-static data member of its class has a 9715 // brace-or-equal-initializer 9716 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9717 if (Diagnose) 9718 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9719 << FI; 9720 return false; 9721 } 9722 9723 // Objective C ARC 4.3.5: 9724 // [...] nontrivally ownership-qualified types are [...] not trivially 9725 // default constructible, copy constructible, move constructible, copy 9726 // assignable, move assignable, or destructible [...] 9727 if (FieldType.hasNonTrivialObjCLifetime()) { 9728 if (Diagnose) 9729 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9730 << RD << FieldType.getObjCLifetime(); 9731 return false; 9732 } 9733 9734 bool ConstRHS = ConstArg && !FI->isMutable(); 9735 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9736 CSM, TSK_Field, TAH, Diagnose)) 9737 return false; 9738 } 9739 9740 return true; 9741 } 9742 9743 /// Diagnose why the specified class does not have a trivial special member of 9744 /// the given kind. 9745 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9746 QualType Ty = Context.getRecordType(RD); 9747 9748 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9749 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9750 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9751 /*Diagnose*/true); 9752 } 9753 9754 /// Determine whether a defaulted or deleted special member function is trivial, 9755 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9756 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9757 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9758 TrivialABIHandling TAH, bool Diagnose) { 9759 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9760 9761 CXXRecordDecl *RD = MD->getParent(); 9762 9763 bool ConstArg = false; 9764 9765 // C++11 [class.copy]p12, p25: [DR1593] 9766 // A [special member] is trivial if [...] its parameter-type-list is 9767 // equivalent to the parameter-type-list of an implicit declaration [...] 9768 switch (CSM) { 9769 case CXXDefaultConstructor: 9770 case CXXDestructor: 9771 // Trivial default constructors and destructors cannot have parameters. 9772 break; 9773 9774 case CXXCopyConstructor: 9775 case CXXCopyAssignment: { 9776 // Trivial copy operations always have const, non-volatile parameter types. 9777 ConstArg = true; 9778 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9779 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9780 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9781 if (Diagnose) 9782 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9783 << Param0->getSourceRange() << Param0->getType() 9784 << Context.getLValueReferenceType( 9785 Context.getRecordType(RD).withConst()); 9786 return false; 9787 } 9788 break; 9789 } 9790 9791 case CXXMoveConstructor: 9792 case CXXMoveAssignment: { 9793 // Trivial move operations always have non-cv-qualified parameters. 9794 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9795 const RValueReferenceType *RT = 9796 Param0->getType()->getAs<RValueReferenceType>(); 9797 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9798 if (Diagnose) 9799 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9800 << Param0->getSourceRange() << Param0->getType() 9801 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9802 return false; 9803 } 9804 break; 9805 } 9806 9807 case CXXInvalid: 9808 llvm_unreachable("not a special member"); 9809 } 9810 9811 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9812 if (Diagnose) 9813 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9814 diag::note_nontrivial_default_arg) 9815 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9816 return false; 9817 } 9818 if (MD->isVariadic()) { 9819 if (Diagnose) 9820 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9821 return false; 9822 } 9823 9824 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9825 // A copy/move [constructor or assignment operator] is trivial if 9826 // -- the [member] selected to copy/move each direct base class subobject 9827 // is trivial 9828 // 9829 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9830 // A [default constructor or destructor] is trivial if 9831 // -- all the direct base classes have trivial [default constructors or 9832 // destructors] 9833 for (const auto &BI : RD->bases()) 9834 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9835 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9836 return false; 9837 9838 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9839 // A copy/move [constructor or assignment operator] for a class X is 9840 // trivial if 9841 // -- for each non-static data member of X that is of class type (or array 9842 // thereof), the constructor selected to copy/move that member is 9843 // trivial 9844 // 9845 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9846 // A [default constructor or destructor] is trivial if 9847 // -- for all of the non-static data members of its class that are of class 9848 // type (or array thereof), each such class has a trivial [default 9849 // constructor or destructor] 9850 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9851 return false; 9852 9853 // C++11 [class.dtor]p5: 9854 // A destructor is trivial if [...] 9855 // -- the destructor is not virtual 9856 if (CSM == CXXDestructor && MD->isVirtual()) { 9857 if (Diagnose) 9858 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9859 return false; 9860 } 9861 9862 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9863 // A [special member] for class X is trivial if [...] 9864 // -- class X has no virtual functions and no virtual base classes 9865 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9866 if (!Diagnose) 9867 return false; 9868 9869 if (RD->getNumVBases()) { 9870 // Check for virtual bases. We already know that the corresponding 9871 // member in all bases is trivial, so vbases must all be direct. 9872 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9873 assert(BS.isVirtual()); 9874 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9875 return false; 9876 } 9877 9878 // Must have a virtual method. 9879 for (const auto *MI : RD->methods()) { 9880 if (MI->isVirtual()) { 9881 SourceLocation MLoc = MI->getBeginLoc(); 9882 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9883 return false; 9884 } 9885 } 9886 9887 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9888 } 9889 9890 // Looks like it's trivial! 9891 return true; 9892 } 9893 9894 namespace { 9895 struct FindHiddenVirtualMethod { 9896 Sema *S; 9897 CXXMethodDecl *Method; 9898 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9899 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9900 9901 private: 9902 /// Check whether any most overridden method from MD in Methods 9903 static bool CheckMostOverridenMethods( 9904 const CXXMethodDecl *MD, 9905 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9906 if (MD->size_overridden_methods() == 0) 9907 return Methods.count(MD->getCanonicalDecl()); 9908 for (const CXXMethodDecl *O : MD->overridden_methods()) 9909 if (CheckMostOverridenMethods(O, Methods)) 9910 return true; 9911 return false; 9912 } 9913 9914 public: 9915 /// Member lookup function that determines whether a given C++ 9916 /// method overloads virtual methods in a base class without overriding any, 9917 /// to be used with CXXRecordDecl::lookupInBases(). 9918 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9919 RecordDecl *BaseRecord = 9920 Specifier->getType()->castAs<RecordType>()->getDecl(); 9921 9922 DeclarationName Name = Method->getDeclName(); 9923 assert(Name.getNameKind() == DeclarationName::Identifier); 9924 9925 bool foundSameNameMethod = false; 9926 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9927 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9928 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9929 NamedDecl *D = *Path.Decls; 9930 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9931 MD = MD->getCanonicalDecl(); 9932 foundSameNameMethod = true; 9933 // Interested only in hidden virtual methods. 9934 if (!MD->isVirtual()) 9935 continue; 9936 // If the method we are checking overrides a method from its base 9937 // don't warn about the other overloaded methods. Clang deviates from 9938 // GCC by only diagnosing overloads of inherited virtual functions that 9939 // do not override any other virtual functions in the base. GCC's 9940 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9941 // function from a base class. These cases may be better served by a 9942 // warning (not specific to virtual functions) on call sites when the 9943 // call would select a different function from the base class, were it 9944 // visible. 9945 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9946 if (!S->IsOverload(Method, MD, false)) 9947 return true; 9948 // Collect the overload only if its hidden. 9949 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9950 overloadedMethods.push_back(MD); 9951 } 9952 } 9953 9954 if (foundSameNameMethod) 9955 OverloadedMethods.append(overloadedMethods.begin(), 9956 overloadedMethods.end()); 9957 return foundSameNameMethod; 9958 } 9959 }; 9960 } // end anonymous namespace 9961 9962 /// Add the most overridden methods from MD to Methods 9963 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9964 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9965 if (MD->size_overridden_methods() == 0) 9966 Methods.insert(MD->getCanonicalDecl()); 9967 else 9968 for (const CXXMethodDecl *O : MD->overridden_methods()) 9969 AddMostOverridenMethods(O, Methods); 9970 } 9971 9972 /// Check if a method overloads virtual methods in a base class without 9973 /// overriding any. 9974 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9975 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9976 if (!MD->getDeclName().isIdentifier()) 9977 return; 9978 9979 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9980 /*bool RecordPaths=*/false, 9981 /*bool DetectVirtual=*/false); 9982 FindHiddenVirtualMethod FHVM; 9983 FHVM.Method = MD; 9984 FHVM.S = this; 9985 9986 // Keep the base methods that were overridden or introduced in the subclass 9987 // by 'using' in a set. A base method not in this set is hidden. 9988 CXXRecordDecl *DC = MD->getParent(); 9989 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9990 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9991 NamedDecl *ND = *I; 9992 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9993 ND = shad->getTargetDecl(); 9994 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9995 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9996 } 9997 9998 if (DC->lookupInBases(FHVM, Paths)) 9999 OverloadedMethods = FHVM.OverloadedMethods; 10000 } 10001 10002 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 10003 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 10004 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 10005 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 10006 PartialDiagnostic PD = PDiag( 10007 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 10008 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 10009 Diag(overloadedMD->getLocation(), PD); 10010 } 10011 } 10012 10013 /// Diagnose methods which overload virtual methods in a base class 10014 /// without overriding any. 10015 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 10016 if (MD->isInvalidDecl()) 10017 return; 10018 10019 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 10020 return; 10021 10022 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 10023 FindHiddenVirtualMethods(MD, OverloadedMethods); 10024 if (!OverloadedMethods.empty()) { 10025 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 10026 << MD << (OverloadedMethods.size() > 1); 10027 10028 NoteHiddenVirtualMethods(MD, OverloadedMethods); 10029 } 10030 } 10031 10032 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 10033 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 10034 // No diagnostics if this is a template instantiation. 10035 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 10036 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10037 diag::ext_cannot_use_trivial_abi) << &RD; 10038 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10039 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 10040 } 10041 RD.dropAttr<TrivialABIAttr>(); 10042 }; 10043 10044 // Ill-formed if the copy and move constructors are deleted. 10045 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 10046 // If the type is dependent, then assume it might have 10047 // implicit copy or move ctor because we won't know yet at this point. 10048 if (RD.isDependentType()) 10049 return true; 10050 if (RD.needsImplicitCopyConstructor() && 10051 !RD.defaultedCopyConstructorIsDeleted()) 10052 return true; 10053 if (RD.needsImplicitMoveConstructor() && 10054 !RD.defaultedMoveConstructorIsDeleted()) 10055 return true; 10056 for (const CXXConstructorDecl *CD : RD.ctors()) 10057 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 10058 return true; 10059 return false; 10060 }; 10061 10062 if (!HasNonDeletedCopyOrMoveConstructor()) { 10063 PrintDiagAndRemoveAttr(0); 10064 return; 10065 } 10066 10067 // Ill-formed if the struct has virtual functions. 10068 if (RD.isPolymorphic()) { 10069 PrintDiagAndRemoveAttr(1); 10070 return; 10071 } 10072 10073 for (const auto &B : RD.bases()) { 10074 // Ill-formed if the base class is non-trivial for the purpose of calls or a 10075 // virtual base. 10076 if (!B.getType()->isDependentType() && 10077 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 10078 PrintDiagAndRemoveAttr(2); 10079 return; 10080 } 10081 10082 if (B.isVirtual()) { 10083 PrintDiagAndRemoveAttr(3); 10084 return; 10085 } 10086 } 10087 10088 for (const auto *FD : RD.fields()) { 10089 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 10090 // non-trivial for the purpose of calls. 10091 QualType FT = FD->getType(); 10092 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 10093 PrintDiagAndRemoveAttr(4); 10094 return; 10095 } 10096 10097 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 10098 if (!RT->isDependentType() && 10099 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 10100 PrintDiagAndRemoveAttr(5); 10101 return; 10102 } 10103 } 10104 } 10105 10106 void Sema::ActOnFinishCXXMemberSpecification( 10107 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 10108 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 10109 if (!TagDecl) 10110 return; 10111 10112 AdjustDeclIfTemplate(TagDecl); 10113 10114 for (const ParsedAttr &AL : AttrList) { 10115 if (AL.getKind() != ParsedAttr::AT_Visibility) 10116 continue; 10117 AL.setInvalid(); 10118 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10119 } 10120 10121 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 10122 // strict aliasing violation! 10123 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 10124 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 10125 10126 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10127 } 10128 10129 /// Find the equality comparison functions that should be implicitly declared 10130 /// in a given class definition, per C++2a [class.compare.default]p3. 10131 static void findImplicitlyDeclaredEqualityComparisons( 10132 ASTContext &Ctx, CXXRecordDecl *RD, 10133 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10134 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10135 if (!RD->lookup(EqEq).empty()) 10136 // Member operator== explicitly declared: no implicit operator==s. 10137 return; 10138 10139 // Traverse friends looking for an '==' or a '<=>'. 10140 for (FriendDecl *Friend : RD->friends()) { 10141 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10142 if (!FD) continue; 10143 10144 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10145 // Friend operator== explicitly declared: no implicit operator==s. 10146 Spaceships.clear(); 10147 return; 10148 } 10149 10150 if (FD->getOverloadedOperator() == OO_Spaceship && 10151 FD->isExplicitlyDefaulted()) 10152 Spaceships.push_back(FD); 10153 } 10154 10155 // Look for members named 'operator<=>'. 10156 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10157 for (NamedDecl *ND : RD->lookup(Cmp)) { 10158 // Note that we could find a non-function here (either a function template 10159 // or a using-declaration). Neither case results in an implicit 10160 // 'operator=='. 10161 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10162 if (FD->isExplicitlyDefaulted()) 10163 Spaceships.push_back(FD); 10164 } 10165 } 10166 10167 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10168 /// special functions, such as the default constructor, copy 10169 /// constructor, or destructor, to the given C++ class (C++ 10170 /// [special]p1). This routine can only be executed just before the 10171 /// definition of the class is complete. 10172 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10173 // Don't add implicit special members to templated classes. 10174 // FIXME: This means unqualified lookups for 'operator=' within a class 10175 // template don't work properly. 10176 if (!ClassDecl->isDependentType()) { 10177 if (ClassDecl->needsImplicitDefaultConstructor()) { 10178 ++getASTContext().NumImplicitDefaultConstructors; 10179 10180 if (ClassDecl->hasInheritedConstructor()) 10181 DeclareImplicitDefaultConstructor(ClassDecl); 10182 } 10183 10184 if (ClassDecl->needsImplicitCopyConstructor()) { 10185 ++getASTContext().NumImplicitCopyConstructors; 10186 10187 // If the properties or semantics of the copy constructor couldn't be 10188 // determined while the class was being declared, force a declaration 10189 // of it now. 10190 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10191 ClassDecl->hasInheritedConstructor()) 10192 DeclareImplicitCopyConstructor(ClassDecl); 10193 // For the MS ABI we need to know whether the copy ctor is deleted. A 10194 // prerequisite for deleting the implicit copy ctor is that the class has 10195 // a move ctor or move assignment that is either user-declared or whose 10196 // semantics are inherited from a subobject. FIXME: We should provide a 10197 // more direct way for CodeGen to ask whether the constructor was deleted. 10198 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10199 (ClassDecl->hasUserDeclaredMoveConstructor() || 10200 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10201 ClassDecl->hasUserDeclaredMoveAssignment() || 10202 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10203 DeclareImplicitCopyConstructor(ClassDecl); 10204 } 10205 10206 if (getLangOpts().CPlusPlus11 && 10207 ClassDecl->needsImplicitMoveConstructor()) { 10208 ++getASTContext().NumImplicitMoveConstructors; 10209 10210 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10211 ClassDecl->hasInheritedConstructor()) 10212 DeclareImplicitMoveConstructor(ClassDecl); 10213 } 10214 10215 if (ClassDecl->needsImplicitCopyAssignment()) { 10216 ++getASTContext().NumImplicitCopyAssignmentOperators; 10217 10218 // If we have a dynamic class, then the copy assignment operator may be 10219 // virtual, so we have to declare it immediately. This ensures that, e.g., 10220 // it shows up in the right place in the vtable and that we diagnose 10221 // problems with the implicit exception specification. 10222 if (ClassDecl->isDynamicClass() || 10223 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10224 ClassDecl->hasInheritedAssignment()) 10225 DeclareImplicitCopyAssignment(ClassDecl); 10226 } 10227 10228 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10229 ++getASTContext().NumImplicitMoveAssignmentOperators; 10230 10231 // Likewise for the move assignment operator. 10232 if (ClassDecl->isDynamicClass() || 10233 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10234 ClassDecl->hasInheritedAssignment()) 10235 DeclareImplicitMoveAssignment(ClassDecl); 10236 } 10237 10238 if (ClassDecl->needsImplicitDestructor()) { 10239 ++getASTContext().NumImplicitDestructors; 10240 10241 // If we have a dynamic class, then the destructor may be virtual, so we 10242 // have to declare the destructor immediately. This ensures that, e.g., it 10243 // shows up in the right place in the vtable and that we diagnose problems 10244 // with the implicit exception specification. 10245 if (ClassDecl->isDynamicClass() || 10246 ClassDecl->needsOverloadResolutionForDestructor()) 10247 DeclareImplicitDestructor(ClassDecl); 10248 } 10249 } 10250 10251 // C++2a [class.compare.default]p3: 10252 // If the member-specification does not explicitly declare any member or 10253 // friend named operator==, an == operator function is declared implicitly 10254 // for each defaulted three-way comparison operator function defined in 10255 // the member-specification 10256 // FIXME: Consider doing this lazily. 10257 // We do this during the initial parse for a class template, not during 10258 // instantiation, so that we can handle unqualified lookups for 'operator==' 10259 // when parsing the template. 10260 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10261 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10262 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10263 DefaultedSpaceships); 10264 for (auto *FD : DefaultedSpaceships) 10265 DeclareImplicitEqualityComparison(ClassDecl, FD); 10266 } 10267 } 10268 10269 unsigned 10270 Sema::ActOnReenterTemplateScope(Decl *D, 10271 llvm::function_ref<Scope *()> EnterScope) { 10272 if (!D) 10273 return 0; 10274 AdjustDeclIfTemplate(D); 10275 10276 // In order to get name lookup right, reenter template scopes in order from 10277 // outermost to innermost. 10278 SmallVector<TemplateParameterList *, 4> ParameterLists; 10279 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10280 10281 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10282 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10283 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10284 10285 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10286 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10287 ParameterLists.push_back(FTD->getTemplateParameters()); 10288 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10289 LookupDC = VD->getDeclContext(); 10290 10291 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10292 ParameterLists.push_back(VTD->getTemplateParameters()); 10293 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10294 ParameterLists.push_back(PSD->getTemplateParameters()); 10295 } 10296 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10297 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10298 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10299 10300 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10301 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10302 ParameterLists.push_back(CTD->getTemplateParameters()); 10303 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10304 ParameterLists.push_back(PSD->getTemplateParameters()); 10305 } 10306 } 10307 // FIXME: Alias declarations and concepts. 10308 10309 unsigned Count = 0; 10310 Scope *InnermostTemplateScope = nullptr; 10311 for (TemplateParameterList *Params : ParameterLists) { 10312 // Ignore explicit specializations; they don't contribute to the template 10313 // depth. 10314 if (Params->size() == 0) 10315 continue; 10316 10317 InnermostTemplateScope = EnterScope(); 10318 for (NamedDecl *Param : *Params) { 10319 if (Param->getDeclName()) { 10320 InnermostTemplateScope->AddDecl(Param); 10321 IdResolver.AddDecl(Param); 10322 } 10323 } 10324 ++Count; 10325 } 10326 10327 // Associate the new template scopes with the corresponding entities. 10328 if (InnermostTemplateScope) { 10329 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10330 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10331 } 10332 10333 return Count; 10334 } 10335 10336 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10337 if (!RecordD) return; 10338 AdjustDeclIfTemplate(RecordD); 10339 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10340 PushDeclContext(S, Record); 10341 } 10342 10343 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10344 if (!RecordD) return; 10345 PopDeclContext(); 10346 } 10347 10348 /// This is used to implement the constant expression evaluation part of the 10349 /// attribute enable_if extension. There is nothing in standard C++ which would 10350 /// require reentering parameters. 10351 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10352 if (!Param) 10353 return; 10354 10355 S->AddDecl(Param); 10356 if (Param->getDeclName()) 10357 IdResolver.AddDecl(Param); 10358 } 10359 10360 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10361 /// parsing a top-level (non-nested) C++ class, and we are now 10362 /// parsing those parts of the given Method declaration that could 10363 /// not be parsed earlier (C++ [class.mem]p2), such as default 10364 /// arguments. This action should enter the scope of the given 10365 /// Method declaration as if we had just parsed the qualified method 10366 /// name. However, it should not bring the parameters into scope; 10367 /// that will be performed by ActOnDelayedCXXMethodParameter. 10368 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10369 } 10370 10371 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10372 /// C++ method declaration. We're (re-)introducing the given 10373 /// function parameter into scope for use in parsing later parts of 10374 /// the method declaration. For example, we could see an 10375 /// ActOnParamDefaultArgument event for this parameter. 10376 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10377 if (!ParamD) 10378 return; 10379 10380 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10381 10382 S->AddDecl(Param); 10383 if (Param->getDeclName()) 10384 IdResolver.AddDecl(Param); 10385 } 10386 10387 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10388 /// processing the delayed method declaration for Method. The method 10389 /// declaration is now considered finished. There may be a separate 10390 /// ActOnStartOfFunctionDef action later (not necessarily 10391 /// immediately!) for this method, if it was also defined inside the 10392 /// class body. 10393 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10394 if (!MethodD) 10395 return; 10396 10397 AdjustDeclIfTemplate(MethodD); 10398 10399 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10400 10401 // Now that we have our default arguments, check the constructor 10402 // again. It could produce additional diagnostics or affect whether 10403 // the class has implicitly-declared destructors, among other 10404 // things. 10405 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10406 CheckConstructor(Constructor); 10407 10408 // Check the default arguments, which we may have added. 10409 if (!Method->isInvalidDecl()) 10410 CheckCXXDefaultArguments(Method); 10411 } 10412 10413 // Emit the given diagnostic for each non-address-space qualifier. 10414 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10415 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10416 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10417 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10418 bool DiagOccured = false; 10419 FTI.MethodQualifiers->forEachQualifier( 10420 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10421 SourceLocation SL) { 10422 // This diagnostic should be emitted on any qualifier except an addr 10423 // space qualifier. However, forEachQualifier currently doesn't visit 10424 // addr space qualifiers, so there's no way to write this condition 10425 // right now; we just diagnose on everything. 10426 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10427 DiagOccured = true; 10428 }); 10429 if (DiagOccured) 10430 D.setInvalidType(); 10431 } 10432 } 10433 10434 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10435 /// the well-formedness of the constructor declarator @p D with type @p 10436 /// R. If there are any errors in the declarator, this routine will 10437 /// emit diagnostics and set the invalid bit to true. In any case, the type 10438 /// will be updated to reflect a well-formed type for the constructor and 10439 /// returned. 10440 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10441 StorageClass &SC) { 10442 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10443 10444 // C++ [class.ctor]p3: 10445 // A constructor shall not be virtual (10.3) or static (9.4). A 10446 // constructor can be invoked for a const, volatile or const 10447 // volatile object. A constructor shall not be declared const, 10448 // volatile, or const volatile (9.3.2). 10449 if (isVirtual) { 10450 if (!D.isInvalidType()) 10451 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10452 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10453 << SourceRange(D.getIdentifierLoc()); 10454 D.setInvalidType(); 10455 } 10456 if (SC == SC_Static) { 10457 if (!D.isInvalidType()) 10458 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10459 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10460 << SourceRange(D.getIdentifierLoc()); 10461 D.setInvalidType(); 10462 SC = SC_None; 10463 } 10464 10465 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10466 diagnoseIgnoredQualifiers( 10467 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10468 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10469 D.getDeclSpec().getRestrictSpecLoc(), 10470 D.getDeclSpec().getAtomicSpecLoc()); 10471 D.setInvalidType(); 10472 } 10473 10474 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10475 10476 // C++0x [class.ctor]p4: 10477 // A constructor shall not be declared with a ref-qualifier. 10478 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10479 if (FTI.hasRefQualifier()) { 10480 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10481 << FTI.RefQualifierIsLValueRef 10482 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10483 D.setInvalidType(); 10484 } 10485 10486 // Rebuild the function type "R" without any type qualifiers (in 10487 // case any of the errors above fired) and with "void" as the 10488 // return type, since constructors don't have return types. 10489 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10490 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10491 return R; 10492 10493 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10494 EPI.TypeQuals = Qualifiers(); 10495 EPI.RefQualifier = RQ_None; 10496 10497 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10498 } 10499 10500 /// CheckConstructor - Checks a fully-formed constructor for 10501 /// well-formedness, issuing any diagnostics required. Returns true if 10502 /// the constructor declarator is invalid. 10503 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10504 CXXRecordDecl *ClassDecl 10505 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10506 if (!ClassDecl) 10507 return Constructor->setInvalidDecl(); 10508 10509 // C++ [class.copy]p3: 10510 // A declaration of a constructor for a class X is ill-formed if 10511 // its first parameter is of type (optionally cv-qualified) X and 10512 // either there are no other parameters or else all other 10513 // parameters have default arguments. 10514 if (!Constructor->isInvalidDecl() && 10515 Constructor->hasOneParamOrDefaultArgs() && 10516 Constructor->getTemplateSpecializationKind() != 10517 TSK_ImplicitInstantiation) { 10518 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10519 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10520 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10521 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10522 const char *ConstRef 10523 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10524 : " const &"; 10525 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10526 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10527 10528 // FIXME: Rather that making the constructor invalid, we should endeavor 10529 // to fix the type. 10530 Constructor->setInvalidDecl(); 10531 } 10532 } 10533 } 10534 10535 /// CheckDestructor - Checks a fully-formed destructor definition for 10536 /// well-formedness, issuing any diagnostics required. Returns true 10537 /// on error. 10538 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10539 CXXRecordDecl *RD = Destructor->getParent(); 10540 10541 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10542 SourceLocation Loc; 10543 10544 if (!Destructor->isImplicit()) 10545 Loc = Destructor->getLocation(); 10546 else 10547 Loc = RD->getLocation(); 10548 10549 // If we have a virtual destructor, look up the deallocation function 10550 if (FunctionDecl *OperatorDelete = 10551 FindDeallocationFunctionForDestructor(Loc, RD)) { 10552 Expr *ThisArg = nullptr; 10553 10554 // If the notional 'delete this' expression requires a non-trivial 10555 // conversion from 'this' to the type of a destroying operator delete's 10556 // first parameter, perform that conversion now. 10557 if (OperatorDelete->isDestroyingOperatorDelete()) { 10558 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10559 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10560 // C++ [class.dtor]p13: 10561 // ... as if for the expression 'delete this' appearing in a 10562 // non-virtual destructor of the destructor's class. 10563 ContextRAII SwitchContext(*this, Destructor); 10564 ExprResult This = 10565 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10566 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10567 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10568 if (This.isInvalid()) { 10569 // FIXME: Register this as a context note so that it comes out 10570 // in the right order. 10571 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10572 return true; 10573 } 10574 ThisArg = This.get(); 10575 } 10576 } 10577 10578 DiagnoseUseOfDecl(OperatorDelete, Loc); 10579 MarkFunctionReferenced(Loc, OperatorDelete); 10580 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10581 } 10582 } 10583 10584 return false; 10585 } 10586 10587 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10588 /// the well-formednes of the destructor declarator @p D with type @p 10589 /// R. If there are any errors in the declarator, this routine will 10590 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10591 /// will be updated to reflect a well-formed type for the destructor and 10592 /// returned. 10593 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10594 StorageClass& SC) { 10595 // C++ [class.dtor]p1: 10596 // [...] A typedef-name that names a class is a class-name 10597 // (7.1.3); however, a typedef-name that names a class shall not 10598 // be used as the identifier in the declarator for a destructor 10599 // declaration. 10600 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10601 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10602 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10603 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10604 else if (const TemplateSpecializationType *TST = 10605 DeclaratorType->getAs<TemplateSpecializationType>()) 10606 if (TST->isTypeAlias()) 10607 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10608 << DeclaratorType << 1; 10609 10610 // C++ [class.dtor]p2: 10611 // A destructor is used to destroy objects of its class type. A 10612 // destructor takes no parameters, and no return type can be 10613 // specified for it (not even void). The address of a destructor 10614 // shall not be taken. A destructor shall not be static. A 10615 // destructor can be invoked for a const, volatile or const 10616 // volatile object. A destructor shall not be declared const, 10617 // volatile or const volatile (9.3.2). 10618 if (SC == SC_Static) { 10619 if (!D.isInvalidType()) 10620 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10621 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10622 << SourceRange(D.getIdentifierLoc()) 10623 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10624 10625 SC = SC_None; 10626 } 10627 if (!D.isInvalidType()) { 10628 // Destructors don't have return types, but the parser will 10629 // happily parse something like: 10630 // 10631 // class X { 10632 // float ~X(); 10633 // }; 10634 // 10635 // The return type will be eliminated later. 10636 if (D.getDeclSpec().hasTypeSpecifier()) 10637 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10638 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10639 << SourceRange(D.getIdentifierLoc()); 10640 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10641 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10642 SourceLocation(), 10643 D.getDeclSpec().getConstSpecLoc(), 10644 D.getDeclSpec().getVolatileSpecLoc(), 10645 D.getDeclSpec().getRestrictSpecLoc(), 10646 D.getDeclSpec().getAtomicSpecLoc()); 10647 D.setInvalidType(); 10648 } 10649 } 10650 10651 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10652 10653 // C++0x [class.dtor]p2: 10654 // A destructor shall not be declared with a ref-qualifier. 10655 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10656 if (FTI.hasRefQualifier()) { 10657 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10658 << FTI.RefQualifierIsLValueRef 10659 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10660 D.setInvalidType(); 10661 } 10662 10663 // Make sure we don't have any parameters. 10664 if (FTIHasNonVoidParameters(FTI)) { 10665 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10666 10667 // Delete the parameters. 10668 FTI.freeParams(); 10669 D.setInvalidType(); 10670 } 10671 10672 // Make sure the destructor isn't variadic. 10673 if (FTI.isVariadic) { 10674 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10675 D.setInvalidType(); 10676 } 10677 10678 // Rebuild the function type "R" without any type qualifiers or 10679 // parameters (in case any of the errors above fired) and with 10680 // "void" as the return type, since destructors don't have return 10681 // types. 10682 if (!D.isInvalidType()) 10683 return R; 10684 10685 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10686 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10687 EPI.Variadic = false; 10688 EPI.TypeQuals = Qualifiers(); 10689 EPI.RefQualifier = RQ_None; 10690 return Context.getFunctionType(Context.VoidTy, None, EPI); 10691 } 10692 10693 static void extendLeft(SourceRange &R, SourceRange Before) { 10694 if (Before.isInvalid()) 10695 return; 10696 R.setBegin(Before.getBegin()); 10697 if (R.getEnd().isInvalid()) 10698 R.setEnd(Before.getEnd()); 10699 } 10700 10701 static void extendRight(SourceRange &R, SourceRange After) { 10702 if (After.isInvalid()) 10703 return; 10704 if (R.getBegin().isInvalid()) 10705 R.setBegin(After.getBegin()); 10706 R.setEnd(After.getEnd()); 10707 } 10708 10709 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10710 /// well-formednes of the conversion function declarator @p D with 10711 /// type @p R. If there are any errors in the declarator, this routine 10712 /// will emit diagnostics and return true. Otherwise, it will return 10713 /// false. Either way, the type @p R will be updated to reflect a 10714 /// well-formed type for the conversion operator. 10715 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10716 StorageClass& SC) { 10717 // C++ [class.conv.fct]p1: 10718 // Neither parameter types nor return type can be specified. The 10719 // type of a conversion function (8.3.5) is "function taking no 10720 // parameter returning conversion-type-id." 10721 if (SC == SC_Static) { 10722 if (!D.isInvalidType()) 10723 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10724 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10725 << D.getName().getSourceRange(); 10726 D.setInvalidType(); 10727 SC = SC_None; 10728 } 10729 10730 TypeSourceInfo *ConvTSI = nullptr; 10731 QualType ConvType = 10732 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10733 10734 const DeclSpec &DS = D.getDeclSpec(); 10735 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10736 // Conversion functions don't have return types, but the parser will 10737 // happily parse something like: 10738 // 10739 // class X { 10740 // float operator bool(); 10741 // }; 10742 // 10743 // The return type will be changed later anyway. 10744 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10745 << SourceRange(DS.getTypeSpecTypeLoc()) 10746 << SourceRange(D.getIdentifierLoc()); 10747 D.setInvalidType(); 10748 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10749 // It's also plausible that the user writes type qualifiers in the wrong 10750 // place, such as: 10751 // struct S { const operator int(); }; 10752 // FIXME: we could provide a fixit to move the qualifiers onto the 10753 // conversion type. 10754 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10755 << SourceRange(D.getIdentifierLoc()) << 0; 10756 D.setInvalidType(); 10757 } 10758 10759 const auto *Proto = R->castAs<FunctionProtoType>(); 10760 10761 // Make sure we don't have any parameters. 10762 if (Proto->getNumParams() > 0) { 10763 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10764 10765 // Delete the parameters. 10766 D.getFunctionTypeInfo().freeParams(); 10767 D.setInvalidType(); 10768 } else if (Proto->isVariadic()) { 10769 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10770 D.setInvalidType(); 10771 } 10772 10773 // Diagnose "&operator bool()" and other such nonsense. This 10774 // is actually a gcc extension which we don't support. 10775 if (Proto->getReturnType() != ConvType) { 10776 bool NeedsTypedef = false; 10777 SourceRange Before, After; 10778 10779 // Walk the chunks and extract information on them for our diagnostic. 10780 bool PastFunctionChunk = false; 10781 for (auto &Chunk : D.type_objects()) { 10782 switch (Chunk.Kind) { 10783 case DeclaratorChunk::Function: 10784 if (!PastFunctionChunk) { 10785 if (Chunk.Fun.HasTrailingReturnType) { 10786 TypeSourceInfo *TRT = nullptr; 10787 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10788 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10789 } 10790 PastFunctionChunk = true; 10791 break; 10792 } 10793 LLVM_FALLTHROUGH; 10794 case DeclaratorChunk::Array: 10795 NeedsTypedef = true; 10796 extendRight(After, Chunk.getSourceRange()); 10797 break; 10798 10799 case DeclaratorChunk::Pointer: 10800 case DeclaratorChunk::BlockPointer: 10801 case DeclaratorChunk::Reference: 10802 case DeclaratorChunk::MemberPointer: 10803 case DeclaratorChunk::Pipe: 10804 extendLeft(Before, Chunk.getSourceRange()); 10805 break; 10806 10807 case DeclaratorChunk::Paren: 10808 extendLeft(Before, Chunk.Loc); 10809 extendRight(After, Chunk.EndLoc); 10810 break; 10811 } 10812 } 10813 10814 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10815 After.isValid() ? After.getBegin() : 10816 D.getIdentifierLoc(); 10817 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10818 DB << Before << After; 10819 10820 if (!NeedsTypedef) { 10821 DB << /*don't need a typedef*/0; 10822 10823 // If we can provide a correct fix-it hint, do so. 10824 if (After.isInvalid() && ConvTSI) { 10825 SourceLocation InsertLoc = 10826 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10827 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10828 << FixItHint::CreateInsertionFromRange( 10829 InsertLoc, CharSourceRange::getTokenRange(Before)) 10830 << FixItHint::CreateRemoval(Before); 10831 } 10832 } else if (!Proto->getReturnType()->isDependentType()) { 10833 DB << /*typedef*/1 << Proto->getReturnType(); 10834 } else if (getLangOpts().CPlusPlus11) { 10835 DB << /*alias template*/2 << Proto->getReturnType(); 10836 } else { 10837 DB << /*might not be fixable*/3; 10838 } 10839 10840 // Recover by incorporating the other type chunks into the result type. 10841 // Note, this does *not* change the name of the function. This is compatible 10842 // with the GCC extension: 10843 // struct S { &operator int(); } s; 10844 // int &r = s.operator int(); // ok in GCC 10845 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10846 ConvType = Proto->getReturnType(); 10847 } 10848 10849 // C++ [class.conv.fct]p4: 10850 // The conversion-type-id shall not represent a function type nor 10851 // an array type. 10852 if (ConvType->isArrayType()) { 10853 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10854 ConvType = Context.getPointerType(ConvType); 10855 D.setInvalidType(); 10856 } else if (ConvType->isFunctionType()) { 10857 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10858 ConvType = Context.getPointerType(ConvType); 10859 D.setInvalidType(); 10860 } 10861 10862 // Rebuild the function type "R" without any parameters (in case any 10863 // of the errors above fired) and with the conversion type as the 10864 // return type. 10865 if (D.isInvalidType()) 10866 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10867 10868 // C++0x explicit conversion operators. 10869 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10870 Diag(DS.getExplicitSpecLoc(), 10871 getLangOpts().CPlusPlus11 10872 ? diag::warn_cxx98_compat_explicit_conversion_functions 10873 : diag::ext_explicit_conversion_functions) 10874 << SourceRange(DS.getExplicitSpecRange()); 10875 } 10876 10877 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10878 /// the declaration of the given C++ conversion function. This routine 10879 /// is responsible for recording the conversion function in the C++ 10880 /// class, if possible. 10881 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10882 assert(Conversion && "Expected to receive a conversion function declaration"); 10883 10884 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10885 10886 // Make sure we aren't redeclaring the conversion function. 10887 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10888 // C++ [class.conv.fct]p1: 10889 // [...] A conversion function is never used to convert a 10890 // (possibly cv-qualified) object to the (possibly cv-qualified) 10891 // same object type (or a reference to it), to a (possibly 10892 // cv-qualified) base class of that type (or a reference to it), 10893 // or to (possibly cv-qualified) void. 10894 QualType ClassType 10895 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10896 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10897 ConvType = ConvTypeRef->getPointeeType(); 10898 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10899 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10900 /* Suppress diagnostics for instantiations. */; 10901 else if (Conversion->size_overridden_methods() != 0) 10902 /* Suppress diagnostics for overriding virtual function in a base class. */; 10903 else if (ConvType->isRecordType()) { 10904 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10905 if (ConvType == ClassType) 10906 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10907 << ClassType; 10908 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10909 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10910 << ClassType << ConvType; 10911 } else if (ConvType->isVoidType()) { 10912 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10913 << ClassType << ConvType; 10914 } 10915 10916 if (FunctionTemplateDecl *ConversionTemplate 10917 = Conversion->getDescribedFunctionTemplate()) 10918 return ConversionTemplate; 10919 10920 return Conversion; 10921 } 10922 10923 namespace { 10924 /// Utility class to accumulate and print a diagnostic listing the invalid 10925 /// specifier(s) on a declaration. 10926 struct BadSpecifierDiagnoser { 10927 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10928 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10929 ~BadSpecifierDiagnoser() { 10930 Diagnostic << Specifiers; 10931 } 10932 10933 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10934 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10935 } 10936 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10937 return check(SpecLoc, 10938 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10939 } 10940 void check(SourceLocation SpecLoc, const char *Spec) { 10941 if (SpecLoc.isInvalid()) return; 10942 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10943 if (!Specifiers.empty()) Specifiers += " "; 10944 Specifiers += Spec; 10945 } 10946 10947 Sema &S; 10948 Sema::SemaDiagnosticBuilder Diagnostic; 10949 std::string Specifiers; 10950 }; 10951 } 10952 10953 /// Check the validity of a declarator that we parsed for a deduction-guide. 10954 /// These aren't actually declarators in the grammar, so we need to check that 10955 /// the user didn't specify any pieces that are not part of the deduction-guide 10956 /// grammar. 10957 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10958 StorageClass &SC) { 10959 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10960 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10961 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10962 10963 // C++ [temp.deduct.guide]p3: 10964 // A deduction-gide shall be declared in the same scope as the 10965 // corresponding class template. 10966 if (!CurContext->getRedeclContext()->Equals( 10967 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10968 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10969 << GuidedTemplateDecl; 10970 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10971 } 10972 10973 auto &DS = D.getMutableDeclSpec(); 10974 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10975 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10976 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10977 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10978 BadSpecifierDiagnoser Diagnoser( 10979 *this, D.getIdentifierLoc(), 10980 diag::err_deduction_guide_invalid_specifier); 10981 10982 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10983 DS.ClearStorageClassSpecs(); 10984 SC = SC_None; 10985 10986 // 'explicit' is permitted. 10987 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10988 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10989 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10990 DS.ClearConstexprSpec(); 10991 10992 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10993 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10994 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10995 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10996 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10997 DS.ClearTypeQualifiers(); 10998 10999 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 11000 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 11001 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 11002 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 11003 DS.ClearTypeSpecType(); 11004 } 11005 11006 if (D.isInvalidType()) 11007 return; 11008 11009 // Check the declarator is simple enough. 11010 bool FoundFunction = false; 11011 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 11012 if (Chunk.Kind == DeclaratorChunk::Paren) 11013 continue; 11014 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 11015 Diag(D.getDeclSpec().getBeginLoc(), 11016 diag::err_deduction_guide_with_complex_decl) 11017 << D.getSourceRange(); 11018 break; 11019 } 11020 if (!Chunk.Fun.hasTrailingReturnType()) { 11021 Diag(D.getName().getBeginLoc(), 11022 diag::err_deduction_guide_no_trailing_return_type); 11023 break; 11024 } 11025 11026 // Check that the return type is written as a specialization of 11027 // the template specified as the deduction-guide's name. 11028 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 11029 TypeSourceInfo *TSI = nullptr; 11030 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 11031 assert(TSI && "deduction guide has valid type but invalid return type?"); 11032 bool AcceptableReturnType = false; 11033 bool MightInstantiateToSpecialization = false; 11034 if (auto RetTST = 11035 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 11036 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 11037 bool TemplateMatches = 11038 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 11039 // FIXME: We should consider other template kinds (using, qualified), 11040 // otherwise we will emit bogus diagnostics. 11041 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 11042 AcceptableReturnType = true; 11043 else { 11044 // This could still instantiate to the right type, unless we know it 11045 // names the wrong class template. 11046 auto *TD = SpecifiedName.getAsTemplateDecl(); 11047 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 11048 !TemplateMatches); 11049 } 11050 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 11051 MightInstantiateToSpecialization = true; 11052 } 11053 11054 if (!AcceptableReturnType) { 11055 Diag(TSI->getTypeLoc().getBeginLoc(), 11056 diag::err_deduction_guide_bad_trailing_return_type) 11057 << GuidedTemplate << TSI->getType() 11058 << MightInstantiateToSpecialization 11059 << TSI->getTypeLoc().getSourceRange(); 11060 } 11061 11062 // Keep going to check that we don't have any inner declarator pieces (we 11063 // could still have a function returning a pointer to a function). 11064 FoundFunction = true; 11065 } 11066 11067 if (D.isFunctionDefinition()) 11068 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 11069 } 11070 11071 //===----------------------------------------------------------------------===// 11072 // Namespace Handling 11073 //===----------------------------------------------------------------------===// 11074 11075 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 11076 /// reopened. 11077 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 11078 SourceLocation Loc, 11079 IdentifierInfo *II, bool *IsInline, 11080 NamespaceDecl *PrevNS) { 11081 assert(*IsInline != PrevNS->isInline()); 11082 11083 // 'inline' must appear on the original definition, but not necessarily 11084 // on all extension definitions, so the note should point to the first 11085 // definition to avoid confusion. 11086 PrevNS = PrevNS->getFirstDecl(); 11087 11088 if (PrevNS->isInline()) 11089 // The user probably just forgot the 'inline', so suggest that it 11090 // be added back. 11091 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 11092 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 11093 else 11094 S.Diag(Loc, diag::err_inline_namespace_mismatch); 11095 11096 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 11097 *IsInline = PrevNS->isInline(); 11098 } 11099 11100 /// ActOnStartNamespaceDef - This is called at the start of a namespace 11101 /// definition. 11102 Decl *Sema::ActOnStartNamespaceDef( 11103 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 11104 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 11105 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 11106 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 11107 // For anonymous namespace, take the location of the left brace. 11108 SourceLocation Loc = II ? IdentLoc : LBrace; 11109 bool IsInline = InlineLoc.isValid(); 11110 bool IsInvalid = false; 11111 bool IsStd = false; 11112 bool AddToKnown = false; 11113 Scope *DeclRegionScope = NamespcScope->getParent(); 11114 11115 NamespaceDecl *PrevNS = nullptr; 11116 if (II) { 11117 // C++ [namespace.def]p2: 11118 // The identifier in an original-namespace-definition shall not 11119 // have been previously defined in the declarative region in 11120 // which the original-namespace-definition appears. The 11121 // identifier in an original-namespace-definition is the name of 11122 // the namespace. Subsequently in that declarative region, it is 11123 // treated as an original-namespace-name. 11124 // 11125 // Since namespace names are unique in their scope, and we don't 11126 // look through using directives, just look for any ordinary names 11127 // as if by qualified name lookup. 11128 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11129 ForExternalRedeclaration); 11130 LookupQualifiedName(R, CurContext->getRedeclContext()); 11131 NamedDecl *PrevDecl = 11132 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11133 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11134 11135 if (PrevNS) { 11136 // This is an extended namespace definition. 11137 if (IsInline != PrevNS->isInline()) 11138 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11139 &IsInline, PrevNS); 11140 } else if (PrevDecl) { 11141 // This is an invalid name redefinition. 11142 Diag(Loc, diag::err_redefinition_different_kind) 11143 << II; 11144 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11145 IsInvalid = true; 11146 // Continue on to push Namespc as current DeclContext and return it. 11147 } else if (II->isStr("std") && 11148 CurContext->getRedeclContext()->isTranslationUnit()) { 11149 // This is the first "real" definition of the namespace "std", so update 11150 // our cache of the "std" namespace to point at this definition. 11151 PrevNS = getStdNamespace(); 11152 IsStd = true; 11153 AddToKnown = !IsInline; 11154 } else { 11155 // We've seen this namespace for the first time. 11156 AddToKnown = !IsInline; 11157 } 11158 } else { 11159 // Anonymous namespaces. 11160 11161 // Determine whether the parent already has an anonymous namespace. 11162 DeclContext *Parent = CurContext->getRedeclContext(); 11163 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11164 PrevNS = TU->getAnonymousNamespace(); 11165 } else { 11166 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11167 PrevNS = ND->getAnonymousNamespace(); 11168 } 11169 11170 if (PrevNS && IsInline != PrevNS->isInline()) 11171 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11172 &IsInline, PrevNS); 11173 } 11174 11175 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11176 StartLoc, Loc, II, PrevNS); 11177 if (IsInvalid) 11178 Namespc->setInvalidDecl(); 11179 11180 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11181 AddPragmaAttributes(DeclRegionScope, Namespc); 11182 11183 // FIXME: Should we be merging attributes? 11184 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11185 PushNamespaceVisibilityAttr(Attr, Loc); 11186 11187 if (IsStd) 11188 StdNamespace = Namespc; 11189 if (AddToKnown) 11190 KnownNamespaces[Namespc] = false; 11191 11192 if (II) { 11193 PushOnScopeChains(Namespc, DeclRegionScope); 11194 } else { 11195 // Link the anonymous namespace into its parent. 11196 DeclContext *Parent = CurContext->getRedeclContext(); 11197 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11198 TU->setAnonymousNamespace(Namespc); 11199 } else { 11200 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11201 } 11202 11203 CurContext->addDecl(Namespc); 11204 11205 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11206 // behaves as if it were replaced by 11207 // namespace unique { /* empty body */ } 11208 // using namespace unique; 11209 // namespace unique { namespace-body } 11210 // where all occurrences of 'unique' in a translation unit are 11211 // replaced by the same identifier and this identifier differs 11212 // from all other identifiers in the entire program. 11213 11214 // We just create the namespace with an empty name and then add an 11215 // implicit using declaration, just like the standard suggests. 11216 // 11217 // CodeGen enforces the "universally unique" aspect by giving all 11218 // declarations semantically contained within an anonymous 11219 // namespace internal linkage. 11220 11221 if (!PrevNS) { 11222 UD = UsingDirectiveDecl::Create(Context, Parent, 11223 /* 'using' */ LBrace, 11224 /* 'namespace' */ SourceLocation(), 11225 /* qualifier */ NestedNameSpecifierLoc(), 11226 /* identifier */ SourceLocation(), 11227 Namespc, 11228 /* Ancestor */ Parent); 11229 UD->setImplicit(); 11230 Parent->addDecl(UD); 11231 } 11232 } 11233 11234 ActOnDocumentableDecl(Namespc); 11235 11236 // Although we could have an invalid decl (i.e. the namespace name is a 11237 // redefinition), push it as current DeclContext and try to continue parsing. 11238 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11239 // for the namespace has the declarations that showed up in that particular 11240 // namespace definition. 11241 PushDeclContext(NamespcScope, Namespc); 11242 return Namespc; 11243 } 11244 11245 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11246 /// is a namespace alias, returns the namespace it points to. 11247 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11248 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11249 return AD->getNamespace(); 11250 return dyn_cast_or_null<NamespaceDecl>(D); 11251 } 11252 11253 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11254 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11255 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11256 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11257 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11258 Namespc->setRBraceLoc(RBrace); 11259 PopDeclContext(); 11260 if (Namespc->hasAttr<VisibilityAttr>()) 11261 PopPragmaVisibility(true, RBrace); 11262 // If this namespace contains an export-declaration, export it now. 11263 if (DeferredExportedNamespaces.erase(Namespc)) 11264 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11265 } 11266 11267 CXXRecordDecl *Sema::getStdBadAlloc() const { 11268 return cast_or_null<CXXRecordDecl>( 11269 StdBadAlloc.get(Context.getExternalSource())); 11270 } 11271 11272 EnumDecl *Sema::getStdAlignValT() const { 11273 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11274 } 11275 11276 NamespaceDecl *Sema::getStdNamespace() const { 11277 return cast_or_null<NamespaceDecl>( 11278 StdNamespace.get(Context.getExternalSource())); 11279 } 11280 11281 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11282 if (!StdExperimentalNamespaceCache) { 11283 if (auto Std = getStdNamespace()) { 11284 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11285 SourceLocation(), LookupNamespaceName); 11286 if (!LookupQualifiedName(Result, Std) || 11287 !(StdExperimentalNamespaceCache = 11288 Result.getAsSingle<NamespaceDecl>())) 11289 Result.suppressDiagnostics(); 11290 } 11291 } 11292 return StdExperimentalNamespaceCache; 11293 } 11294 11295 namespace { 11296 11297 enum UnsupportedSTLSelect { 11298 USS_InvalidMember, 11299 USS_MissingMember, 11300 USS_NonTrivial, 11301 USS_Other 11302 }; 11303 11304 struct InvalidSTLDiagnoser { 11305 Sema &S; 11306 SourceLocation Loc; 11307 QualType TyForDiags; 11308 11309 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11310 const VarDecl *VD = nullptr) { 11311 { 11312 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11313 << TyForDiags << ((int)Sel); 11314 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11315 assert(!Name.empty()); 11316 D << Name; 11317 } 11318 } 11319 if (Sel == USS_InvalidMember) { 11320 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11321 << VD << VD->getSourceRange(); 11322 } 11323 return QualType(); 11324 } 11325 }; 11326 } // namespace 11327 11328 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11329 SourceLocation Loc, 11330 ComparisonCategoryUsage Usage) { 11331 assert(getLangOpts().CPlusPlus && 11332 "Looking for comparison category type outside of C++."); 11333 11334 // Use an elaborated type for diagnostics which has a name containing the 11335 // prepended 'std' namespace but not any inline namespace names. 11336 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11337 auto *NNS = 11338 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11339 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11340 }; 11341 11342 // Check if we've already successfully checked the comparison category type 11343 // before. If so, skip checking it again. 11344 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11345 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11346 // The only thing we need to check is that the type has a reachable 11347 // definition in the current context. 11348 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11349 return QualType(); 11350 11351 return Info->getType(); 11352 } 11353 11354 // If lookup failed 11355 if (!Info) { 11356 std::string NameForDiags = "std::"; 11357 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11358 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11359 << NameForDiags << (int)Usage; 11360 return QualType(); 11361 } 11362 11363 assert(Info->Kind == Kind); 11364 assert(Info->Record); 11365 11366 // Update the Record decl in case we encountered a forward declaration on our 11367 // first pass. FIXME: This is a bit of a hack. 11368 if (Info->Record->hasDefinition()) 11369 Info->Record = Info->Record->getDefinition(); 11370 11371 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11372 return QualType(); 11373 11374 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11375 11376 if (!Info->Record->isTriviallyCopyable()) 11377 return UnsupportedSTLError(USS_NonTrivial); 11378 11379 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11380 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11381 // Tolerate empty base classes. 11382 if (Base->isEmpty()) 11383 continue; 11384 // Reject STL implementations which have at least one non-empty base. 11385 return UnsupportedSTLError(); 11386 } 11387 11388 // Check that the STL has implemented the types using a single integer field. 11389 // This expectation allows better codegen for builtin operators. We require: 11390 // (1) The class has exactly one field. 11391 // (2) The field is an integral or enumeration type. 11392 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11393 if (std::distance(FIt, FEnd) != 1 || 11394 !FIt->getType()->isIntegralOrEnumerationType()) { 11395 return UnsupportedSTLError(); 11396 } 11397 11398 // Build each of the require values and store them in Info. 11399 for (ComparisonCategoryResult CCR : 11400 ComparisonCategories::getPossibleResultsForType(Kind)) { 11401 StringRef MemName = ComparisonCategories::getResultString(CCR); 11402 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11403 11404 if (!ValInfo) 11405 return UnsupportedSTLError(USS_MissingMember, MemName); 11406 11407 VarDecl *VD = ValInfo->VD; 11408 assert(VD && "should not be null!"); 11409 11410 // Attempt to diagnose reasons why the STL definition of this type 11411 // might be foobar, including it failing to be a constant expression. 11412 // TODO Handle more ways the lookup or result can be invalid. 11413 if (!VD->isStaticDataMember() || 11414 !VD->isUsableInConstantExpressions(Context)) 11415 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11416 11417 // Attempt to evaluate the var decl as a constant expression and extract 11418 // the value of its first field as a ICE. If this fails, the STL 11419 // implementation is not supported. 11420 if (!ValInfo->hasValidIntValue()) 11421 return UnsupportedSTLError(); 11422 11423 MarkVariableReferenced(Loc, VD); 11424 } 11425 11426 // We've successfully built the required types and expressions. Update 11427 // the cache and return the newly cached value. 11428 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11429 return Info->getType(); 11430 } 11431 11432 /// Retrieve the special "std" namespace, which may require us to 11433 /// implicitly define the namespace. 11434 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11435 if (!StdNamespace) { 11436 // The "std" namespace has not yet been defined, so build one implicitly. 11437 StdNamespace = NamespaceDecl::Create(Context, 11438 Context.getTranslationUnitDecl(), 11439 /*Inline=*/false, 11440 SourceLocation(), SourceLocation(), 11441 &PP.getIdentifierTable().get("std"), 11442 /*PrevDecl=*/nullptr); 11443 getStdNamespace()->setImplicit(true); 11444 } 11445 11446 return getStdNamespace(); 11447 } 11448 11449 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11450 assert(getLangOpts().CPlusPlus && 11451 "Looking for std::initializer_list outside of C++."); 11452 11453 // We're looking for implicit instantiations of 11454 // template <typename E> class std::initializer_list. 11455 11456 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11457 return false; 11458 11459 ClassTemplateDecl *Template = nullptr; 11460 const TemplateArgument *Arguments = nullptr; 11461 11462 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11463 11464 ClassTemplateSpecializationDecl *Specialization = 11465 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11466 if (!Specialization) 11467 return false; 11468 11469 Template = Specialization->getSpecializedTemplate(); 11470 Arguments = Specialization->getTemplateArgs().data(); 11471 } else if (const TemplateSpecializationType *TST = 11472 Ty->getAs<TemplateSpecializationType>()) { 11473 Template = dyn_cast_or_null<ClassTemplateDecl>( 11474 TST->getTemplateName().getAsTemplateDecl()); 11475 Arguments = TST->getArgs(); 11476 } 11477 if (!Template) 11478 return false; 11479 11480 if (!StdInitializerList) { 11481 // Haven't recognized std::initializer_list yet, maybe this is it. 11482 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11483 if (TemplateClass->getIdentifier() != 11484 &PP.getIdentifierTable().get("initializer_list") || 11485 !getStdNamespace()->InEnclosingNamespaceSetOf( 11486 TemplateClass->getDeclContext())) 11487 return false; 11488 // This is a template called std::initializer_list, but is it the right 11489 // template? 11490 TemplateParameterList *Params = Template->getTemplateParameters(); 11491 if (Params->getMinRequiredArguments() != 1) 11492 return false; 11493 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11494 return false; 11495 11496 // It's the right template. 11497 StdInitializerList = Template; 11498 } 11499 11500 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11501 return false; 11502 11503 // This is an instance of std::initializer_list. Find the argument type. 11504 if (Element) 11505 *Element = Arguments[0].getAsType(); 11506 return true; 11507 } 11508 11509 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11510 NamespaceDecl *Std = S.getStdNamespace(); 11511 if (!Std) { 11512 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11513 return nullptr; 11514 } 11515 11516 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11517 Loc, Sema::LookupOrdinaryName); 11518 if (!S.LookupQualifiedName(Result, Std)) { 11519 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11520 return nullptr; 11521 } 11522 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11523 if (!Template) { 11524 Result.suppressDiagnostics(); 11525 // We found something weird. Complain about the first thing we found. 11526 NamedDecl *Found = *Result.begin(); 11527 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11528 return nullptr; 11529 } 11530 11531 // We found some template called std::initializer_list. Now verify that it's 11532 // correct. 11533 TemplateParameterList *Params = Template->getTemplateParameters(); 11534 if (Params->getMinRequiredArguments() != 1 || 11535 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11536 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11537 return nullptr; 11538 } 11539 11540 return Template; 11541 } 11542 11543 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11544 if (!StdInitializerList) { 11545 StdInitializerList = LookupStdInitializerList(*this, Loc); 11546 if (!StdInitializerList) 11547 return QualType(); 11548 } 11549 11550 TemplateArgumentListInfo Args(Loc, Loc); 11551 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11552 Context.getTrivialTypeSourceInfo(Element, 11553 Loc))); 11554 return Context.getCanonicalType( 11555 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11556 } 11557 11558 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11559 // C++ [dcl.init.list]p2: 11560 // A constructor is an initializer-list constructor if its first parameter 11561 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11562 // std::initializer_list<E> for some type E, and either there are no other 11563 // parameters or else all other parameters have default arguments. 11564 if (!Ctor->hasOneParamOrDefaultArgs()) 11565 return false; 11566 11567 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11568 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11569 ArgType = RT->getPointeeType().getUnqualifiedType(); 11570 11571 return isStdInitializerList(ArgType, nullptr); 11572 } 11573 11574 /// Determine whether a using statement is in a context where it will be 11575 /// apply in all contexts. 11576 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11577 switch (CurContext->getDeclKind()) { 11578 case Decl::TranslationUnit: 11579 return true; 11580 case Decl::LinkageSpec: 11581 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11582 default: 11583 return false; 11584 } 11585 } 11586 11587 namespace { 11588 11589 // Callback to only accept typo corrections that are namespaces. 11590 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11591 public: 11592 bool ValidateCandidate(const TypoCorrection &candidate) override { 11593 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11594 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11595 return false; 11596 } 11597 11598 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11599 return std::make_unique<NamespaceValidatorCCC>(*this); 11600 } 11601 }; 11602 11603 } 11604 11605 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11606 CXXScopeSpec &SS, 11607 SourceLocation IdentLoc, 11608 IdentifierInfo *Ident) { 11609 R.clear(); 11610 NamespaceValidatorCCC CCC{}; 11611 if (TypoCorrection Corrected = 11612 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11613 Sema::CTK_ErrorRecovery)) { 11614 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11615 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11616 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11617 Ident->getName().equals(CorrectedStr); 11618 S.diagnoseTypo(Corrected, 11619 S.PDiag(diag::err_using_directive_member_suggest) 11620 << Ident << DC << DroppedSpecifier << SS.getRange(), 11621 S.PDiag(diag::note_namespace_defined_here)); 11622 } else { 11623 S.diagnoseTypo(Corrected, 11624 S.PDiag(diag::err_using_directive_suggest) << Ident, 11625 S.PDiag(diag::note_namespace_defined_here)); 11626 } 11627 R.addDecl(Corrected.getFoundDecl()); 11628 return true; 11629 } 11630 return false; 11631 } 11632 11633 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11634 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11635 SourceLocation IdentLoc, 11636 IdentifierInfo *NamespcName, 11637 const ParsedAttributesView &AttrList) { 11638 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11639 assert(NamespcName && "Invalid NamespcName."); 11640 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11641 11642 // This can only happen along a recovery path. 11643 while (S->isTemplateParamScope()) 11644 S = S->getParent(); 11645 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11646 11647 UsingDirectiveDecl *UDir = nullptr; 11648 NestedNameSpecifier *Qualifier = nullptr; 11649 if (SS.isSet()) 11650 Qualifier = SS.getScopeRep(); 11651 11652 // Lookup namespace name. 11653 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11654 LookupParsedName(R, S, &SS); 11655 if (R.isAmbiguous()) 11656 return nullptr; 11657 11658 if (R.empty()) { 11659 R.clear(); 11660 // Allow "using namespace std;" or "using namespace ::std;" even if 11661 // "std" hasn't been defined yet, for GCC compatibility. 11662 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11663 NamespcName->isStr("std")) { 11664 Diag(IdentLoc, diag::ext_using_undefined_std); 11665 R.addDecl(getOrCreateStdNamespace()); 11666 R.resolveKind(); 11667 } 11668 // Otherwise, attempt typo correction. 11669 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11670 } 11671 11672 if (!R.empty()) { 11673 NamedDecl *Named = R.getRepresentativeDecl(); 11674 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11675 assert(NS && "expected namespace decl"); 11676 11677 // The use of a nested name specifier may trigger deprecation warnings. 11678 DiagnoseUseOfDecl(Named, IdentLoc); 11679 11680 // C++ [namespace.udir]p1: 11681 // A using-directive specifies that the names in the nominated 11682 // namespace can be used in the scope in which the 11683 // using-directive appears after the using-directive. During 11684 // unqualified name lookup (3.4.1), the names appear as if they 11685 // were declared in the nearest enclosing namespace which 11686 // contains both the using-directive and the nominated 11687 // namespace. [Note: in this context, "contains" means "contains 11688 // directly or indirectly". ] 11689 11690 // Find enclosing context containing both using-directive and 11691 // nominated namespace. 11692 DeclContext *CommonAncestor = NS; 11693 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11694 CommonAncestor = CommonAncestor->getParent(); 11695 11696 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11697 SS.getWithLocInContext(Context), 11698 IdentLoc, Named, CommonAncestor); 11699 11700 if (IsUsingDirectiveInToplevelContext(CurContext) && 11701 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11702 Diag(IdentLoc, diag::warn_using_directive_in_header); 11703 } 11704 11705 PushUsingDirective(S, UDir); 11706 } else { 11707 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11708 } 11709 11710 if (UDir) 11711 ProcessDeclAttributeList(S, UDir, AttrList); 11712 11713 return UDir; 11714 } 11715 11716 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11717 // If the scope has an associated entity and the using directive is at 11718 // namespace or translation unit scope, add the UsingDirectiveDecl into 11719 // its lookup structure so qualified name lookup can find it. 11720 DeclContext *Ctx = S->getEntity(); 11721 if (Ctx && !Ctx->isFunctionOrMethod()) 11722 Ctx->addDecl(UDir); 11723 else 11724 // Otherwise, it is at block scope. The using-directives will affect lookup 11725 // only to the end of the scope. 11726 S->PushUsingDirective(UDir); 11727 } 11728 11729 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11730 SourceLocation UsingLoc, 11731 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11732 UnqualifiedId &Name, 11733 SourceLocation EllipsisLoc, 11734 const ParsedAttributesView &AttrList) { 11735 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11736 11737 if (SS.isEmpty()) { 11738 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11739 return nullptr; 11740 } 11741 11742 switch (Name.getKind()) { 11743 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11744 case UnqualifiedIdKind::IK_Identifier: 11745 case UnqualifiedIdKind::IK_OperatorFunctionId: 11746 case UnqualifiedIdKind::IK_LiteralOperatorId: 11747 case UnqualifiedIdKind::IK_ConversionFunctionId: 11748 break; 11749 11750 case UnqualifiedIdKind::IK_ConstructorName: 11751 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11752 // C++11 inheriting constructors. 11753 Diag(Name.getBeginLoc(), 11754 getLangOpts().CPlusPlus11 11755 ? diag::warn_cxx98_compat_using_decl_constructor 11756 : diag::err_using_decl_constructor) 11757 << SS.getRange(); 11758 11759 if (getLangOpts().CPlusPlus11) break; 11760 11761 return nullptr; 11762 11763 case UnqualifiedIdKind::IK_DestructorName: 11764 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11765 return nullptr; 11766 11767 case UnqualifiedIdKind::IK_TemplateId: 11768 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11769 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11770 return nullptr; 11771 11772 case UnqualifiedIdKind::IK_DeductionGuideName: 11773 llvm_unreachable("cannot parse qualified deduction guide name"); 11774 } 11775 11776 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11777 DeclarationName TargetName = TargetNameInfo.getName(); 11778 if (!TargetName) 11779 return nullptr; 11780 11781 // Warn about access declarations. 11782 if (UsingLoc.isInvalid()) { 11783 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11784 ? diag::err_access_decl 11785 : diag::warn_access_decl_deprecated) 11786 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11787 } 11788 11789 if (EllipsisLoc.isInvalid()) { 11790 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11791 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11792 return nullptr; 11793 } else { 11794 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11795 !TargetNameInfo.containsUnexpandedParameterPack()) { 11796 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11797 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11798 EllipsisLoc = SourceLocation(); 11799 } 11800 } 11801 11802 NamedDecl *UD = 11803 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11804 SS, TargetNameInfo, EllipsisLoc, AttrList, 11805 /*IsInstantiation*/ false, 11806 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11807 if (UD) 11808 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11809 11810 return UD; 11811 } 11812 11813 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11814 SourceLocation UsingLoc, 11815 SourceLocation EnumLoc, 11816 const DeclSpec &DS) { 11817 switch (DS.getTypeSpecType()) { 11818 case DeclSpec::TST_error: 11819 // This will already have been diagnosed 11820 return nullptr; 11821 11822 case DeclSpec::TST_enum: 11823 break; 11824 11825 case DeclSpec::TST_typename: 11826 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11827 return nullptr; 11828 11829 default: 11830 llvm_unreachable("unexpected DeclSpec type"); 11831 } 11832 11833 // As with enum-decls, we ignore attributes for now. 11834 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11835 if (auto *Def = Enum->getDefinition()) 11836 Enum = Def; 11837 11838 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11839 DS.getTypeSpecTypeNameLoc(), Enum); 11840 if (UD) 11841 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11842 11843 return UD; 11844 } 11845 11846 /// Determine whether a using declaration considers the given 11847 /// declarations as "equivalent", e.g., if they are redeclarations of 11848 /// the same entity or are both typedefs of the same type. 11849 static bool 11850 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11851 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11852 return true; 11853 11854 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11855 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11856 return Context.hasSameType(TD1->getUnderlyingType(), 11857 TD2->getUnderlyingType()); 11858 11859 // Two using_if_exists using-declarations are equivalent if both are 11860 // unresolved. 11861 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11862 isa<UnresolvedUsingIfExistsDecl>(D2)) 11863 return true; 11864 11865 return false; 11866 } 11867 11868 11869 /// Determines whether to create a using shadow decl for a particular 11870 /// decl, given the set of decls existing prior to this using lookup. 11871 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11872 const LookupResult &Previous, 11873 UsingShadowDecl *&PrevShadow) { 11874 // Diagnose finding a decl which is not from a base class of the 11875 // current class. We do this now because there are cases where this 11876 // function will silently decide not to build a shadow decl, which 11877 // will pre-empt further diagnostics. 11878 // 11879 // We don't need to do this in C++11 because we do the check once on 11880 // the qualifier. 11881 // 11882 // FIXME: diagnose the following if we care enough: 11883 // struct A { int foo; }; 11884 // struct B : A { using A::foo; }; 11885 // template <class T> struct C : A {}; 11886 // template <class T> struct D : C<T> { using B::foo; } // <--- 11887 // This is invalid (during instantiation) in C++03 because B::foo 11888 // resolves to the using decl in B, which is not a base class of D<T>. 11889 // We can't diagnose it immediately because C<T> is an unknown 11890 // specialization. The UsingShadowDecl in D<T> then points directly 11891 // to A::foo, which will look well-formed when we instantiate. 11892 // The right solution is to not collapse the shadow-decl chain. 11893 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11894 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11895 DeclContext *OrigDC = Orig->getDeclContext(); 11896 11897 // Handle enums and anonymous structs. 11898 if (isa<EnumDecl>(OrigDC)) 11899 OrigDC = OrigDC->getParent(); 11900 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11901 while (OrigRec->isAnonymousStructOrUnion()) 11902 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11903 11904 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11905 if (OrigDC == CurContext) { 11906 Diag(Using->getLocation(), 11907 diag::err_using_decl_nested_name_specifier_is_current_class) 11908 << Using->getQualifierLoc().getSourceRange(); 11909 Diag(Orig->getLocation(), diag::note_using_decl_target); 11910 Using->setInvalidDecl(); 11911 return true; 11912 } 11913 11914 Diag(Using->getQualifierLoc().getBeginLoc(), 11915 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11916 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11917 << Using->getQualifierLoc().getSourceRange(); 11918 Diag(Orig->getLocation(), diag::note_using_decl_target); 11919 Using->setInvalidDecl(); 11920 return true; 11921 } 11922 } 11923 11924 if (Previous.empty()) return false; 11925 11926 NamedDecl *Target = Orig; 11927 if (isa<UsingShadowDecl>(Target)) 11928 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11929 11930 // If the target happens to be one of the previous declarations, we 11931 // don't have a conflict. 11932 // 11933 // FIXME: but we might be increasing its access, in which case we 11934 // should redeclare it. 11935 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11936 bool FoundEquivalentDecl = false; 11937 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11938 I != E; ++I) { 11939 NamedDecl *D = (*I)->getUnderlyingDecl(); 11940 // We can have UsingDecls in our Previous results because we use the same 11941 // LookupResult for checking whether the UsingDecl itself is a valid 11942 // redeclaration. 11943 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11944 continue; 11945 11946 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11947 // C++ [class.mem]p19: 11948 // If T is the name of a class, then [every named member other than 11949 // a non-static data member] shall have a name different from T 11950 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11951 !isa<IndirectFieldDecl>(Target) && 11952 !isa<UnresolvedUsingValueDecl>(Target) && 11953 DiagnoseClassNameShadow( 11954 CurContext, 11955 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11956 return true; 11957 } 11958 11959 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11960 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11961 PrevShadow = Shadow; 11962 FoundEquivalentDecl = true; 11963 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11964 // We don't conflict with an existing using shadow decl of an equivalent 11965 // declaration, but we're not a redeclaration of it. 11966 FoundEquivalentDecl = true; 11967 } 11968 11969 if (isVisible(D)) 11970 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11971 } 11972 11973 if (FoundEquivalentDecl) 11974 return false; 11975 11976 // Always emit a diagnostic for a mismatch between an unresolved 11977 // using_if_exists and a resolved using declaration in either direction. 11978 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11979 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11980 if (!NonTag && !Tag) 11981 return false; 11982 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11983 Diag(Target->getLocation(), diag::note_using_decl_target); 11984 Diag((NonTag ? NonTag : Tag)->getLocation(), 11985 diag::note_using_decl_conflict); 11986 BUD->setInvalidDecl(); 11987 return true; 11988 } 11989 11990 if (FunctionDecl *FD = Target->getAsFunction()) { 11991 NamedDecl *OldDecl = nullptr; 11992 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11993 /*IsForUsingDecl*/ true)) { 11994 case Ovl_Overload: 11995 return false; 11996 11997 case Ovl_NonFunction: 11998 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11999 break; 12000 12001 // We found a decl with the exact signature. 12002 case Ovl_Match: 12003 // If we're in a record, we want to hide the target, so we 12004 // return true (without a diagnostic) to tell the caller not to 12005 // build a shadow decl. 12006 if (CurContext->isRecord()) 12007 return true; 12008 12009 // If we're not in a record, this is an error. 12010 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12011 break; 12012 } 12013 12014 Diag(Target->getLocation(), diag::note_using_decl_target); 12015 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 12016 BUD->setInvalidDecl(); 12017 return true; 12018 } 12019 12020 // Target is not a function. 12021 12022 if (isa<TagDecl>(Target)) { 12023 // No conflict between a tag and a non-tag. 12024 if (!Tag) return false; 12025 12026 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12027 Diag(Target->getLocation(), diag::note_using_decl_target); 12028 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 12029 BUD->setInvalidDecl(); 12030 return true; 12031 } 12032 12033 // No conflict between a tag and a non-tag. 12034 if (!NonTag) return false; 12035 12036 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12037 Diag(Target->getLocation(), diag::note_using_decl_target); 12038 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 12039 BUD->setInvalidDecl(); 12040 return true; 12041 } 12042 12043 /// Determine whether a direct base class is a virtual base class. 12044 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 12045 if (!Derived->getNumVBases()) 12046 return false; 12047 for (auto &B : Derived->bases()) 12048 if (B.getType()->getAsCXXRecordDecl() == Base) 12049 return B.isVirtual(); 12050 llvm_unreachable("not a direct base class"); 12051 } 12052 12053 /// Builds a shadow declaration corresponding to a 'using' declaration. 12054 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 12055 NamedDecl *Orig, 12056 UsingShadowDecl *PrevDecl) { 12057 // If we resolved to another shadow declaration, just coalesce them. 12058 NamedDecl *Target = Orig; 12059 if (isa<UsingShadowDecl>(Target)) { 12060 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 12061 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 12062 } 12063 12064 NamedDecl *NonTemplateTarget = Target; 12065 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 12066 NonTemplateTarget = TargetTD->getTemplatedDecl(); 12067 12068 UsingShadowDecl *Shadow; 12069 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 12070 UsingDecl *Using = cast<UsingDecl>(BUD); 12071 bool IsVirtualBase = 12072 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 12073 Using->getQualifier()->getAsRecordDecl()); 12074 Shadow = ConstructorUsingShadowDecl::Create( 12075 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 12076 } else { 12077 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 12078 Target->getDeclName(), BUD, Target); 12079 } 12080 BUD->addShadowDecl(Shadow); 12081 12082 Shadow->setAccess(BUD->getAccess()); 12083 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 12084 Shadow->setInvalidDecl(); 12085 12086 Shadow->setPreviousDecl(PrevDecl); 12087 12088 if (S) 12089 PushOnScopeChains(Shadow, S); 12090 else 12091 CurContext->addDecl(Shadow); 12092 12093 12094 return Shadow; 12095 } 12096 12097 /// Hides a using shadow declaration. This is required by the current 12098 /// using-decl implementation when a resolvable using declaration in a 12099 /// class is followed by a declaration which would hide or override 12100 /// one or more of the using decl's targets; for example: 12101 /// 12102 /// struct Base { void foo(int); }; 12103 /// struct Derived : Base { 12104 /// using Base::foo; 12105 /// void foo(int); 12106 /// }; 12107 /// 12108 /// The governing language is C++03 [namespace.udecl]p12: 12109 /// 12110 /// When a using-declaration brings names from a base class into a 12111 /// derived class scope, member functions in the derived class 12112 /// override and/or hide member functions with the same name and 12113 /// parameter types in a base class (rather than conflicting). 12114 /// 12115 /// There are two ways to implement this: 12116 /// (1) optimistically create shadow decls when they're not hidden 12117 /// by existing declarations, or 12118 /// (2) don't create any shadow decls (or at least don't make them 12119 /// visible) until we've fully parsed/instantiated the class. 12120 /// The problem with (1) is that we might have to retroactively remove 12121 /// a shadow decl, which requires several O(n) operations because the 12122 /// decl structures are (very reasonably) not designed for removal. 12123 /// (2) avoids this but is very fiddly and phase-dependent. 12124 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12125 if (Shadow->getDeclName().getNameKind() == 12126 DeclarationName::CXXConversionFunctionName) 12127 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12128 12129 // Remove it from the DeclContext... 12130 Shadow->getDeclContext()->removeDecl(Shadow); 12131 12132 // ...and the scope, if applicable... 12133 if (S) { 12134 S->RemoveDecl(Shadow); 12135 IdResolver.RemoveDecl(Shadow); 12136 } 12137 12138 // ...and the using decl. 12139 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12140 12141 // TODO: complain somehow if Shadow was used. It shouldn't 12142 // be possible for this to happen, because...? 12143 } 12144 12145 /// Find the base specifier for a base class with the given type. 12146 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12147 QualType DesiredBase, 12148 bool &AnyDependentBases) { 12149 // Check whether the named type is a direct base class. 12150 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12151 .getUnqualifiedType(); 12152 for (auto &Base : Derived->bases()) { 12153 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12154 if (CanonicalDesiredBase == BaseType) 12155 return &Base; 12156 if (BaseType->isDependentType()) 12157 AnyDependentBases = true; 12158 } 12159 return nullptr; 12160 } 12161 12162 namespace { 12163 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12164 public: 12165 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12166 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12167 : HasTypenameKeyword(HasTypenameKeyword), 12168 IsInstantiation(IsInstantiation), OldNNS(NNS), 12169 RequireMemberOf(RequireMemberOf) {} 12170 12171 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12172 NamedDecl *ND = Candidate.getCorrectionDecl(); 12173 12174 // Keywords are not valid here. 12175 if (!ND || isa<NamespaceDecl>(ND)) 12176 return false; 12177 12178 // Completely unqualified names are invalid for a 'using' declaration. 12179 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12180 return false; 12181 12182 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12183 // reject. 12184 12185 if (RequireMemberOf) { 12186 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12187 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12188 // No-one ever wants a using-declaration to name an injected-class-name 12189 // of a base class, unless they're declaring an inheriting constructor. 12190 ASTContext &Ctx = ND->getASTContext(); 12191 if (!Ctx.getLangOpts().CPlusPlus11) 12192 return false; 12193 QualType FoundType = Ctx.getRecordType(FoundRecord); 12194 12195 // Check that the injected-class-name is named as a member of its own 12196 // type; we don't want to suggest 'using Derived::Base;', since that 12197 // means something else. 12198 NestedNameSpecifier *Specifier = 12199 Candidate.WillReplaceSpecifier() 12200 ? Candidate.getCorrectionSpecifier() 12201 : OldNNS; 12202 if (!Specifier->getAsType() || 12203 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12204 return false; 12205 12206 // Check that this inheriting constructor declaration actually names a 12207 // direct base class of the current class. 12208 bool AnyDependentBases = false; 12209 if (!findDirectBaseWithType(RequireMemberOf, 12210 Ctx.getRecordType(FoundRecord), 12211 AnyDependentBases) && 12212 !AnyDependentBases) 12213 return false; 12214 } else { 12215 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12216 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12217 return false; 12218 12219 // FIXME: Check that the base class member is accessible? 12220 } 12221 } else { 12222 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12223 if (FoundRecord && FoundRecord->isInjectedClassName()) 12224 return false; 12225 } 12226 12227 if (isa<TypeDecl>(ND)) 12228 return HasTypenameKeyword || !IsInstantiation; 12229 12230 return !HasTypenameKeyword; 12231 } 12232 12233 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12234 return std::make_unique<UsingValidatorCCC>(*this); 12235 } 12236 12237 private: 12238 bool HasTypenameKeyword; 12239 bool IsInstantiation; 12240 NestedNameSpecifier *OldNNS; 12241 CXXRecordDecl *RequireMemberOf; 12242 }; 12243 } // end anonymous namespace 12244 12245 /// Remove decls we can't actually see from a lookup being used to declare 12246 /// shadow using decls. 12247 /// 12248 /// \param S - The scope of the potential shadow decl 12249 /// \param Previous - The lookup of a potential shadow decl's name. 12250 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12251 // It is really dumb that we have to do this. 12252 LookupResult::Filter F = Previous.makeFilter(); 12253 while (F.hasNext()) { 12254 NamedDecl *D = F.next(); 12255 if (!isDeclInScope(D, CurContext, S)) 12256 F.erase(); 12257 // If we found a local extern declaration that's not ordinarily visible, 12258 // and this declaration is being added to a non-block scope, ignore it. 12259 // We're only checking for scope conflicts here, not also for violations 12260 // of the linkage rules. 12261 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12262 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12263 F.erase(); 12264 } 12265 F.done(); 12266 } 12267 12268 /// Builds a using declaration. 12269 /// 12270 /// \param IsInstantiation - Whether this call arises from an 12271 /// instantiation of an unresolved using declaration. We treat 12272 /// the lookup differently for these declarations. 12273 NamedDecl *Sema::BuildUsingDeclaration( 12274 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12275 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12276 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12277 const ParsedAttributesView &AttrList, bool IsInstantiation, 12278 bool IsUsingIfExists) { 12279 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12280 SourceLocation IdentLoc = NameInfo.getLoc(); 12281 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12282 12283 // FIXME: We ignore attributes for now. 12284 12285 // For an inheriting constructor declaration, the name of the using 12286 // declaration is the name of a constructor in this class, not in the 12287 // base class. 12288 DeclarationNameInfo UsingName = NameInfo; 12289 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12290 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12291 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12292 Context.getCanonicalType(Context.getRecordType(RD)))); 12293 12294 // Do the redeclaration lookup in the current scope. 12295 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12296 ForVisibleRedeclaration); 12297 Previous.setHideTags(false); 12298 if (S) { 12299 LookupName(Previous, S); 12300 12301 FilterUsingLookup(S, Previous); 12302 } else { 12303 assert(IsInstantiation && "no scope in non-instantiation"); 12304 if (CurContext->isRecord()) 12305 LookupQualifiedName(Previous, CurContext); 12306 else { 12307 // No redeclaration check is needed here; in non-member contexts we 12308 // diagnosed all possible conflicts with other using-declarations when 12309 // building the template: 12310 // 12311 // For a dependent non-type using declaration, the only valid case is 12312 // if we instantiate to a single enumerator. We check for conflicts 12313 // between shadow declarations we introduce, and we check in the template 12314 // definition for conflicts between a non-type using declaration and any 12315 // other declaration, which together covers all cases. 12316 // 12317 // A dependent typename using declaration will never successfully 12318 // instantiate, since it will always name a class member, so we reject 12319 // that in the template definition. 12320 } 12321 } 12322 12323 // Check for invalid redeclarations. 12324 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12325 SS, IdentLoc, Previous)) 12326 return nullptr; 12327 12328 // 'using_if_exists' doesn't make sense on an inherited constructor. 12329 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12330 DeclarationName::CXXConstructorName) { 12331 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12332 return nullptr; 12333 } 12334 12335 DeclContext *LookupContext = computeDeclContext(SS); 12336 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12337 if (!LookupContext || EllipsisLoc.isValid()) { 12338 NamedDecl *D; 12339 // Dependent scope, or an unexpanded pack 12340 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12341 SS, NameInfo, IdentLoc)) 12342 return nullptr; 12343 12344 if (HasTypenameKeyword) { 12345 // FIXME: not all declaration name kinds are legal here 12346 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12347 UsingLoc, TypenameLoc, 12348 QualifierLoc, 12349 IdentLoc, NameInfo.getName(), 12350 EllipsisLoc); 12351 } else { 12352 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12353 QualifierLoc, NameInfo, EllipsisLoc); 12354 } 12355 D->setAccess(AS); 12356 CurContext->addDecl(D); 12357 ProcessDeclAttributeList(S, D, AttrList); 12358 return D; 12359 } 12360 12361 auto Build = [&](bool Invalid) { 12362 UsingDecl *UD = 12363 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12364 UsingName, HasTypenameKeyword); 12365 UD->setAccess(AS); 12366 CurContext->addDecl(UD); 12367 ProcessDeclAttributeList(S, UD, AttrList); 12368 UD->setInvalidDecl(Invalid); 12369 return UD; 12370 }; 12371 auto BuildInvalid = [&]{ return Build(true); }; 12372 auto BuildValid = [&]{ return Build(false); }; 12373 12374 if (RequireCompleteDeclContext(SS, LookupContext)) 12375 return BuildInvalid(); 12376 12377 // Look up the target name. 12378 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12379 12380 // Unlike most lookups, we don't always want to hide tag 12381 // declarations: tag names are visible through the using declaration 12382 // even if hidden by ordinary names, *except* in a dependent context 12383 // where they may be used by two-phase lookup. 12384 if (!IsInstantiation) 12385 R.setHideTags(false); 12386 12387 // For the purposes of this lookup, we have a base object type 12388 // equal to that of the current context. 12389 if (CurContext->isRecord()) { 12390 R.setBaseObjectType( 12391 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12392 } 12393 12394 LookupQualifiedName(R, LookupContext); 12395 12396 // Validate the context, now we have a lookup 12397 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12398 IdentLoc, &R)) 12399 return nullptr; 12400 12401 if (R.empty() && IsUsingIfExists) 12402 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12403 UsingName.getName()), 12404 AS_public); 12405 12406 // Try to correct typos if possible. If constructor name lookup finds no 12407 // results, that means the named class has no explicit constructors, and we 12408 // suppressed declaring implicit ones (probably because it's dependent or 12409 // invalid). 12410 if (R.empty() && 12411 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12412 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12413 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12414 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12415 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12416 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12417 CurContext->isStdNamespace() && 12418 isa<TranslationUnitDecl>(LookupContext) && 12419 getSourceManager().isInSystemHeader(UsingLoc)) 12420 return nullptr; 12421 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12422 dyn_cast<CXXRecordDecl>(CurContext)); 12423 if (TypoCorrection Corrected = 12424 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12425 CTK_ErrorRecovery)) { 12426 // We reject candidates where DroppedSpecifier == true, hence the 12427 // literal '0' below. 12428 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12429 << NameInfo.getName() << LookupContext << 0 12430 << SS.getRange()); 12431 12432 // If we picked a correction with no attached Decl we can't do anything 12433 // useful with it, bail out. 12434 NamedDecl *ND = Corrected.getCorrectionDecl(); 12435 if (!ND) 12436 return BuildInvalid(); 12437 12438 // If we corrected to an inheriting constructor, handle it as one. 12439 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12440 if (RD && RD->isInjectedClassName()) { 12441 // The parent of the injected class name is the class itself. 12442 RD = cast<CXXRecordDecl>(RD->getParent()); 12443 12444 // Fix up the information we'll use to build the using declaration. 12445 if (Corrected.WillReplaceSpecifier()) { 12446 NestedNameSpecifierLocBuilder Builder; 12447 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12448 QualifierLoc.getSourceRange()); 12449 QualifierLoc = Builder.getWithLocInContext(Context); 12450 } 12451 12452 // In this case, the name we introduce is the name of a derived class 12453 // constructor. 12454 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12455 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12456 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12457 UsingName.setNamedTypeInfo(nullptr); 12458 for (auto *Ctor : LookupConstructors(RD)) 12459 R.addDecl(Ctor); 12460 R.resolveKind(); 12461 } else { 12462 // FIXME: Pick up all the declarations if we found an overloaded 12463 // function. 12464 UsingName.setName(ND->getDeclName()); 12465 R.addDecl(ND); 12466 } 12467 } else { 12468 Diag(IdentLoc, diag::err_no_member) 12469 << NameInfo.getName() << LookupContext << SS.getRange(); 12470 return BuildInvalid(); 12471 } 12472 } 12473 12474 if (R.isAmbiguous()) 12475 return BuildInvalid(); 12476 12477 if (HasTypenameKeyword) { 12478 // If we asked for a typename and got a non-type decl, error out. 12479 if (!R.getAsSingle<TypeDecl>() && 12480 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12481 Diag(IdentLoc, diag::err_using_typename_non_type); 12482 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12483 Diag((*I)->getUnderlyingDecl()->getLocation(), 12484 diag::note_using_decl_target); 12485 return BuildInvalid(); 12486 } 12487 } else { 12488 // If we asked for a non-typename and we got a type, error out, 12489 // but only if this is an instantiation of an unresolved using 12490 // decl. Otherwise just silently find the type name. 12491 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12492 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12493 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12494 return BuildInvalid(); 12495 } 12496 } 12497 12498 // C++14 [namespace.udecl]p6: 12499 // A using-declaration shall not name a namespace. 12500 if (R.getAsSingle<NamespaceDecl>()) { 12501 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12502 << SS.getRange(); 12503 return BuildInvalid(); 12504 } 12505 12506 UsingDecl *UD = BuildValid(); 12507 12508 // Some additional rules apply to inheriting constructors. 12509 if (UsingName.getName().getNameKind() == 12510 DeclarationName::CXXConstructorName) { 12511 // Suppress access diagnostics; the access check is instead performed at the 12512 // point of use for an inheriting constructor. 12513 R.suppressDiagnostics(); 12514 if (CheckInheritingConstructorUsingDecl(UD)) 12515 return UD; 12516 } 12517 12518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12519 UsingShadowDecl *PrevDecl = nullptr; 12520 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12521 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12522 } 12523 12524 return UD; 12525 } 12526 12527 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12528 SourceLocation UsingLoc, 12529 SourceLocation EnumLoc, 12530 SourceLocation NameLoc, 12531 EnumDecl *ED) { 12532 bool Invalid = false; 12533 12534 if (CurContext->getRedeclContext()->isRecord()) { 12535 /// In class scope, check if this is a duplicate, for better a diagnostic. 12536 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12537 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12538 ForVisibleRedeclaration); 12539 12540 LookupName(Previous, S); 12541 12542 for (NamedDecl *D : Previous) 12543 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12544 if (UED->getEnumDecl() == ED) { 12545 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12546 << SourceRange(EnumLoc, NameLoc); 12547 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12548 Invalid = true; 12549 break; 12550 } 12551 } 12552 12553 if (RequireCompleteEnumDecl(ED, NameLoc)) 12554 Invalid = true; 12555 12556 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12557 EnumLoc, NameLoc, ED); 12558 UD->setAccess(AS); 12559 CurContext->addDecl(UD); 12560 12561 if (Invalid) { 12562 UD->setInvalidDecl(); 12563 return UD; 12564 } 12565 12566 // Create the shadow decls for each enumerator 12567 for (EnumConstantDecl *EC : ED->enumerators()) { 12568 UsingShadowDecl *PrevDecl = nullptr; 12569 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12570 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12571 ForVisibleRedeclaration); 12572 LookupName(Previous, S); 12573 FilterUsingLookup(S, Previous); 12574 12575 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12576 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12577 } 12578 12579 return UD; 12580 } 12581 12582 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12583 ArrayRef<NamedDecl *> Expansions) { 12584 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12585 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12586 isa<UsingPackDecl>(InstantiatedFrom)); 12587 12588 auto *UPD = 12589 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12590 UPD->setAccess(InstantiatedFrom->getAccess()); 12591 CurContext->addDecl(UPD); 12592 return UPD; 12593 } 12594 12595 /// Additional checks for a using declaration referring to a constructor name. 12596 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12597 assert(!UD->hasTypename() && "expecting a constructor name"); 12598 12599 const Type *SourceType = UD->getQualifier()->getAsType(); 12600 assert(SourceType && 12601 "Using decl naming constructor doesn't have type in scope spec."); 12602 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12603 12604 // Check whether the named type is a direct base class. 12605 bool AnyDependentBases = false; 12606 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12607 AnyDependentBases); 12608 if (!Base && !AnyDependentBases) { 12609 Diag(UD->getUsingLoc(), 12610 diag::err_using_decl_constructor_not_in_direct_base) 12611 << UD->getNameInfo().getSourceRange() 12612 << QualType(SourceType, 0) << TargetClass; 12613 UD->setInvalidDecl(); 12614 return true; 12615 } 12616 12617 if (Base) 12618 Base->setInheritConstructors(); 12619 12620 return false; 12621 } 12622 12623 /// Checks that the given using declaration is not an invalid 12624 /// redeclaration. Note that this is checking only for the using decl 12625 /// itself, not for any ill-formedness among the UsingShadowDecls. 12626 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12627 bool HasTypenameKeyword, 12628 const CXXScopeSpec &SS, 12629 SourceLocation NameLoc, 12630 const LookupResult &Prev) { 12631 NestedNameSpecifier *Qual = SS.getScopeRep(); 12632 12633 // C++03 [namespace.udecl]p8: 12634 // C++0x [namespace.udecl]p10: 12635 // A using-declaration is a declaration and can therefore be used 12636 // repeatedly where (and only where) multiple declarations are 12637 // allowed. 12638 // 12639 // That's in non-member contexts. 12640 if (!CurContext->getRedeclContext()->isRecord()) { 12641 // A dependent qualifier outside a class can only ever resolve to an 12642 // enumeration type. Therefore it conflicts with any other non-type 12643 // declaration in the same scope. 12644 // FIXME: How should we check for dependent type-type conflicts at block 12645 // scope? 12646 if (Qual->isDependent() && !HasTypenameKeyword) { 12647 for (auto *D : Prev) { 12648 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12649 bool OldCouldBeEnumerator = 12650 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12651 Diag(NameLoc, 12652 OldCouldBeEnumerator ? diag::err_redefinition 12653 : diag::err_redefinition_different_kind) 12654 << Prev.getLookupName(); 12655 Diag(D->getLocation(), diag::note_previous_definition); 12656 return true; 12657 } 12658 } 12659 } 12660 return false; 12661 } 12662 12663 const NestedNameSpecifier *CNNS = 12664 Context.getCanonicalNestedNameSpecifier(Qual); 12665 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12666 NamedDecl *D = *I; 12667 12668 bool DTypename; 12669 NestedNameSpecifier *DQual; 12670 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12671 DTypename = UD->hasTypename(); 12672 DQual = UD->getQualifier(); 12673 } else if (UnresolvedUsingValueDecl *UD 12674 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12675 DTypename = false; 12676 DQual = UD->getQualifier(); 12677 } else if (UnresolvedUsingTypenameDecl *UD 12678 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12679 DTypename = true; 12680 DQual = UD->getQualifier(); 12681 } else continue; 12682 12683 // using decls differ if one says 'typename' and the other doesn't. 12684 // FIXME: non-dependent using decls? 12685 if (HasTypenameKeyword != DTypename) continue; 12686 12687 // using decls differ if they name different scopes (but note that 12688 // template instantiation can cause this check to trigger when it 12689 // didn't before instantiation). 12690 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12691 continue; 12692 12693 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12694 Diag(D->getLocation(), diag::note_using_decl) << 1; 12695 return true; 12696 } 12697 12698 return false; 12699 } 12700 12701 /// Checks that the given nested-name qualifier used in a using decl 12702 /// in the current context is appropriately related to the current 12703 /// scope. If an error is found, diagnoses it and returns true. 12704 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12705 /// result of that lookup. UD is likewise nullptr, except when we have an 12706 /// already-populated UsingDecl whose shadow decls contain the same information 12707 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12708 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12709 const CXXScopeSpec &SS, 12710 const DeclarationNameInfo &NameInfo, 12711 SourceLocation NameLoc, 12712 const LookupResult *R, const UsingDecl *UD) { 12713 DeclContext *NamedContext = computeDeclContext(SS); 12714 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12715 "resolvable context must have exactly one set of decls"); 12716 12717 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12718 // relationship. 12719 bool Cxx20Enumerator = false; 12720 if (NamedContext) { 12721 EnumConstantDecl *EC = nullptr; 12722 if (R) 12723 EC = R->getAsSingle<EnumConstantDecl>(); 12724 else if (UD && UD->shadow_size() == 1) 12725 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12726 if (EC) 12727 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12728 12729 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12730 // C++14 [namespace.udecl]p7: 12731 // A using-declaration shall not name a scoped enumerator. 12732 // C++20 p1099 permits enumerators. 12733 if (EC && R && ED->isScoped()) 12734 Diag(SS.getBeginLoc(), 12735 getLangOpts().CPlusPlus20 12736 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12737 : diag::ext_using_decl_scoped_enumerator) 12738 << SS.getRange(); 12739 12740 // We want to consider the scope of the enumerator 12741 NamedContext = ED->getDeclContext(); 12742 } 12743 } 12744 12745 if (!CurContext->isRecord()) { 12746 // C++03 [namespace.udecl]p3: 12747 // C++0x [namespace.udecl]p8: 12748 // A using-declaration for a class member shall be a member-declaration. 12749 // C++20 [namespace.udecl]p7 12750 // ... other than an enumerator ... 12751 12752 // If we weren't able to compute a valid scope, it might validly be a 12753 // dependent class or enumeration scope. If we have a 'typename' keyword, 12754 // the scope must resolve to a class type. 12755 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12756 : !HasTypename) 12757 return false; // OK 12758 12759 Diag(NameLoc, 12760 Cxx20Enumerator 12761 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12762 : diag::err_using_decl_can_not_refer_to_class_member) 12763 << SS.getRange(); 12764 12765 if (Cxx20Enumerator) 12766 return false; // OK 12767 12768 auto *RD = NamedContext 12769 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12770 : nullptr; 12771 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12772 // See if there's a helpful fixit 12773 12774 if (!R) { 12775 // We will have already diagnosed the problem on the template 12776 // definition, Maybe we should do so again? 12777 } else if (R->getAsSingle<TypeDecl>()) { 12778 if (getLangOpts().CPlusPlus11) { 12779 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12780 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12781 << 0 // alias declaration 12782 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12783 NameInfo.getName().getAsString() + 12784 " = "); 12785 } else { 12786 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12787 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12788 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12789 << 1 // typedef declaration 12790 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12791 << FixItHint::CreateInsertion( 12792 InsertLoc, " " + NameInfo.getName().getAsString()); 12793 } 12794 } else if (R->getAsSingle<VarDecl>()) { 12795 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12796 // repeating the type of the static data member here. 12797 FixItHint FixIt; 12798 if (getLangOpts().CPlusPlus11) { 12799 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12800 FixIt = FixItHint::CreateReplacement( 12801 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12802 } 12803 12804 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12805 << 2 // reference declaration 12806 << FixIt; 12807 } else if (R->getAsSingle<EnumConstantDecl>()) { 12808 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12809 // repeating the type of the enumeration here, and we can't do so if 12810 // the type is anonymous. 12811 FixItHint FixIt; 12812 if (getLangOpts().CPlusPlus11) { 12813 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12814 FixIt = FixItHint::CreateReplacement( 12815 UsingLoc, 12816 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12817 } 12818 12819 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12820 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12821 << FixIt; 12822 } 12823 } 12824 12825 return true; // Fail 12826 } 12827 12828 // If the named context is dependent, we can't decide much. 12829 if (!NamedContext) { 12830 // FIXME: in C++0x, we can diagnose if we can prove that the 12831 // nested-name-specifier does not refer to a base class, which is 12832 // still possible in some cases. 12833 12834 // Otherwise we have to conservatively report that things might be 12835 // okay. 12836 return false; 12837 } 12838 12839 // The current scope is a record. 12840 if (!NamedContext->isRecord()) { 12841 // Ideally this would point at the last name in the specifier, 12842 // but we don't have that level of source info. 12843 Diag(SS.getBeginLoc(), 12844 Cxx20Enumerator 12845 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12846 : diag::err_using_decl_nested_name_specifier_is_not_class) 12847 << SS.getScopeRep() << SS.getRange(); 12848 12849 if (Cxx20Enumerator) 12850 return false; // OK 12851 12852 return true; 12853 } 12854 12855 if (!NamedContext->isDependentContext() && 12856 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12857 return true; 12858 12859 if (getLangOpts().CPlusPlus11) { 12860 // C++11 [namespace.udecl]p3: 12861 // In a using-declaration used as a member-declaration, the 12862 // nested-name-specifier shall name a base class of the class 12863 // being defined. 12864 12865 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12866 cast<CXXRecordDecl>(NamedContext))) { 12867 12868 if (Cxx20Enumerator) { 12869 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12870 << SS.getRange(); 12871 return false; 12872 } 12873 12874 if (CurContext == NamedContext) { 12875 Diag(SS.getBeginLoc(), 12876 diag::err_using_decl_nested_name_specifier_is_current_class) 12877 << SS.getRange(); 12878 return !getLangOpts().CPlusPlus20; 12879 } 12880 12881 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12882 Diag(SS.getBeginLoc(), 12883 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12884 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12885 << SS.getRange(); 12886 } 12887 return true; 12888 } 12889 12890 return false; 12891 } 12892 12893 // C++03 [namespace.udecl]p4: 12894 // A using-declaration used as a member-declaration shall refer 12895 // to a member of a base class of the class being defined [etc.]. 12896 12897 // Salient point: SS doesn't have to name a base class as long as 12898 // lookup only finds members from base classes. Therefore we can 12899 // diagnose here only if we can prove that that can't happen, 12900 // i.e. if the class hierarchies provably don't intersect. 12901 12902 // TODO: it would be nice if "definitely valid" results were cached 12903 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12904 // need to be repeated. 12905 12906 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12907 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12908 Bases.insert(Base); 12909 return true; 12910 }; 12911 12912 // Collect all bases. Return false if we find a dependent base. 12913 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12914 return false; 12915 12916 // Returns true if the base is dependent or is one of the accumulated base 12917 // classes. 12918 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12919 return !Bases.count(Base); 12920 }; 12921 12922 // Return false if the class has a dependent base or if it or one 12923 // of its bases is present in the base set of the current context. 12924 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12925 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12926 return false; 12927 12928 Diag(SS.getRange().getBegin(), 12929 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12930 << SS.getScopeRep() 12931 << cast<CXXRecordDecl>(CurContext) 12932 << SS.getRange(); 12933 12934 return true; 12935 } 12936 12937 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12938 MultiTemplateParamsArg TemplateParamLists, 12939 SourceLocation UsingLoc, UnqualifiedId &Name, 12940 const ParsedAttributesView &AttrList, 12941 TypeResult Type, Decl *DeclFromDeclSpec) { 12942 // Skip up to the relevant declaration scope. 12943 while (S->isTemplateParamScope()) 12944 S = S->getParent(); 12945 assert((S->getFlags() & Scope::DeclScope) && 12946 "got alias-declaration outside of declaration scope"); 12947 12948 if (Type.isInvalid()) 12949 return nullptr; 12950 12951 bool Invalid = false; 12952 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12953 TypeSourceInfo *TInfo = nullptr; 12954 GetTypeFromParser(Type.get(), &TInfo); 12955 12956 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12957 return nullptr; 12958 12959 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12960 UPPC_DeclarationType)) { 12961 Invalid = true; 12962 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12963 TInfo->getTypeLoc().getBeginLoc()); 12964 } 12965 12966 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12967 TemplateParamLists.size() 12968 ? forRedeclarationInCurContext() 12969 : ForVisibleRedeclaration); 12970 LookupName(Previous, S); 12971 12972 // Warn about shadowing the name of a template parameter. 12973 if (Previous.isSingleResult() && 12974 Previous.getFoundDecl()->isTemplateParameter()) { 12975 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12976 Previous.clear(); 12977 } 12978 12979 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12980 "name in alias declaration must be an identifier"); 12981 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12982 Name.StartLocation, 12983 Name.Identifier, TInfo); 12984 12985 NewTD->setAccess(AS); 12986 12987 if (Invalid) 12988 NewTD->setInvalidDecl(); 12989 12990 ProcessDeclAttributeList(S, NewTD, AttrList); 12991 AddPragmaAttributes(S, NewTD); 12992 12993 CheckTypedefForVariablyModifiedType(S, NewTD); 12994 Invalid |= NewTD->isInvalidDecl(); 12995 12996 bool Redeclaration = false; 12997 12998 NamedDecl *NewND; 12999 if (TemplateParamLists.size()) { 13000 TypeAliasTemplateDecl *OldDecl = nullptr; 13001 TemplateParameterList *OldTemplateParams = nullptr; 13002 13003 if (TemplateParamLists.size() != 1) { 13004 Diag(UsingLoc, diag::err_alias_template_extra_headers) 13005 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 13006 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 13007 } 13008 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 13009 13010 // Check that we can declare a template here. 13011 if (CheckTemplateDeclScope(S, TemplateParams)) 13012 return nullptr; 13013 13014 // Only consider previous declarations in the same scope. 13015 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 13016 /*ExplicitInstantiationOrSpecialization*/false); 13017 if (!Previous.empty()) { 13018 Redeclaration = true; 13019 13020 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 13021 if (!OldDecl && !Invalid) { 13022 Diag(UsingLoc, diag::err_redefinition_different_kind) 13023 << Name.Identifier; 13024 13025 NamedDecl *OldD = Previous.getRepresentativeDecl(); 13026 if (OldD->getLocation().isValid()) 13027 Diag(OldD->getLocation(), diag::note_previous_definition); 13028 13029 Invalid = true; 13030 } 13031 13032 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 13033 if (TemplateParameterListsAreEqual(TemplateParams, 13034 OldDecl->getTemplateParameters(), 13035 /*Complain=*/true, 13036 TPL_TemplateMatch)) 13037 OldTemplateParams = 13038 OldDecl->getMostRecentDecl()->getTemplateParameters(); 13039 else 13040 Invalid = true; 13041 13042 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 13043 if (!Invalid && 13044 !Context.hasSameType(OldTD->getUnderlyingType(), 13045 NewTD->getUnderlyingType())) { 13046 // FIXME: The C++0x standard does not clearly say this is ill-formed, 13047 // but we can't reasonably accept it. 13048 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 13049 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 13050 if (OldTD->getLocation().isValid()) 13051 Diag(OldTD->getLocation(), diag::note_previous_definition); 13052 Invalid = true; 13053 } 13054 } 13055 } 13056 13057 // Merge any previous default template arguments into our parameters, 13058 // and check the parameter list. 13059 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 13060 TPC_TypeAliasTemplate)) 13061 return nullptr; 13062 13063 TypeAliasTemplateDecl *NewDecl = 13064 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 13065 Name.Identifier, TemplateParams, 13066 NewTD); 13067 NewTD->setDescribedAliasTemplate(NewDecl); 13068 13069 NewDecl->setAccess(AS); 13070 13071 if (Invalid) 13072 NewDecl->setInvalidDecl(); 13073 else if (OldDecl) { 13074 NewDecl->setPreviousDecl(OldDecl); 13075 CheckRedeclarationInModule(NewDecl, OldDecl); 13076 } 13077 13078 NewND = NewDecl; 13079 } else { 13080 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 13081 setTagNameForLinkagePurposes(TD, NewTD); 13082 handleTagNumbering(TD, S); 13083 } 13084 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 13085 NewND = NewTD; 13086 } 13087 13088 PushOnScopeChains(NewND, S); 13089 ActOnDocumentableDecl(NewND); 13090 return NewND; 13091 } 13092 13093 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 13094 SourceLocation AliasLoc, 13095 IdentifierInfo *Alias, CXXScopeSpec &SS, 13096 SourceLocation IdentLoc, 13097 IdentifierInfo *Ident) { 13098 13099 // Lookup the namespace name. 13100 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 13101 LookupParsedName(R, S, &SS); 13102 13103 if (R.isAmbiguous()) 13104 return nullptr; 13105 13106 if (R.empty()) { 13107 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 13108 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 13109 return nullptr; 13110 } 13111 } 13112 assert(!R.isAmbiguous() && !R.empty()); 13113 NamedDecl *ND = R.getRepresentativeDecl(); 13114 13115 // Check if we have a previous declaration with the same name. 13116 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 13117 ForVisibleRedeclaration); 13118 LookupName(PrevR, S); 13119 13120 // Check we're not shadowing a template parameter. 13121 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 13122 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 13123 PrevR.clear(); 13124 } 13125 13126 // Filter out any other lookup result from an enclosing scope. 13127 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13128 /*AllowInlineNamespace*/false); 13129 13130 // Find the previous declaration and check that we can redeclare it. 13131 NamespaceAliasDecl *Prev = nullptr; 13132 if (PrevR.isSingleResult()) { 13133 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13134 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13135 // We already have an alias with the same name that points to the same 13136 // namespace; check that it matches. 13137 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13138 Prev = AD; 13139 } else if (isVisible(PrevDecl)) { 13140 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13141 << Alias; 13142 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13143 << AD->getNamespace(); 13144 return nullptr; 13145 } 13146 } else if (isVisible(PrevDecl)) { 13147 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13148 ? diag::err_redefinition 13149 : diag::err_redefinition_different_kind; 13150 Diag(AliasLoc, DiagID) << Alias; 13151 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13152 return nullptr; 13153 } 13154 } 13155 13156 // The use of a nested name specifier may trigger deprecation warnings. 13157 DiagnoseUseOfDecl(ND, IdentLoc); 13158 13159 NamespaceAliasDecl *AliasDecl = 13160 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13161 Alias, SS.getWithLocInContext(Context), 13162 IdentLoc, ND); 13163 if (Prev) 13164 AliasDecl->setPreviousDecl(Prev); 13165 13166 PushOnScopeChains(AliasDecl, S); 13167 return AliasDecl; 13168 } 13169 13170 namespace { 13171 struct SpecialMemberExceptionSpecInfo 13172 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13173 SourceLocation Loc; 13174 Sema::ImplicitExceptionSpecification ExceptSpec; 13175 13176 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13177 Sema::CXXSpecialMember CSM, 13178 Sema::InheritedConstructorInfo *ICI, 13179 SourceLocation Loc) 13180 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13181 13182 bool visitBase(CXXBaseSpecifier *Base); 13183 bool visitField(FieldDecl *FD); 13184 13185 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13186 unsigned Quals); 13187 13188 void visitSubobjectCall(Subobject Subobj, 13189 Sema::SpecialMemberOverloadResult SMOR); 13190 }; 13191 } 13192 13193 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13194 auto *RT = Base->getType()->getAs<RecordType>(); 13195 if (!RT) 13196 return false; 13197 13198 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13199 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13200 if (auto *BaseCtor = SMOR.getMethod()) { 13201 visitSubobjectCall(Base, BaseCtor); 13202 return false; 13203 } 13204 13205 visitClassSubobject(BaseClass, Base, 0); 13206 return false; 13207 } 13208 13209 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13210 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13211 Expr *E = FD->getInClassInitializer(); 13212 if (!E) 13213 // FIXME: It's a little wasteful to build and throw away a 13214 // CXXDefaultInitExpr here. 13215 // FIXME: We should have a single context note pointing at Loc, and 13216 // this location should be MD->getLocation() instead, since that's 13217 // the location where we actually use the default init expression. 13218 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13219 if (E) 13220 ExceptSpec.CalledExpr(E); 13221 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13222 ->getAs<RecordType>()) { 13223 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13224 FD->getType().getCVRQualifiers()); 13225 } 13226 return false; 13227 } 13228 13229 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13230 Subobject Subobj, 13231 unsigned Quals) { 13232 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13233 bool IsMutable = Field && Field->isMutable(); 13234 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13235 } 13236 13237 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13238 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13239 // Note, if lookup fails, it doesn't matter what exception specification we 13240 // choose because the special member will be deleted. 13241 if (CXXMethodDecl *MD = SMOR.getMethod()) 13242 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13243 } 13244 13245 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13246 llvm::APSInt Result; 13247 ExprResult Converted = CheckConvertedConstantExpression( 13248 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13249 ExplicitSpec.setExpr(Converted.get()); 13250 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13251 ExplicitSpec.setKind(Result.getBoolValue() 13252 ? ExplicitSpecKind::ResolvedTrue 13253 : ExplicitSpecKind::ResolvedFalse); 13254 return true; 13255 } 13256 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13257 return false; 13258 } 13259 13260 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13261 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13262 if (!ExplicitExpr->isTypeDependent()) 13263 tryResolveExplicitSpecifier(ES); 13264 return ES; 13265 } 13266 13267 static Sema::ImplicitExceptionSpecification 13268 ComputeDefaultedSpecialMemberExceptionSpec( 13269 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13270 Sema::InheritedConstructorInfo *ICI) { 13271 ComputingExceptionSpec CES(S, MD, Loc); 13272 13273 CXXRecordDecl *ClassDecl = MD->getParent(); 13274 13275 // C++ [except.spec]p14: 13276 // An implicitly declared special member function (Clause 12) shall have an 13277 // exception-specification. [...] 13278 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13279 if (ClassDecl->isInvalidDecl()) 13280 return Info.ExceptSpec; 13281 13282 // FIXME: If this diagnostic fires, we're probably missing a check for 13283 // attempting to resolve an exception specification before it's known 13284 // at a higher level. 13285 if (S.RequireCompleteType(MD->getLocation(), 13286 S.Context.getRecordType(ClassDecl), 13287 diag::err_exception_spec_incomplete_type)) 13288 return Info.ExceptSpec; 13289 13290 // C++1z [except.spec]p7: 13291 // [Look for exceptions thrown by] a constructor selected [...] to 13292 // initialize a potentially constructed subobject, 13293 // C++1z [except.spec]p8: 13294 // The exception specification for an implicitly-declared destructor, or a 13295 // destructor without a noexcept-specifier, is potentially-throwing if and 13296 // only if any of the destructors for any of its potentially constructed 13297 // subojects is potentially throwing. 13298 // FIXME: We respect the first rule but ignore the "potentially constructed" 13299 // in the second rule to resolve a core issue (no number yet) that would have 13300 // us reject: 13301 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13302 // struct B : A {}; 13303 // struct C : B { void f(); }; 13304 // ... due to giving B::~B() a non-throwing exception specification. 13305 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13306 : Info.VisitAllBases); 13307 13308 return Info.ExceptSpec; 13309 } 13310 13311 namespace { 13312 /// RAII object to register a special member as being currently declared. 13313 struct DeclaringSpecialMember { 13314 Sema &S; 13315 Sema::SpecialMemberDecl D; 13316 Sema::ContextRAII SavedContext; 13317 bool WasAlreadyBeingDeclared; 13318 13319 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13320 : S(S), D(RD, CSM), SavedContext(S, RD) { 13321 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13322 if (WasAlreadyBeingDeclared) 13323 // This almost never happens, but if it does, ensure that our cache 13324 // doesn't contain a stale result. 13325 S.SpecialMemberCache.clear(); 13326 else { 13327 // Register a note to be produced if we encounter an error while 13328 // declaring the special member. 13329 Sema::CodeSynthesisContext Ctx; 13330 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13331 // FIXME: We don't have a location to use here. Using the class's 13332 // location maintains the fiction that we declare all special members 13333 // with the class, but (1) it's not clear that lying about that helps our 13334 // users understand what's going on, and (2) there may be outer contexts 13335 // on the stack (some of which are relevant) and printing them exposes 13336 // our lies. 13337 Ctx.PointOfInstantiation = RD->getLocation(); 13338 Ctx.Entity = RD; 13339 Ctx.SpecialMember = CSM; 13340 S.pushCodeSynthesisContext(Ctx); 13341 } 13342 } 13343 ~DeclaringSpecialMember() { 13344 if (!WasAlreadyBeingDeclared) { 13345 S.SpecialMembersBeingDeclared.erase(D); 13346 S.popCodeSynthesisContext(); 13347 } 13348 } 13349 13350 /// Are we already trying to declare this special member? 13351 bool isAlreadyBeingDeclared() const { 13352 return WasAlreadyBeingDeclared; 13353 } 13354 }; 13355 } 13356 13357 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13358 // Look up any existing declarations, but don't trigger declaration of all 13359 // implicit special members with this name. 13360 DeclarationName Name = FD->getDeclName(); 13361 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13362 ForExternalRedeclaration); 13363 for (auto *D : FD->getParent()->lookup(Name)) 13364 if (auto *Acceptable = R.getAcceptableDecl(D)) 13365 R.addDecl(Acceptable); 13366 R.resolveKind(); 13367 R.suppressDiagnostics(); 13368 13369 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false, 13370 FD->isThisDeclarationADefinition()); 13371 } 13372 13373 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13374 QualType ResultTy, 13375 ArrayRef<QualType> Args) { 13376 // Build an exception specification pointing back at this constructor. 13377 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13378 13379 LangAS AS = getDefaultCXXMethodAddrSpace(); 13380 if (AS != LangAS::Default) { 13381 EPI.TypeQuals.addAddressSpace(AS); 13382 } 13383 13384 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13385 SpecialMem->setType(QT); 13386 13387 // During template instantiation of implicit special member functions we need 13388 // a reliable TypeSourceInfo for the function prototype in order to allow 13389 // functions to be substituted. 13390 if (inTemplateInstantiation() && 13391 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13392 TypeSourceInfo *TSI = 13393 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13394 SpecialMem->setTypeSourceInfo(TSI); 13395 } 13396 } 13397 13398 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13399 CXXRecordDecl *ClassDecl) { 13400 // C++ [class.ctor]p5: 13401 // A default constructor for a class X is a constructor of class X 13402 // that can be called without an argument. If there is no 13403 // user-declared constructor for class X, a default constructor is 13404 // implicitly declared. An implicitly-declared default constructor 13405 // is an inline public member of its class. 13406 assert(ClassDecl->needsImplicitDefaultConstructor() && 13407 "Should not build implicit default constructor!"); 13408 13409 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13410 if (DSM.isAlreadyBeingDeclared()) 13411 return nullptr; 13412 13413 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13414 CXXDefaultConstructor, 13415 false); 13416 13417 // Create the actual constructor declaration. 13418 CanQualType ClassType 13419 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13420 SourceLocation ClassLoc = ClassDecl->getLocation(); 13421 DeclarationName Name 13422 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13423 DeclarationNameInfo NameInfo(Name, ClassLoc); 13424 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13425 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13426 /*TInfo=*/nullptr, ExplicitSpecifier(), 13427 getCurFPFeatures().isFPConstrained(), 13428 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13429 Constexpr ? ConstexprSpecKind::Constexpr 13430 : ConstexprSpecKind::Unspecified); 13431 DefaultCon->setAccess(AS_public); 13432 DefaultCon->setDefaulted(); 13433 13434 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13435 13436 if (getLangOpts().CUDA) 13437 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13438 DefaultCon, 13439 /* ConstRHS */ false, 13440 /* Diagnose */ false); 13441 13442 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13443 // constructors is easy to compute. 13444 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13445 13446 // Note that we have declared this constructor. 13447 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13448 13449 Scope *S = getScopeForContext(ClassDecl); 13450 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13451 13452 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13453 SetDeclDeleted(DefaultCon, ClassLoc); 13454 13455 if (S) 13456 PushOnScopeChains(DefaultCon, S, false); 13457 ClassDecl->addDecl(DefaultCon); 13458 13459 return DefaultCon; 13460 } 13461 13462 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13463 CXXConstructorDecl *Constructor) { 13464 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13465 !Constructor->doesThisDeclarationHaveABody() && 13466 !Constructor->isDeleted()) && 13467 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13468 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13469 return; 13470 13471 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13472 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13473 13474 SynthesizedFunctionScope Scope(*this, Constructor); 13475 13476 // The exception specification is needed because we are defining the 13477 // function. 13478 ResolveExceptionSpec(CurrentLocation, 13479 Constructor->getType()->castAs<FunctionProtoType>()); 13480 MarkVTableUsed(CurrentLocation, ClassDecl); 13481 13482 // Add a context note for diagnostics produced after this point. 13483 Scope.addContextNote(CurrentLocation); 13484 13485 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13486 Constructor->setInvalidDecl(); 13487 return; 13488 } 13489 13490 SourceLocation Loc = Constructor->getEndLoc().isValid() 13491 ? Constructor->getEndLoc() 13492 : Constructor->getLocation(); 13493 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13494 Constructor->markUsed(Context); 13495 13496 if (ASTMutationListener *L = getASTMutationListener()) { 13497 L->CompletedImplicitDefinition(Constructor); 13498 } 13499 13500 DiagnoseUninitializedFields(*this, Constructor); 13501 } 13502 13503 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13504 // Perform any delayed checks on exception specifications. 13505 CheckDelayedMemberExceptionSpecs(); 13506 } 13507 13508 /// Find or create the fake constructor we synthesize to model constructing an 13509 /// object of a derived class via a constructor of a base class. 13510 CXXConstructorDecl * 13511 Sema::findInheritingConstructor(SourceLocation Loc, 13512 CXXConstructorDecl *BaseCtor, 13513 ConstructorUsingShadowDecl *Shadow) { 13514 CXXRecordDecl *Derived = Shadow->getParent(); 13515 SourceLocation UsingLoc = Shadow->getLocation(); 13516 13517 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13518 // For now we use the name of the base class constructor as a member of the 13519 // derived class to indicate a (fake) inherited constructor name. 13520 DeclarationName Name = BaseCtor->getDeclName(); 13521 13522 // Check to see if we already have a fake constructor for this inherited 13523 // constructor call. 13524 for (NamedDecl *Ctor : Derived->lookup(Name)) 13525 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13526 ->getInheritedConstructor() 13527 .getConstructor(), 13528 BaseCtor)) 13529 return cast<CXXConstructorDecl>(Ctor); 13530 13531 DeclarationNameInfo NameInfo(Name, UsingLoc); 13532 TypeSourceInfo *TInfo = 13533 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13534 FunctionProtoTypeLoc ProtoLoc = 13535 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13536 13537 // Check the inherited constructor is valid and find the list of base classes 13538 // from which it was inherited. 13539 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13540 13541 bool Constexpr = 13542 BaseCtor->isConstexpr() && 13543 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13544 false, BaseCtor, &ICI); 13545 13546 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13547 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13548 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13549 /*isInline=*/true, 13550 /*isImplicitlyDeclared=*/true, 13551 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13552 InheritedConstructor(Shadow, BaseCtor), 13553 BaseCtor->getTrailingRequiresClause()); 13554 if (Shadow->isInvalidDecl()) 13555 DerivedCtor->setInvalidDecl(); 13556 13557 // Build an unevaluated exception specification for this fake constructor. 13558 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13559 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13560 EPI.ExceptionSpec.Type = EST_Unevaluated; 13561 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13562 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13563 FPT->getParamTypes(), EPI)); 13564 13565 // Build the parameter declarations. 13566 SmallVector<ParmVarDecl *, 16> ParamDecls; 13567 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13568 TypeSourceInfo *TInfo = 13569 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13570 ParmVarDecl *PD = ParmVarDecl::Create( 13571 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13572 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13573 PD->setScopeInfo(0, I); 13574 PD->setImplicit(); 13575 // Ensure attributes are propagated onto parameters (this matters for 13576 // format, pass_object_size, ...). 13577 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13578 ParamDecls.push_back(PD); 13579 ProtoLoc.setParam(I, PD); 13580 } 13581 13582 // Set up the new constructor. 13583 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13584 DerivedCtor->setAccess(BaseCtor->getAccess()); 13585 DerivedCtor->setParams(ParamDecls); 13586 Derived->addDecl(DerivedCtor); 13587 13588 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13589 SetDeclDeleted(DerivedCtor, UsingLoc); 13590 13591 return DerivedCtor; 13592 } 13593 13594 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13595 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13596 Ctor->getInheritedConstructor().getShadowDecl()); 13597 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13598 /*Diagnose*/true); 13599 } 13600 13601 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13602 CXXConstructorDecl *Constructor) { 13603 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13604 assert(Constructor->getInheritedConstructor() && 13605 !Constructor->doesThisDeclarationHaveABody() && 13606 !Constructor->isDeleted()); 13607 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13608 return; 13609 13610 // Initializations are performed "as if by a defaulted default constructor", 13611 // so enter the appropriate scope. 13612 SynthesizedFunctionScope Scope(*this, Constructor); 13613 13614 // The exception specification is needed because we are defining the 13615 // function. 13616 ResolveExceptionSpec(CurrentLocation, 13617 Constructor->getType()->castAs<FunctionProtoType>()); 13618 MarkVTableUsed(CurrentLocation, ClassDecl); 13619 13620 // Add a context note for diagnostics produced after this point. 13621 Scope.addContextNote(CurrentLocation); 13622 13623 ConstructorUsingShadowDecl *Shadow = 13624 Constructor->getInheritedConstructor().getShadowDecl(); 13625 CXXConstructorDecl *InheritedCtor = 13626 Constructor->getInheritedConstructor().getConstructor(); 13627 13628 // [class.inhctor.init]p1: 13629 // initialization proceeds as if a defaulted default constructor is used to 13630 // initialize the D object and each base class subobject from which the 13631 // constructor was inherited 13632 13633 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13634 CXXRecordDecl *RD = Shadow->getParent(); 13635 SourceLocation InitLoc = Shadow->getLocation(); 13636 13637 // Build explicit initializers for all base classes from which the 13638 // constructor was inherited. 13639 SmallVector<CXXCtorInitializer*, 8> Inits; 13640 for (bool VBase : {false, true}) { 13641 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13642 if (B.isVirtual() != VBase) 13643 continue; 13644 13645 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13646 if (!BaseRD) 13647 continue; 13648 13649 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13650 if (!BaseCtor.first) 13651 continue; 13652 13653 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13654 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13655 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13656 13657 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13658 Inits.push_back(new (Context) CXXCtorInitializer( 13659 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13660 SourceLocation())); 13661 } 13662 } 13663 13664 // We now proceed as if for a defaulted default constructor, with the relevant 13665 // initializers replaced. 13666 13667 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13668 Constructor->setInvalidDecl(); 13669 return; 13670 } 13671 13672 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13673 Constructor->markUsed(Context); 13674 13675 if (ASTMutationListener *L = getASTMutationListener()) { 13676 L->CompletedImplicitDefinition(Constructor); 13677 } 13678 13679 DiagnoseUninitializedFields(*this, Constructor); 13680 } 13681 13682 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13683 // C++ [class.dtor]p2: 13684 // If a class has no user-declared destructor, a destructor is 13685 // declared implicitly. An implicitly-declared destructor is an 13686 // inline public member of its class. 13687 assert(ClassDecl->needsImplicitDestructor()); 13688 13689 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13690 if (DSM.isAlreadyBeingDeclared()) 13691 return nullptr; 13692 13693 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13694 CXXDestructor, 13695 false); 13696 13697 // Create the actual destructor declaration. 13698 CanQualType ClassType 13699 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13700 SourceLocation ClassLoc = ClassDecl->getLocation(); 13701 DeclarationName Name 13702 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13703 DeclarationNameInfo NameInfo(Name, ClassLoc); 13704 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13705 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13706 getCurFPFeatures().isFPConstrained(), 13707 /*isInline=*/true, 13708 /*isImplicitlyDeclared=*/true, 13709 Constexpr ? ConstexprSpecKind::Constexpr 13710 : ConstexprSpecKind::Unspecified); 13711 Destructor->setAccess(AS_public); 13712 Destructor->setDefaulted(); 13713 13714 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13715 13716 if (getLangOpts().CUDA) 13717 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13718 Destructor, 13719 /* ConstRHS */ false, 13720 /* Diagnose */ false); 13721 13722 // We don't need to use SpecialMemberIsTrivial here; triviality for 13723 // destructors is easy to compute. 13724 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13725 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13726 ClassDecl->hasTrivialDestructorForCall()); 13727 13728 // Note that we have declared this destructor. 13729 ++getASTContext().NumImplicitDestructorsDeclared; 13730 13731 Scope *S = getScopeForContext(ClassDecl); 13732 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13733 13734 // We can't check whether an implicit destructor is deleted before we complete 13735 // the definition of the class, because its validity depends on the alignment 13736 // of the class. We'll check this from ActOnFields once the class is complete. 13737 if (ClassDecl->isCompleteDefinition() && 13738 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13739 SetDeclDeleted(Destructor, ClassLoc); 13740 13741 // Introduce this destructor into its scope. 13742 if (S) 13743 PushOnScopeChains(Destructor, S, false); 13744 ClassDecl->addDecl(Destructor); 13745 13746 return Destructor; 13747 } 13748 13749 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13750 CXXDestructorDecl *Destructor) { 13751 assert((Destructor->isDefaulted() && 13752 !Destructor->doesThisDeclarationHaveABody() && 13753 !Destructor->isDeleted()) && 13754 "DefineImplicitDestructor - call it for implicit default dtor"); 13755 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13756 return; 13757 13758 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13759 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13760 13761 SynthesizedFunctionScope Scope(*this, Destructor); 13762 13763 // The exception specification is needed because we are defining the 13764 // function. 13765 ResolveExceptionSpec(CurrentLocation, 13766 Destructor->getType()->castAs<FunctionProtoType>()); 13767 MarkVTableUsed(CurrentLocation, ClassDecl); 13768 13769 // Add a context note for diagnostics produced after this point. 13770 Scope.addContextNote(CurrentLocation); 13771 13772 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13773 Destructor->getParent()); 13774 13775 if (CheckDestructor(Destructor)) { 13776 Destructor->setInvalidDecl(); 13777 return; 13778 } 13779 13780 SourceLocation Loc = Destructor->getEndLoc().isValid() 13781 ? Destructor->getEndLoc() 13782 : Destructor->getLocation(); 13783 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13784 Destructor->markUsed(Context); 13785 13786 if (ASTMutationListener *L = getASTMutationListener()) { 13787 L->CompletedImplicitDefinition(Destructor); 13788 } 13789 } 13790 13791 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13792 CXXDestructorDecl *Destructor) { 13793 if (Destructor->isInvalidDecl()) 13794 return; 13795 13796 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13797 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13798 "implicit complete dtors unneeded outside MS ABI"); 13799 assert(ClassDecl->getNumVBases() > 0 && 13800 "complete dtor only exists for classes with vbases"); 13801 13802 SynthesizedFunctionScope Scope(*this, Destructor); 13803 13804 // Add a context note for diagnostics produced after this point. 13805 Scope.addContextNote(CurrentLocation); 13806 13807 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13808 } 13809 13810 /// Perform any semantic analysis which needs to be delayed until all 13811 /// pending class member declarations have been parsed. 13812 void Sema::ActOnFinishCXXMemberDecls() { 13813 // If the context is an invalid C++ class, just suppress these checks. 13814 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13815 if (Record->isInvalidDecl()) { 13816 DelayedOverridingExceptionSpecChecks.clear(); 13817 DelayedEquivalentExceptionSpecChecks.clear(); 13818 return; 13819 } 13820 checkForMultipleExportedDefaultConstructors(*this, Record); 13821 } 13822 } 13823 13824 void Sema::ActOnFinishCXXNonNestedClass() { 13825 referenceDLLExportedClassMethods(); 13826 13827 if (!DelayedDllExportMemberFunctions.empty()) { 13828 SmallVector<CXXMethodDecl*, 4> WorkList; 13829 std::swap(DelayedDllExportMemberFunctions, WorkList); 13830 for (CXXMethodDecl *M : WorkList) { 13831 DefineDefaultedFunction(*this, M, M->getLocation()); 13832 13833 // Pass the method to the consumer to get emitted. This is not necessary 13834 // for explicit instantiation definitions, as they will get emitted 13835 // anyway. 13836 if (M->getParent()->getTemplateSpecializationKind() != 13837 TSK_ExplicitInstantiationDefinition) 13838 ActOnFinishInlineFunctionDef(M); 13839 } 13840 } 13841 } 13842 13843 void Sema::referenceDLLExportedClassMethods() { 13844 if (!DelayedDllExportClasses.empty()) { 13845 // Calling ReferenceDllExportedMembers might cause the current function to 13846 // be called again, so use a local copy of DelayedDllExportClasses. 13847 SmallVector<CXXRecordDecl *, 4> WorkList; 13848 std::swap(DelayedDllExportClasses, WorkList); 13849 for (CXXRecordDecl *Class : WorkList) 13850 ReferenceDllExportedMembers(*this, Class); 13851 } 13852 } 13853 13854 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13855 assert(getLangOpts().CPlusPlus11 && 13856 "adjusting dtor exception specs was introduced in c++11"); 13857 13858 if (Destructor->isDependentContext()) 13859 return; 13860 13861 // C++11 [class.dtor]p3: 13862 // A declaration of a destructor that does not have an exception- 13863 // specification is implicitly considered to have the same exception- 13864 // specification as an implicit declaration. 13865 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13866 if (DtorType->hasExceptionSpec()) 13867 return; 13868 13869 // Replace the destructor's type, building off the existing one. Fortunately, 13870 // the only thing of interest in the destructor type is its extended info. 13871 // The return and arguments are fixed. 13872 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13873 EPI.ExceptionSpec.Type = EST_Unevaluated; 13874 EPI.ExceptionSpec.SourceDecl = Destructor; 13875 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13876 13877 // FIXME: If the destructor has a body that could throw, and the newly created 13878 // spec doesn't allow exceptions, we should emit a warning, because this 13879 // change in behavior can break conforming C++03 programs at runtime. 13880 // However, we don't have a body or an exception specification yet, so it 13881 // needs to be done somewhere else. 13882 } 13883 13884 namespace { 13885 /// An abstract base class for all helper classes used in building the 13886 // copy/move operators. These classes serve as factory functions and help us 13887 // avoid using the same Expr* in the AST twice. 13888 class ExprBuilder { 13889 ExprBuilder(const ExprBuilder&) = delete; 13890 ExprBuilder &operator=(const ExprBuilder&) = delete; 13891 13892 protected: 13893 static Expr *assertNotNull(Expr *E) { 13894 assert(E && "Expression construction must not fail."); 13895 return E; 13896 } 13897 13898 public: 13899 ExprBuilder() {} 13900 virtual ~ExprBuilder() {} 13901 13902 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13903 }; 13904 13905 class RefBuilder: public ExprBuilder { 13906 VarDecl *Var; 13907 QualType VarType; 13908 13909 public: 13910 Expr *build(Sema &S, SourceLocation Loc) const override { 13911 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13912 } 13913 13914 RefBuilder(VarDecl *Var, QualType VarType) 13915 : Var(Var), VarType(VarType) {} 13916 }; 13917 13918 class ThisBuilder: public ExprBuilder { 13919 public: 13920 Expr *build(Sema &S, SourceLocation Loc) const override { 13921 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13922 } 13923 }; 13924 13925 class CastBuilder: public ExprBuilder { 13926 const ExprBuilder &Builder; 13927 QualType Type; 13928 ExprValueKind Kind; 13929 const CXXCastPath &Path; 13930 13931 public: 13932 Expr *build(Sema &S, SourceLocation Loc) const override { 13933 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13934 CK_UncheckedDerivedToBase, Kind, 13935 &Path).get()); 13936 } 13937 13938 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13939 const CXXCastPath &Path) 13940 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13941 }; 13942 13943 class DerefBuilder: public ExprBuilder { 13944 const ExprBuilder &Builder; 13945 13946 public: 13947 Expr *build(Sema &S, SourceLocation Loc) const override { 13948 return assertNotNull( 13949 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13950 } 13951 13952 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13953 }; 13954 13955 class MemberBuilder: public ExprBuilder { 13956 const ExprBuilder &Builder; 13957 QualType Type; 13958 CXXScopeSpec SS; 13959 bool IsArrow; 13960 LookupResult &MemberLookup; 13961 13962 public: 13963 Expr *build(Sema &S, SourceLocation Loc) const override { 13964 return assertNotNull(S.BuildMemberReferenceExpr( 13965 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13966 nullptr, MemberLookup, nullptr, nullptr).get()); 13967 } 13968 13969 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13970 LookupResult &MemberLookup) 13971 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13972 MemberLookup(MemberLookup) {} 13973 }; 13974 13975 class MoveCastBuilder: public ExprBuilder { 13976 const ExprBuilder &Builder; 13977 13978 public: 13979 Expr *build(Sema &S, SourceLocation Loc) const override { 13980 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13981 } 13982 13983 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13984 }; 13985 13986 class LvalueConvBuilder: public ExprBuilder { 13987 const ExprBuilder &Builder; 13988 13989 public: 13990 Expr *build(Sema &S, SourceLocation Loc) const override { 13991 return assertNotNull( 13992 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13993 } 13994 13995 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13996 }; 13997 13998 class SubscriptBuilder: public ExprBuilder { 13999 const ExprBuilder &Base; 14000 const ExprBuilder &Index; 14001 14002 public: 14003 Expr *build(Sema &S, SourceLocation Loc) const override { 14004 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 14005 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 14006 } 14007 14008 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 14009 : Base(Base), Index(Index) {} 14010 }; 14011 14012 } // end anonymous namespace 14013 14014 /// When generating a defaulted copy or move assignment operator, if a field 14015 /// should be copied with __builtin_memcpy rather than via explicit assignments, 14016 /// do so. This optimization only applies for arrays of scalars, and for arrays 14017 /// of class type where the selected copy/move-assignment operator is trivial. 14018 static StmtResult 14019 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 14020 const ExprBuilder &ToB, const ExprBuilder &FromB) { 14021 // Compute the size of the memory buffer to be copied. 14022 QualType SizeType = S.Context.getSizeType(); 14023 llvm::APInt Size(S.Context.getTypeSize(SizeType), 14024 S.Context.getTypeSizeInChars(T).getQuantity()); 14025 14026 // Take the address of the field references for "from" and "to". We 14027 // directly construct UnaryOperators here because semantic analysis 14028 // does not permit us to take the address of an xvalue. 14029 Expr *From = FromB.build(S, Loc); 14030 From = UnaryOperator::Create( 14031 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 14032 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14033 Expr *To = ToB.build(S, Loc); 14034 To = UnaryOperator::Create( 14035 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 14036 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14037 14038 const Type *E = T->getBaseElementTypeUnsafe(); 14039 bool NeedsCollectableMemCpy = 14040 E->isRecordType() && 14041 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 14042 14043 // Create a reference to the __builtin_objc_memmove_collectable function 14044 StringRef MemCpyName = NeedsCollectableMemCpy ? 14045 "__builtin_objc_memmove_collectable" : 14046 "__builtin_memcpy"; 14047 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 14048 Sema::LookupOrdinaryName); 14049 S.LookupName(R, S.TUScope, true); 14050 14051 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 14052 if (!MemCpy) 14053 // Something went horribly wrong earlier, and we will have complained 14054 // about it. 14055 return StmtError(); 14056 14057 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 14058 VK_PRValue, Loc, nullptr); 14059 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 14060 14061 Expr *CallArgs[] = { 14062 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 14063 }; 14064 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 14065 Loc, CallArgs, Loc); 14066 14067 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 14068 return Call.getAs<Stmt>(); 14069 } 14070 14071 /// Builds a statement that copies/moves the given entity from \p From to 14072 /// \c To. 14073 /// 14074 /// This routine is used to copy/move the members of a class with an 14075 /// implicitly-declared copy/move assignment operator. When the entities being 14076 /// copied are arrays, this routine builds for loops to copy them. 14077 /// 14078 /// \param S The Sema object used for type-checking. 14079 /// 14080 /// \param Loc The location where the implicit copy/move is being generated. 14081 /// 14082 /// \param T The type of the expressions being copied/moved. Both expressions 14083 /// must have this type. 14084 /// 14085 /// \param To The expression we are copying/moving to. 14086 /// 14087 /// \param From The expression we are copying/moving from. 14088 /// 14089 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 14090 /// Otherwise, it's a non-static member subobject. 14091 /// 14092 /// \param Copying Whether we're copying or moving. 14093 /// 14094 /// \param Depth Internal parameter recording the depth of the recursion. 14095 /// 14096 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 14097 /// if a memcpy should be used instead. 14098 static StmtResult 14099 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 14100 const ExprBuilder &To, const ExprBuilder &From, 14101 bool CopyingBaseSubobject, bool Copying, 14102 unsigned Depth = 0) { 14103 // C++11 [class.copy]p28: 14104 // Each subobject is assigned in the manner appropriate to its type: 14105 // 14106 // - if the subobject is of class type, as if by a call to operator= with 14107 // the subobject as the object expression and the corresponding 14108 // subobject of x as a single function argument (as if by explicit 14109 // qualification; that is, ignoring any possible virtual overriding 14110 // functions in more derived classes); 14111 // 14112 // C++03 [class.copy]p13: 14113 // - if the subobject is of class type, the copy assignment operator for 14114 // the class is used (as if by explicit qualification; that is, 14115 // ignoring any possible virtual overriding functions in more derived 14116 // classes); 14117 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 14118 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 14119 14120 // Look for operator=. 14121 DeclarationName Name 14122 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14123 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14124 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14125 14126 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14127 // operator. 14128 if (!S.getLangOpts().CPlusPlus11) { 14129 LookupResult::Filter F = OpLookup.makeFilter(); 14130 while (F.hasNext()) { 14131 NamedDecl *D = F.next(); 14132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14133 if (Method->isCopyAssignmentOperator() || 14134 (!Copying && Method->isMoveAssignmentOperator())) 14135 continue; 14136 14137 F.erase(); 14138 } 14139 F.done(); 14140 } 14141 14142 // Suppress the protected check (C++ [class.protected]) for each of the 14143 // assignment operators we found. This strange dance is required when 14144 // we're assigning via a base classes's copy-assignment operator. To 14145 // ensure that we're getting the right base class subobject (without 14146 // ambiguities), we need to cast "this" to that subobject type; to 14147 // ensure that we don't go through the virtual call mechanism, we need 14148 // to qualify the operator= name with the base class (see below). However, 14149 // this means that if the base class has a protected copy assignment 14150 // operator, the protected member access check will fail. So, we 14151 // rewrite "protected" access to "public" access in this case, since we 14152 // know by construction that we're calling from a derived class. 14153 if (CopyingBaseSubobject) { 14154 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14155 L != LEnd; ++L) { 14156 if (L.getAccess() == AS_protected) 14157 L.setAccess(AS_public); 14158 } 14159 } 14160 14161 // Create the nested-name-specifier that will be used to qualify the 14162 // reference to operator=; this is required to suppress the virtual 14163 // call mechanism. 14164 CXXScopeSpec SS; 14165 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14166 SS.MakeTrivial(S.Context, 14167 NestedNameSpecifier::Create(S.Context, nullptr, false, 14168 CanonicalT), 14169 Loc); 14170 14171 // Create the reference to operator=. 14172 ExprResult OpEqualRef 14173 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14174 SS, /*TemplateKWLoc=*/SourceLocation(), 14175 /*FirstQualifierInScope=*/nullptr, 14176 OpLookup, 14177 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14178 /*SuppressQualifierCheck=*/true); 14179 if (OpEqualRef.isInvalid()) 14180 return StmtError(); 14181 14182 // Build the call to the assignment operator. 14183 14184 Expr *FromInst = From.build(S, Loc); 14185 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14186 OpEqualRef.getAs<Expr>(), 14187 Loc, FromInst, Loc); 14188 if (Call.isInvalid()) 14189 return StmtError(); 14190 14191 // If we built a call to a trivial 'operator=' while copying an array, 14192 // bail out. We'll replace the whole shebang with a memcpy. 14193 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14194 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14195 return StmtResult((Stmt*)nullptr); 14196 14197 // Convert to an expression-statement, and clean up any produced 14198 // temporaries. 14199 return S.ActOnExprStmt(Call); 14200 } 14201 14202 // - if the subobject is of scalar type, the built-in assignment 14203 // operator is used. 14204 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14205 if (!ArrayTy) { 14206 ExprResult Assignment = S.CreateBuiltinBinOp( 14207 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14208 if (Assignment.isInvalid()) 14209 return StmtError(); 14210 return S.ActOnExprStmt(Assignment); 14211 } 14212 14213 // - if the subobject is an array, each element is assigned, in the 14214 // manner appropriate to the element type; 14215 14216 // Construct a loop over the array bounds, e.g., 14217 // 14218 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14219 // 14220 // that will copy each of the array elements. 14221 QualType SizeType = S.Context.getSizeType(); 14222 14223 // Create the iteration variable. 14224 IdentifierInfo *IterationVarName = nullptr; 14225 { 14226 SmallString<8> Str; 14227 llvm::raw_svector_ostream OS(Str); 14228 OS << "__i" << Depth; 14229 IterationVarName = &S.Context.Idents.get(OS.str()); 14230 } 14231 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14232 IterationVarName, SizeType, 14233 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14234 SC_None); 14235 14236 // Initialize the iteration variable to zero. 14237 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14238 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14239 14240 // Creates a reference to the iteration variable. 14241 RefBuilder IterationVarRef(IterationVar, SizeType); 14242 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14243 14244 // Create the DeclStmt that holds the iteration variable. 14245 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14246 14247 // Subscript the "from" and "to" expressions with the iteration variable. 14248 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14249 MoveCastBuilder FromIndexMove(FromIndexCopy); 14250 const ExprBuilder *FromIndex; 14251 if (Copying) 14252 FromIndex = &FromIndexCopy; 14253 else 14254 FromIndex = &FromIndexMove; 14255 14256 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14257 14258 // Build the copy/move for an individual element of the array. 14259 StmtResult Copy = 14260 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14261 ToIndex, *FromIndex, CopyingBaseSubobject, 14262 Copying, Depth + 1); 14263 // Bail out if copying fails or if we determined that we should use memcpy. 14264 if (Copy.isInvalid() || !Copy.get()) 14265 return Copy; 14266 14267 // Create the comparison against the array bound. 14268 llvm::APInt Upper 14269 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14270 Expr *Comparison = BinaryOperator::Create( 14271 S.Context, IterationVarRefRVal.build(S, Loc), 14272 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14273 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14274 S.CurFPFeatureOverrides()); 14275 14276 // Create the pre-increment of the iteration variable. We can determine 14277 // whether the increment will overflow based on the value of the array 14278 // bound. 14279 Expr *Increment = UnaryOperator::Create( 14280 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14281 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14282 14283 // Construct the loop that copies all elements of this array. 14284 return S.ActOnForStmt( 14285 Loc, Loc, InitStmt, 14286 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14287 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14288 } 14289 14290 static StmtResult 14291 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14292 const ExprBuilder &To, const ExprBuilder &From, 14293 bool CopyingBaseSubobject, bool Copying) { 14294 // Maybe we should use a memcpy? 14295 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14296 T.isTriviallyCopyableType(S.Context)) 14297 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14298 14299 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14300 CopyingBaseSubobject, 14301 Copying, 0)); 14302 14303 // If we ended up picking a trivial assignment operator for an array of a 14304 // non-trivially-copyable class type, just emit a memcpy. 14305 if (!Result.isInvalid() && !Result.get()) 14306 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14307 14308 return Result; 14309 } 14310 14311 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14312 // Note: The following rules are largely analoguous to the copy 14313 // constructor rules. Note that virtual bases are not taken into account 14314 // for determining the argument type of the operator. Note also that 14315 // operators taking an object instead of a reference are allowed. 14316 assert(ClassDecl->needsImplicitCopyAssignment()); 14317 14318 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14319 if (DSM.isAlreadyBeingDeclared()) 14320 return nullptr; 14321 14322 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14323 LangAS AS = getDefaultCXXMethodAddrSpace(); 14324 if (AS != LangAS::Default) 14325 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14326 QualType RetType = Context.getLValueReferenceType(ArgType); 14327 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14328 if (Const) 14329 ArgType = ArgType.withConst(); 14330 14331 ArgType = Context.getLValueReferenceType(ArgType); 14332 14333 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14334 CXXCopyAssignment, 14335 Const); 14336 14337 // An implicitly-declared copy assignment operator is an inline public 14338 // member of its class. 14339 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14340 SourceLocation ClassLoc = ClassDecl->getLocation(); 14341 DeclarationNameInfo NameInfo(Name, ClassLoc); 14342 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14343 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14344 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14345 getCurFPFeatures().isFPConstrained(), 14346 /*isInline=*/true, 14347 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14348 SourceLocation()); 14349 CopyAssignment->setAccess(AS_public); 14350 CopyAssignment->setDefaulted(); 14351 CopyAssignment->setImplicit(); 14352 14353 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14354 14355 if (getLangOpts().CUDA) 14356 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14357 CopyAssignment, 14358 /* ConstRHS */ Const, 14359 /* Diagnose */ false); 14360 14361 // Add the parameter to the operator. 14362 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14363 ClassLoc, ClassLoc, 14364 /*Id=*/nullptr, ArgType, 14365 /*TInfo=*/nullptr, SC_None, 14366 nullptr); 14367 CopyAssignment->setParams(FromParam); 14368 14369 CopyAssignment->setTrivial( 14370 ClassDecl->needsOverloadResolutionForCopyAssignment() 14371 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14372 : ClassDecl->hasTrivialCopyAssignment()); 14373 14374 // Note that we have added this copy-assignment operator. 14375 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14376 14377 Scope *S = getScopeForContext(ClassDecl); 14378 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14379 14380 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14381 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14382 SetDeclDeleted(CopyAssignment, ClassLoc); 14383 } 14384 14385 if (S) 14386 PushOnScopeChains(CopyAssignment, S, false); 14387 ClassDecl->addDecl(CopyAssignment); 14388 14389 return CopyAssignment; 14390 } 14391 14392 /// Diagnose an implicit copy operation for a class which is odr-used, but 14393 /// which is deprecated because the class has a user-declared copy constructor, 14394 /// copy assignment operator, or destructor. 14395 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14396 assert(CopyOp->isImplicit()); 14397 14398 CXXRecordDecl *RD = CopyOp->getParent(); 14399 CXXMethodDecl *UserDeclaredOperation = nullptr; 14400 14401 // In Microsoft mode, assignment operations don't affect constructors and 14402 // vice versa. 14403 if (RD->hasUserDeclaredDestructor()) { 14404 UserDeclaredOperation = RD->getDestructor(); 14405 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14406 RD->hasUserDeclaredCopyConstructor() && 14407 !S.getLangOpts().MSVCCompat) { 14408 // Find any user-declared copy constructor. 14409 for (auto *I : RD->ctors()) { 14410 if (I->isCopyConstructor()) { 14411 UserDeclaredOperation = I; 14412 break; 14413 } 14414 } 14415 assert(UserDeclaredOperation); 14416 } else if (isa<CXXConstructorDecl>(CopyOp) && 14417 RD->hasUserDeclaredCopyAssignment() && 14418 !S.getLangOpts().MSVCCompat) { 14419 // Find any user-declared move assignment operator. 14420 for (auto *I : RD->methods()) { 14421 if (I->isCopyAssignmentOperator()) { 14422 UserDeclaredOperation = I; 14423 break; 14424 } 14425 } 14426 assert(UserDeclaredOperation); 14427 } 14428 14429 if (UserDeclaredOperation) { 14430 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14431 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14432 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14433 unsigned DiagID = 14434 (UDOIsUserProvided && UDOIsDestructor) 14435 ? diag::warn_deprecated_copy_with_user_provided_dtor 14436 : (UDOIsUserProvided && !UDOIsDestructor) 14437 ? diag::warn_deprecated_copy_with_user_provided_copy 14438 : (!UDOIsUserProvided && UDOIsDestructor) 14439 ? diag::warn_deprecated_copy_with_dtor 14440 : diag::warn_deprecated_copy; 14441 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14442 << RD << IsCopyAssignment; 14443 } 14444 } 14445 14446 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14447 CXXMethodDecl *CopyAssignOperator) { 14448 assert((CopyAssignOperator->isDefaulted() && 14449 CopyAssignOperator->isOverloadedOperator() && 14450 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14451 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14452 !CopyAssignOperator->isDeleted()) && 14453 "DefineImplicitCopyAssignment called for wrong function"); 14454 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14455 return; 14456 14457 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14458 if (ClassDecl->isInvalidDecl()) { 14459 CopyAssignOperator->setInvalidDecl(); 14460 return; 14461 } 14462 14463 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14464 14465 // The exception specification is needed because we are defining the 14466 // function. 14467 ResolveExceptionSpec(CurrentLocation, 14468 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14469 14470 // Add a context note for diagnostics produced after this point. 14471 Scope.addContextNote(CurrentLocation); 14472 14473 // C++11 [class.copy]p18: 14474 // The [definition of an implicitly declared copy assignment operator] is 14475 // deprecated if the class has a user-declared copy constructor or a 14476 // user-declared destructor. 14477 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14478 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14479 14480 // C++0x [class.copy]p30: 14481 // The implicitly-defined or explicitly-defaulted copy assignment operator 14482 // for a non-union class X performs memberwise copy assignment of its 14483 // subobjects. The direct base classes of X are assigned first, in the 14484 // order of their declaration in the base-specifier-list, and then the 14485 // immediate non-static data members of X are assigned, in the order in 14486 // which they were declared in the class definition. 14487 14488 // The statements that form the synthesized function body. 14489 SmallVector<Stmt*, 8> Statements; 14490 14491 // The parameter for the "other" object, which we are copying from. 14492 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14493 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14494 QualType OtherRefType = Other->getType(); 14495 if (const LValueReferenceType *OtherRef 14496 = OtherRefType->getAs<LValueReferenceType>()) { 14497 OtherRefType = OtherRef->getPointeeType(); 14498 OtherQuals = OtherRefType.getQualifiers(); 14499 } 14500 14501 // Our location for everything implicitly-generated. 14502 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14503 ? CopyAssignOperator->getEndLoc() 14504 : CopyAssignOperator->getLocation(); 14505 14506 // Builds a DeclRefExpr for the "other" object. 14507 RefBuilder OtherRef(Other, OtherRefType); 14508 14509 // Builds the "this" pointer. 14510 ThisBuilder This; 14511 14512 // Assign base classes. 14513 bool Invalid = false; 14514 for (auto &Base : ClassDecl->bases()) { 14515 // Form the assignment: 14516 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14517 QualType BaseType = Base.getType().getUnqualifiedType(); 14518 if (!BaseType->isRecordType()) { 14519 Invalid = true; 14520 continue; 14521 } 14522 14523 CXXCastPath BasePath; 14524 BasePath.push_back(&Base); 14525 14526 // Construct the "from" expression, which is an implicit cast to the 14527 // appropriately-qualified base type. 14528 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14529 VK_LValue, BasePath); 14530 14531 // Dereference "this". 14532 DerefBuilder DerefThis(This); 14533 CastBuilder To(DerefThis, 14534 Context.getQualifiedType( 14535 BaseType, CopyAssignOperator->getMethodQualifiers()), 14536 VK_LValue, BasePath); 14537 14538 // Build the copy. 14539 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14540 To, From, 14541 /*CopyingBaseSubobject=*/true, 14542 /*Copying=*/true); 14543 if (Copy.isInvalid()) { 14544 CopyAssignOperator->setInvalidDecl(); 14545 return; 14546 } 14547 14548 // Success! Record the copy. 14549 Statements.push_back(Copy.getAs<Expr>()); 14550 } 14551 14552 // Assign non-static members. 14553 for (auto *Field : ClassDecl->fields()) { 14554 // FIXME: We should form some kind of AST representation for the implied 14555 // memcpy in a union copy operation. 14556 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14557 continue; 14558 14559 if (Field->isInvalidDecl()) { 14560 Invalid = true; 14561 continue; 14562 } 14563 14564 // Check for members of reference type; we can't copy those. 14565 if (Field->getType()->isReferenceType()) { 14566 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14567 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14568 Diag(Field->getLocation(), diag::note_declared_at); 14569 Invalid = true; 14570 continue; 14571 } 14572 14573 // Check for members of const-qualified, non-class type. 14574 QualType BaseType = Context.getBaseElementType(Field->getType()); 14575 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14576 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14577 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14578 Diag(Field->getLocation(), diag::note_declared_at); 14579 Invalid = true; 14580 continue; 14581 } 14582 14583 // Suppress assigning zero-width bitfields. 14584 if (Field->isZeroLengthBitField(Context)) 14585 continue; 14586 14587 QualType FieldType = Field->getType().getNonReferenceType(); 14588 if (FieldType->isIncompleteArrayType()) { 14589 assert(ClassDecl->hasFlexibleArrayMember() && 14590 "Incomplete array type is not valid"); 14591 continue; 14592 } 14593 14594 // Build references to the field in the object we're copying from and to. 14595 CXXScopeSpec SS; // Intentionally empty 14596 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14597 LookupMemberName); 14598 MemberLookup.addDecl(Field); 14599 MemberLookup.resolveKind(); 14600 14601 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14602 14603 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14604 14605 // Build the copy of this field. 14606 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14607 To, From, 14608 /*CopyingBaseSubobject=*/false, 14609 /*Copying=*/true); 14610 if (Copy.isInvalid()) { 14611 CopyAssignOperator->setInvalidDecl(); 14612 return; 14613 } 14614 14615 // Success! Record the copy. 14616 Statements.push_back(Copy.getAs<Stmt>()); 14617 } 14618 14619 if (!Invalid) { 14620 // Add a "return *this;" 14621 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14622 14623 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14624 if (Return.isInvalid()) 14625 Invalid = true; 14626 else 14627 Statements.push_back(Return.getAs<Stmt>()); 14628 } 14629 14630 if (Invalid) { 14631 CopyAssignOperator->setInvalidDecl(); 14632 return; 14633 } 14634 14635 StmtResult Body; 14636 { 14637 CompoundScopeRAII CompoundScope(*this); 14638 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14639 /*isStmtExpr=*/false); 14640 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14641 } 14642 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14643 CopyAssignOperator->markUsed(Context); 14644 14645 if (ASTMutationListener *L = getASTMutationListener()) { 14646 L->CompletedImplicitDefinition(CopyAssignOperator); 14647 } 14648 } 14649 14650 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14651 assert(ClassDecl->needsImplicitMoveAssignment()); 14652 14653 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14654 if (DSM.isAlreadyBeingDeclared()) 14655 return nullptr; 14656 14657 // Note: The following rules are largely analoguous to the move 14658 // constructor rules. 14659 14660 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14661 LangAS AS = getDefaultCXXMethodAddrSpace(); 14662 if (AS != LangAS::Default) 14663 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14664 QualType RetType = Context.getLValueReferenceType(ArgType); 14665 ArgType = Context.getRValueReferenceType(ArgType); 14666 14667 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14668 CXXMoveAssignment, 14669 false); 14670 14671 // An implicitly-declared move assignment operator is an inline public 14672 // member of its class. 14673 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14674 SourceLocation ClassLoc = ClassDecl->getLocation(); 14675 DeclarationNameInfo NameInfo(Name, ClassLoc); 14676 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14677 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14678 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14679 getCurFPFeatures().isFPConstrained(), 14680 /*isInline=*/true, 14681 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14682 SourceLocation()); 14683 MoveAssignment->setAccess(AS_public); 14684 MoveAssignment->setDefaulted(); 14685 MoveAssignment->setImplicit(); 14686 14687 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14688 14689 if (getLangOpts().CUDA) 14690 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14691 MoveAssignment, 14692 /* ConstRHS */ false, 14693 /* Diagnose */ false); 14694 14695 // Add the parameter to the operator. 14696 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14697 ClassLoc, ClassLoc, 14698 /*Id=*/nullptr, ArgType, 14699 /*TInfo=*/nullptr, SC_None, 14700 nullptr); 14701 MoveAssignment->setParams(FromParam); 14702 14703 MoveAssignment->setTrivial( 14704 ClassDecl->needsOverloadResolutionForMoveAssignment() 14705 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14706 : ClassDecl->hasTrivialMoveAssignment()); 14707 14708 // Note that we have added this copy-assignment operator. 14709 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14710 14711 Scope *S = getScopeForContext(ClassDecl); 14712 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14713 14714 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14715 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14716 SetDeclDeleted(MoveAssignment, ClassLoc); 14717 } 14718 14719 if (S) 14720 PushOnScopeChains(MoveAssignment, S, false); 14721 ClassDecl->addDecl(MoveAssignment); 14722 14723 return MoveAssignment; 14724 } 14725 14726 /// Check if we're implicitly defining a move assignment operator for a class 14727 /// with virtual bases. Such a move assignment might move-assign the virtual 14728 /// base multiple times. 14729 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14730 SourceLocation CurrentLocation) { 14731 assert(!Class->isDependentContext() && "should not define dependent move"); 14732 14733 // Only a virtual base could get implicitly move-assigned multiple times. 14734 // Only a non-trivial move assignment can observe this. We only want to 14735 // diagnose if we implicitly define an assignment operator that assigns 14736 // two base classes, both of which move-assign the same virtual base. 14737 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14738 Class->getNumBases() < 2) 14739 return; 14740 14741 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14742 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14743 VBaseMap VBases; 14744 14745 for (auto &BI : Class->bases()) { 14746 Worklist.push_back(&BI); 14747 while (!Worklist.empty()) { 14748 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14749 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14750 14751 // If the base has no non-trivial move assignment operators, 14752 // we don't care about moves from it. 14753 if (!Base->hasNonTrivialMoveAssignment()) 14754 continue; 14755 14756 // If there's nothing virtual here, skip it. 14757 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14758 continue; 14759 14760 // If we're not actually going to call a move assignment for this base, 14761 // or the selected move assignment is trivial, skip it. 14762 Sema::SpecialMemberOverloadResult SMOR = 14763 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14764 /*ConstArg*/false, /*VolatileArg*/false, 14765 /*RValueThis*/true, /*ConstThis*/false, 14766 /*VolatileThis*/false); 14767 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14768 !SMOR.getMethod()->isMoveAssignmentOperator()) 14769 continue; 14770 14771 if (BaseSpec->isVirtual()) { 14772 // We're going to move-assign this virtual base, and its move 14773 // assignment operator is not trivial. If this can happen for 14774 // multiple distinct direct bases of Class, diagnose it. (If it 14775 // only happens in one base, we'll diagnose it when synthesizing 14776 // that base class's move assignment operator.) 14777 CXXBaseSpecifier *&Existing = 14778 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14779 .first->second; 14780 if (Existing && Existing != &BI) { 14781 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14782 << Class << Base; 14783 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14784 << (Base->getCanonicalDecl() == 14785 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14786 << Base << Existing->getType() << Existing->getSourceRange(); 14787 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14788 << (Base->getCanonicalDecl() == 14789 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14790 << Base << BI.getType() << BaseSpec->getSourceRange(); 14791 14792 // Only diagnose each vbase once. 14793 Existing = nullptr; 14794 } 14795 } else { 14796 // Only walk over bases that have defaulted move assignment operators. 14797 // We assume that any user-provided move assignment operator handles 14798 // the multiple-moves-of-vbase case itself somehow. 14799 if (!SMOR.getMethod()->isDefaulted()) 14800 continue; 14801 14802 // We're going to move the base classes of Base. Add them to the list. 14803 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases())); 14804 } 14805 } 14806 } 14807 } 14808 14809 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14810 CXXMethodDecl *MoveAssignOperator) { 14811 assert((MoveAssignOperator->isDefaulted() && 14812 MoveAssignOperator->isOverloadedOperator() && 14813 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14814 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14815 !MoveAssignOperator->isDeleted()) && 14816 "DefineImplicitMoveAssignment called for wrong function"); 14817 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14818 return; 14819 14820 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14821 if (ClassDecl->isInvalidDecl()) { 14822 MoveAssignOperator->setInvalidDecl(); 14823 return; 14824 } 14825 14826 // C++0x [class.copy]p28: 14827 // The implicitly-defined or move assignment operator for a non-union class 14828 // X performs memberwise move assignment of its subobjects. The direct base 14829 // classes of X are assigned first, in the order of their declaration in the 14830 // base-specifier-list, and then the immediate non-static data members of X 14831 // are assigned, in the order in which they were declared in the class 14832 // definition. 14833 14834 // Issue a warning if our implicit move assignment operator will move 14835 // from a virtual base more than once. 14836 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14837 14838 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14839 14840 // The exception specification is needed because we are defining the 14841 // function. 14842 ResolveExceptionSpec(CurrentLocation, 14843 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14844 14845 // Add a context note for diagnostics produced after this point. 14846 Scope.addContextNote(CurrentLocation); 14847 14848 // The statements that form the synthesized function body. 14849 SmallVector<Stmt*, 8> Statements; 14850 14851 // The parameter for the "other" object, which we are move from. 14852 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14853 QualType OtherRefType = 14854 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14855 14856 // Our location for everything implicitly-generated. 14857 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14858 ? MoveAssignOperator->getEndLoc() 14859 : MoveAssignOperator->getLocation(); 14860 14861 // Builds a reference to the "other" object. 14862 RefBuilder OtherRef(Other, OtherRefType); 14863 // Cast to rvalue. 14864 MoveCastBuilder MoveOther(OtherRef); 14865 14866 // Builds the "this" pointer. 14867 ThisBuilder This; 14868 14869 // Assign base classes. 14870 bool Invalid = false; 14871 for (auto &Base : ClassDecl->bases()) { 14872 // C++11 [class.copy]p28: 14873 // It is unspecified whether subobjects representing virtual base classes 14874 // are assigned more than once by the implicitly-defined copy assignment 14875 // operator. 14876 // FIXME: Do not assign to a vbase that will be assigned by some other base 14877 // class. For a move-assignment, this can result in the vbase being moved 14878 // multiple times. 14879 14880 // Form the assignment: 14881 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14882 QualType BaseType = Base.getType().getUnqualifiedType(); 14883 if (!BaseType->isRecordType()) { 14884 Invalid = true; 14885 continue; 14886 } 14887 14888 CXXCastPath BasePath; 14889 BasePath.push_back(&Base); 14890 14891 // Construct the "from" expression, which is an implicit cast to the 14892 // appropriately-qualified base type. 14893 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14894 14895 // Dereference "this". 14896 DerefBuilder DerefThis(This); 14897 14898 // Implicitly cast "this" to the appropriately-qualified base type. 14899 CastBuilder To(DerefThis, 14900 Context.getQualifiedType( 14901 BaseType, MoveAssignOperator->getMethodQualifiers()), 14902 VK_LValue, BasePath); 14903 14904 // Build the move. 14905 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14906 To, From, 14907 /*CopyingBaseSubobject=*/true, 14908 /*Copying=*/false); 14909 if (Move.isInvalid()) { 14910 MoveAssignOperator->setInvalidDecl(); 14911 return; 14912 } 14913 14914 // Success! Record the move. 14915 Statements.push_back(Move.getAs<Expr>()); 14916 } 14917 14918 // Assign non-static members. 14919 for (auto *Field : ClassDecl->fields()) { 14920 // FIXME: We should form some kind of AST representation for the implied 14921 // memcpy in a union copy operation. 14922 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14923 continue; 14924 14925 if (Field->isInvalidDecl()) { 14926 Invalid = true; 14927 continue; 14928 } 14929 14930 // Check for members of reference type; we can't move those. 14931 if (Field->getType()->isReferenceType()) { 14932 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14933 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14934 Diag(Field->getLocation(), diag::note_declared_at); 14935 Invalid = true; 14936 continue; 14937 } 14938 14939 // Check for members of const-qualified, non-class type. 14940 QualType BaseType = Context.getBaseElementType(Field->getType()); 14941 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14942 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14943 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14944 Diag(Field->getLocation(), diag::note_declared_at); 14945 Invalid = true; 14946 continue; 14947 } 14948 14949 // Suppress assigning zero-width bitfields. 14950 if (Field->isZeroLengthBitField(Context)) 14951 continue; 14952 14953 QualType FieldType = Field->getType().getNonReferenceType(); 14954 if (FieldType->isIncompleteArrayType()) { 14955 assert(ClassDecl->hasFlexibleArrayMember() && 14956 "Incomplete array type is not valid"); 14957 continue; 14958 } 14959 14960 // Build references to the field in the object we're copying from and to. 14961 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14962 LookupMemberName); 14963 MemberLookup.addDecl(Field); 14964 MemberLookup.resolveKind(); 14965 MemberBuilder From(MoveOther, OtherRefType, 14966 /*IsArrow=*/false, MemberLookup); 14967 MemberBuilder To(This, getCurrentThisType(), 14968 /*IsArrow=*/true, MemberLookup); 14969 14970 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14971 "Member reference with rvalue base must be rvalue except for reference " 14972 "members, which aren't allowed for move assignment."); 14973 14974 // Build the move of this field. 14975 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14976 To, From, 14977 /*CopyingBaseSubobject=*/false, 14978 /*Copying=*/false); 14979 if (Move.isInvalid()) { 14980 MoveAssignOperator->setInvalidDecl(); 14981 return; 14982 } 14983 14984 // Success! Record the copy. 14985 Statements.push_back(Move.getAs<Stmt>()); 14986 } 14987 14988 if (!Invalid) { 14989 // Add a "return *this;" 14990 ExprResult ThisObj = 14991 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14992 14993 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14994 if (Return.isInvalid()) 14995 Invalid = true; 14996 else 14997 Statements.push_back(Return.getAs<Stmt>()); 14998 } 14999 15000 if (Invalid) { 15001 MoveAssignOperator->setInvalidDecl(); 15002 return; 15003 } 15004 15005 StmtResult Body; 15006 { 15007 CompoundScopeRAII CompoundScope(*this); 15008 Body = ActOnCompoundStmt(Loc, Loc, Statements, 15009 /*isStmtExpr=*/false); 15010 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 15011 } 15012 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 15013 MoveAssignOperator->markUsed(Context); 15014 15015 if (ASTMutationListener *L = getASTMutationListener()) { 15016 L->CompletedImplicitDefinition(MoveAssignOperator); 15017 } 15018 } 15019 15020 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 15021 CXXRecordDecl *ClassDecl) { 15022 // C++ [class.copy]p4: 15023 // If the class definition does not explicitly declare a copy 15024 // constructor, one is declared implicitly. 15025 assert(ClassDecl->needsImplicitCopyConstructor()); 15026 15027 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 15028 if (DSM.isAlreadyBeingDeclared()) 15029 return nullptr; 15030 15031 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15032 QualType ArgType = ClassType; 15033 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 15034 if (Const) 15035 ArgType = ArgType.withConst(); 15036 15037 LangAS AS = getDefaultCXXMethodAddrSpace(); 15038 if (AS != LangAS::Default) 15039 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 15040 15041 ArgType = Context.getLValueReferenceType(ArgType); 15042 15043 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15044 CXXCopyConstructor, 15045 Const); 15046 15047 DeclarationName Name 15048 = Context.DeclarationNames.getCXXConstructorName( 15049 Context.getCanonicalType(ClassType)); 15050 SourceLocation ClassLoc = ClassDecl->getLocation(); 15051 DeclarationNameInfo NameInfo(Name, ClassLoc); 15052 15053 // An implicitly-declared copy constructor is an inline public 15054 // member of its class. 15055 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 15056 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15057 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15058 /*isInline=*/true, 15059 /*isImplicitlyDeclared=*/true, 15060 Constexpr ? ConstexprSpecKind::Constexpr 15061 : ConstexprSpecKind::Unspecified); 15062 CopyConstructor->setAccess(AS_public); 15063 CopyConstructor->setDefaulted(); 15064 15065 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 15066 15067 if (getLangOpts().CUDA) 15068 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 15069 CopyConstructor, 15070 /* ConstRHS */ Const, 15071 /* Diagnose */ false); 15072 15073 // During template instantiation of special member functions we need a 15074 // reliable TypeSourceInfo for the parameter types in order to allow functions 15075 // to be substituted. 15076 TypeSourceInfo *TSI = nullptr; 15077 if (inTemplateInstantiation() && ClassDecl->isLambda()) 15078 TSI = Context.getTrivialTypeSourceInfo(ArgType); 15079 15080 // Add the parameter to the constructor. 15081 ParmVarDecl *FromParam = 15082 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 15083 /*IdentifierInfo=*/nullptr, ArgType, 15084 /*TInfo=*/TSI, SC_None, nullptr); 15085 CopyConstructor->setParams(FromParam); 15086 15087 CopyConstructor->setTrivial( 15088 ClassDecl->needsOverloadResolutionForCopyConstructor() 15089 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 15090 : ClassDecl->hasTrivialCopyConstructor()); 15091 15092 CopyConstructor->setTrivialForCall( 15093 ClassDecl->hasAttr<TrivialABIAttr>() || 15094 (ClassDecl->needsOverloadResolutionForCopyConstructor() 15095 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 15096 TAH_ConsiderTrivialABI) 15097 : ClassDecl->hasTrivialCopyConstructorForCall())); 15098 15099 // Note that we have declared this constructor. 15100 ++getASTContext().NumImplicitCopyConstructorsDeclared; 15101 15102 Scope *S = getScopeForContext(ClassDecl); 15103 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 15104 15105 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 15106 ClassDecl->setImplicitCopyConstructorIsDeleted(); 15107 SetDeclDeleted(CopyConstructor, ClassLoc); 15108 } 15109 15110 if (S) 15111 PushOnScopeChains(CopyConstructor, S, false); 15112 ClassDecl->addDecl(CopyConstructor); 15113 15114 return CopyConstructor; 15115 } 15116 15117 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 15118 CXXConstructorDecl *CopyConstructor) { 15119 assert((CopyConstructor->isDefaulted() && 15120 CopyConstructor->isCopyConstructor() && 15121 !CopyConstructor->doesThisDeclarationHaveABody() && 15122 !CopyConstructor->isDeleted()) && 15123 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 15124 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15125 return; 15126 15127 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15128 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 15129 15130 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15131 15132 // The exception specification is needed because we are defining the 15133 // function. 15134 ResolveExceptionSpec(CurrentLocation, 15135 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15136 MarkVTableUsed(CurrentLocation, ClassDecl); 15137 15138 // Add a context note for diagnostics produced after this point. 15139 Scope.addContextNote(CurrentLocation); 15140 15141 // C++11 [class.copy]p7: 15142 // The [definition of an implicitly declared copy constructor] is 15143 // deprecated if the class has a user-declared copy assignment operator 15144 // or a user-declared destructor. 15145 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15146 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15147 15148 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15149 CopyConstructor->setInvalidDecl(); 15150 } else { 15151 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15152 ? CopyConstructor->getEndLoc() 15153 : CopyConstructor->getLocation(); 15154 Sema::CompoundScopeRAII CompoundScope(*this); 15155 CopyConstructor->setBody( 15156 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15157 CopyConstructor->markUsed(Context); 15158 } 15159 15160 if (ASTMutationListener *L = getASTMutationListener()) { 15161 L->CompletedImplicitDefinition(CopyConstructor); 15162 } 15163 } 15164 15165 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15166 CXXRecordDecl *ClassDecl) { 15167 assert(ClassDecl->needsImplicitMoveConstructor()); 15168 15169 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15170 if (DSM.isAlreadyBeingDeclared()) 15171 return nullptr; 15172 15173 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15174 15175 QualType ArgType = ClassType; 15176 LangAS AS = getDefaultCXXMethodAddrSpace(); 15177 if (AS != LangAS::Default) 15178 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15179 ArgType = Context.getRValueReferenceType(ArgType); 15180 15181 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15182 CXXMoveConstructor, 15183 false); 15184 15185 DeclarationName Name 15186 = Context.DeclarationNames.getCXXConstructorName( 15187 Context.getCanonicalType(ClassType)); 15188 SourceLocation ClassLoc = ClassDecl->getLocation(); 15189 DeclarationNameInfo NameInfo(Name, ClassLoc); 15190 15191 // C++11 [class.copy]p11: 15192 // An implicitly-declared copy/move constructor is an inline public 15193 // member of its class. 15194 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15195 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15196 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15197 /*isInline=*/true, 15198 /*isImplicitlyDeclared=*/true, 15199 Constexpr ? ConstexprSpecKind::Constexpr 15200 : ConstexprSpecKind::Unspecified); 15201 MoveConstructor->setAccess(AS_public); 15202 MoveConstructor->setDefaulted(); 15203 15204 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15205 15206 if (getLangOpts().CUDA) 15207 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15208 MoveConstructor, 15209 /* ConstRHS */ false, 15210 /* Diagnose */ false); 15211 15212 // Add the parameter to the constructor. 15213 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15214 ClassLoc, ClassLoc, 15215 /*IdentifierInfo=*/nullptr, 15216 ArgType, /*TInfo=*/nullptr, 15217 SC_None, nullptr); 15218 MoveConstructor->setParams(FromParam); 15219 15220 MoveConstructor->setTrivial( 15221 ClassDecl->needsOverloadResolutionForMoveConstructor() 15222 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15223 : ClassDecl->hasTrivialMoveConstructor()); 15224 15225 MoveConstructor->setTrivialForCall( 15226 ClassDecl->hasAttr<TrivialABIAttr>() || 15227 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15228 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15229 TAH_ConsiderTrivialABI) 15230 : ClassDecl->hasTrivialMoveConstructorForCall())); 15231 15232 // Note that we have declared this constructor. 15233 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15234 15235 Scope *S = getScopeForContext(ClassDecl); 15236 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15237 15238 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15239 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15240 SetDeclDeleted(MoveConstructor, ClassLoc); 15241 } 15242 15243 if (S) 15244 PushOnScopeChains(MoveConstructor, S, false); 15245 ClassDecl->addDecl(MoveConstructor); 15246 15247 return MoveConstructor; 15248 } 15249 15250 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15251 CXXConstructorDecl *MoveConstructor) { 15252 assert((MoveConstructor->isDefaulted() && 15253 MoveConstructor->isMoveConstructor() && 15254 !MoveConstructor->doesThisDeclarationHaveABody() && 15255 !MoveConstructor->isDeleted()) && 15256 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15257 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15258 return; 15259 15260 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15261 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15262 15263 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15264 15265 // The exception specification is needed because we are defining the 15266 // function. 15267 ResolveExceptionSpec(CurrentLocation, 15268 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15269 MarkVTableUsed(CurrentLocation, ClassDecl); 15270 15271 // Add a context note for diagnostics produced after this point. 15272 Scope.addContextNote(CurrentLocation); 15273 15274 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15275 MoveConstructor->setInvalidDecl(); 15276 } else { 15277 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15278 ? MoveConstructor->getEndLoc() 15279 : MoveConstructor->getLocation(); 15280 Sema::CompoundScopeRAII CompoundScope(*this); 15281 MoveConstructor->setBody(ActOnCompoundStmt( 15282 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15283 MoveConstructor->markUsed(Context); 15284 } 15285 15286 if (ASTMutationListener *L = getASTMutationListener()) { 15287 L->CompletedImplicitDefinition(MoveConstructor); 15288 } 15289 } 15290 15291 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15292 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15293 } 15294 15295 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15296 SourceLocation CurrentLocation, 15297 CXXConversionDecl *Conv) { 15298 SynthesizedFunctionScope Scope(*this, Conv); 15299 assert(!Conv->getReturnType()->isUndeducedType()); 15300 15301 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15302 CallingConv CC = 15303 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15304 15305 CXXRecordDecl *Lambda = Conv->getParent(); 15306 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15307 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15308 15309 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15310 CallOp = InstantiateFunctionDeclaration( 15311 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15312 if (!CallOp) 15313 return; 15314 15315 Invoker = InstantiateFunctionDeclaration( 15316 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15317 if (!Invoker) 15318 return; 15319 } 15320 15321 if (CallOp->isInvalidDecl()) 15322 return; 15323 15324 // Mark the call operator referenced (and add to pending instantiations 15325 // if necessary). 15326 // For both the conversion and static-invoker template specializations 15327 // we construct their body's in this function, so no need to add them 15328 // to the PendingInstantiations. 15329 MarkFunctionReferenced(CurrentLocation, CallOp); 15330 15331 // Fill in the __invoke function with a dummy implementation. IR generation 15332 // will fill in the actual details. Update its type in case it contained 15333 // an 'auto'. 15334 Invoker->markUsed(Context); 15335 Invoker->setReferenced(); 15336 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15337 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15338 15339 // Construct the body of the conversion function { return __invoke; }. 15340 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15341 VK_LValue, Conv->getLocation()); 15342 assert(FunctionRef && "Can't refer to __invoke function?"); 15343 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15344 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15345 Conv->getLocation())); 15346 Conv->markUsed(Context); 15347 Conv->setReferenced(); 15348 15349 if (ASTMutationListener *L = getASTMutationListener()) { 15350 L->CompletedImplicitDefinition(Conv); 15351 L->CompletedImplicitDefinition(Invoker); 15352 } 15353 } 15354 15355 15356 15357 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15358 SourceLocation CurrentLocation, 15359 CXXConversionDecl *Conv) 15360 { 15361 assert(!Conv->getParent()->isGenericLambda()); 15362 15363 SynthesizedFunctionScope Scope(*this, Conv); 15364 15365 // Copy-initialize the lambda object as needed to capture it. 15366 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15367 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15368 15369 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15370 Conv->getLocation(), 15371 Conv, DerefThis); 15372 15373 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15374 // behavior. Note that only the general conversion function does this 15375 // (since it's unusable otherwise); in the case where we inline the 15376 // block literal, it has block literal lifetime semantics. 15377 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15378 BuildBlock = ImplicitCastExpr::Create( 15379 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15380 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15381 15382 if (BuildBlock.isInvalid()) { 15383 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15384 Conv->setInvalidDecl(); 15385 return; 15386 } 15387 15388 // Create the return statement that returns the block from the conversion 15389 // function. 15390 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15391 if (Return.isInvalid()) { 15392 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15393 Conv->setInvalidDecl(); 15394 return; 15395 } 15396 15397 // Set the body of the conversion function. 15398 Stmt *ReturnS = Return.get(); 15399 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15400 Conv->getLocation())); 15401 Conv->markUsed(Context); 15402 15403 // We're done; notify the mutation listener, if any. 15404 if (ASTMutationListener *L = getASTMutationListener()) { 15405 L->CompletedImplicitDefinition(Conv); 15406 } 15407 } 15408 15409 /// Determine whether the given list arguments contains exactly one 15410 /// "real" (non-default) argument. 15411 static bool hasOneRealArgument(MultiExprArg Args) { 15412 switch (Args.size()) { 15413 case 0: 15414 return false; 15415 15416 default: 15417 if (!Args[1]->isDefaultArgument()) 15418 return false; 15419 15420 LLVM_FALLTHROUGH; 15421 case 1: 15422 return !Args[0]->isDefaultArgument(); 15423 } 15424 15425 return false; 15426 } 15427 15428 ExprResult 15429 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15430 NamedDecl *FoundDecl, 15431 CXXConstructorDecl *Constructor, 15432 MultiExprArg ExprArgs, 15433 bool HadMultipleCandidates, 15434 bool IsListInitialization, 15435 bool IsStdInitListInitialization, 15436 bool RequiresZeroInit, 15437 unsigned ConstructKind, 15438 SourceRange ParenRange) { 15439 bool Elidable = false; 15440 15441 // C++0x [class.copy]p34: 15442 // When certain criteria are met, an implementation is allowed to 15443 // omit the copy/move construction of a class object, even if the 15444 // copy/move constructor and/or destructor for the object have 15445 // side effects. [...] 15446 // - when a temporary class object that has not been bound to a 15447 // reference (12.2) would be copied/moved to a class object 15448 // with the same cv-unqualified type, the copy/move operation 15449 // can be omitted by constructing the temporary object 15450 // directly into the target of the omitted copy/move 15451 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15452 // FIXME: Converting constructors should also be accepted. 15453 // But to fix this, the logic that digs down into a CXXConstructExpr 15454 // to find the source object needs to handle it. 15455 // Right now it assumes the source object is passed directly as the 15456 // first argument. 15457 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15458 Expr *SubExpr = ExprArgs[0]; 15459 // FIXME: Per above, this is also incorrect if we want to accept 15460 // converting constructors, as isTemporaryObject will 15461 // reject temporaries with different type from the 15462 // CXXRecord itself. 15463 Elidable = SubExpr->isTemporaryObject( 15464 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15465 } 15466 15467 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15468 FoundDecl, Constructor, 15469 Elidable, ExprArgs, HadMultipleCandidates, 15470 IsListInitialization, 15471 IsStdInitListInitialization, RequiresZeroInit, 15472 ConstructKind, ParenRange); 15473 } 15474 15475 ExprResult 15476 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15477 NamedDecl *FoundDecl, 15478 CXXConstructorDecl *Constructor, 15479 bool Elidable, 15480 MultiExprArg ExprArgs, 15481 bool HadMultipleCandidates, 15482 bool IsListInitialization, 15483 bool IsStdInitListInitialization, 15484 bool RequiresZeroInit, 15485 unsigned ConstructKind, 15486 SourceRange ParenRange) { 15487 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15488 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15489 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15490 return ExprError(); 15491 } 15492 15493 return BuildCXXConstructExpr( 15494 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15495 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15496 RequiresZeroInit, ConstructKind, ParenRange); 15497 } 15498 15499 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15500 /// including handling of its default argument expressions. 15501 ExprResult 15502 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15503 CXXConstructorDecl *Constructor, 15504 bool Elidable, 15505 MultiExprArg ExprArgs, 15506 bool HadMultipleCandidates, 15507 bool IsListInitialization, 15508 bool IsStdInitListInitialization, 15509 bool RequiresZeroInit, 15510 unsigned ConstructKind, 15511 SourceRange ParenRange) { 15512 assert(declaresSameEntity( 15513 Constructor->getParent(), 15514 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15515 "given constructor for wrong type"); 15516 MarkFunctionReferenced(ConstructLoc, Constructor); 15517 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15518 return ExprError(); 15519 if (getLangOpts().SYCLIsDevice && 15520 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15521 return ExprError(); 15522 15523 return CheckForImmediateInvocation( 15524 CXXConstructExpr::Create( 15525 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15526 HadMultipleCandidates, IsListInitialization, 15527 IsStdInitListInitialization, RequiresZeroInit, 15528 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15529 ParenRange), 15530 Constructor); 15531 } 15532 15533 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15534 assert(Field->hasInClassInitializer()); 15535 15536 // If we already have the in-class initializer nothing needs to be done. 15537 if (Field->getInClassInitializer()) 15538 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15539 15540 // If we might have already tried and failed to instantiate, don't try again. 15541 if (Field->isInvalidDecl()) 15542 return ExprError(); 15543 15544 // Maybe we haven't instantiated the in-class initializer. Go check the 15545 // pattern FieldDecl to see if it has one. 15546 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15547 15548 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15549 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15550 DeclContext::lookup_result Lookup = 15551 ClassPattern->lookup(Field->getDeclName()); 15552 15553 FieldDecl *Pattern = nullptr; 15554 for (auto L : Lookup) { 15555 if (isa<FieldDecl>(L)) { 15556 Pattern = cast<FieldDecl>(L); 15557 break; 15558 } 15559 } 15560 assert(Pattern && "We must have set the Pattern!"); 15561 15562 if (!Pattern->hasInClassInitializer() || 15563 InstantiateInClassInitializer(Loc, Field, Pattern, 15564 getTemplateInstantiationArgs(Field))) { 15565 // Don't diagnose this again. 15566 Field->setInvalidDecl(); 15567 return ExprError(); 15568 } 15569 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15570 } 15571 15572 // DR1351: 15573 // If the brace-or-equal-initializer of a non-static data member 15574 // invokes a defaulted default constructor of its class or of an 15575 // enclosing class in a potentially evaluated subexpression, the 15576 // program is ill-formed. 15577 // 15578 // This resolution is unworkable: the exception specification of the 15579 // default constructor can be needed in an unevaluated context, in 15580 // particular, in the operand of a noexcept-expression, and we can be 15581 // unable to compute an exception specification for an enclosed class. 15582 // 15583 // Any attempt to resolve the exception specification of a defaulted default 15584 // constructor before the initializer is lexically complete will ultimately 15585 // come here at which point we can diagnose it. 15586 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15587 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15588 << OutermostClass << Field; 15589 Diag(Field->getEndLoc(), 15590 diag::note_default_member_initializer_not_yet_parsed); 15591 // Recover by marking the field invalid, unless we're in a SFINAE context. 15592 if (!isSFINAEContext()) 15593 Field->setInvalidDecl(); 15594 return ExprError(); 15595 } 15596 15597 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15598 if (VD->isInvalidDecl()) return; 15599 // If initializing the variable failed, don't also diagnose problems with 15600 // the destructor, they're likely related. 15601 if (VD->getInit() && VD->getInit()->containsErrors()) 15602 return; 15603 15604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15605 if (ClassDecl->isInvalidDecl()) return; 15606 if (ClassDecl->hasIrrelevantDestructor()) return; 15607 if (ClassDecl->isDependentContext()) return; 15608 15609 if (VD->isNoDestroy(getASTContext())) 15610 return; 15611 15612 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15613 15614 // If this is an array, we'll require the destructor during initialization, so 15615 // we can skip over this. We still want to emit exit-time destructor warnings 15616 // though. 15617 if (!VD->getType()->isArrayType()) { 15618 MarkFunctionReferenced(VD->getLocation(), Destructor); 15619 CheckDestructorAccess(VD->getLocation(), Destructor, 15620 PDiag(diag::err_access_dtor_var) 15621 << VD->getDeclName() << VD->getType()); 15622 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15623 } 15624 15625 if (Destructor->isTrivial()) return; 15626 15627 // If the destructor is constexpr, check whether the variable has constant 15628 // destruction now. 15629 if (Destructor->isConstexpr()) { 15630 bool HasConstantInit = false; 15631 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15632 HasConstantInit = VD->evaluateValue(); 15633 SmallVector<PartialDiagnosticAt, 8> Notes; 15634 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15635 HasConstantInit) { 15636 Diag(VD->getLocation(), 15637 diag::err_constexpr_var_requires_const_destruction) << VD; 15638 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15639 Diag(Notes[I].first, Notes[I].second); 15640 } 15641 } 15642 15643 if (!VD->hasGlobalStorage()) return; 15644 15645 // Emit warning for non-trivial dtor in global scope (a real global, 15646 // class-static, function-static). 15647 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15648 15649 // TODO: this should be re-enabled for static locals by !CXAAtExit 15650 if (!VD->isStaticLocal()) 15651 Diag(VD->getLocation(), diag::warn_global_destructor); 15652 } 15653 15654 /// Given a constructor and the set of arguments provided for the 15655 /// constructor, convert the arguments and add any required default arguments 15656 /// to form a proper call to this constructor. 15657 /// 15658 /// \returns true if an error occurred, false otherwise. 15659 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15660 QualType DeclInitType, MultiExprArg ArgsPtr, 15661 SourceLocation Loc, 15662 SmallVectorImpl<Expr *> &ConvertedArgs, 15663 bool AllowExplicit, 15664 bool IsListInitialization) { 15665 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15666 unsigned NumArgs = ArgsPtr.size(); 15667 Expr **Args = ArgsPtr.data(); 15668 15669 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15670 unsigned NumParams = Proto->getNumParams(); 15671 15672 // If too few arguments are available, we'll fill in the rest with defaults. 15673 if (NumArgs < NumParams) 15674 ConvertedArgs.reserve(NumParams); 15675 else 15676 ConvertedArgs.reserve(NumArgs); 15677 15678 VariadicCallType CallType = 15679 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15680 SmallVector<Expr *, 8> AllArgs; 15681 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15682 Proto, 0, 15683 llvm::makeArrayRef(Args, NumArgs), 15684 AllArgs, 15685 CallType, AllowExplicit, 15686 IsListInitialization); 15687 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15688 15689 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15690 15691 CheckConstructorCall(Constructor, DeclInitType, 15692 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15693 Proto, Loc); 15694 15695 return Invalid; 15696 } 15697 15698 static inline bool 15699 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15700 const FunctionDecl *FnDecl) { 15701 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15702 if (isa<NamespaceDecl>(DC)) { 15703 return SemaRef.Diag(FnDecl->getLocation(), 15704 diag::err_operator_new_delete_declared_in_namespace) 15705 << FnDecl->getDeclName(); 15706 } 15707 15708 if (isa<TranslationUnitDecl>(DC) && 15709 FnDecl->getStorageClass() == SC_Static) { 15710 return SemaRef.Diag(FnDecl->getLocation(), 15711 diag::err_operator_new_delete_declared_static) 15712 << FnDecl->getDeclName(); 15713 } 15714 15715 return false; 15716 } 15717 15718 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15719 const PointerType *PtrTy) { 15720 auto &Ctx = SemaRef.Context; 15721 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15722 PtrQuals.removeAddressSpace(); 15723 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15724 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15725 } 15726 15727 static inline bool 15728 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15729 CanQualType ExpectedResultType, 15730 CanQualType ExpectedFirstParamType, 15731 unsigned DependentParamTypeDiag, 15732 unsigned InvalidParamTypeDiag) { 15733 QualType ResultType = 15734 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15735 15736 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15737 // The operator is valid on any address space for OpenCL. 15738 // Drop address space from actual and expected result types. 15739 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15740 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15741 15742 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15743 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15744 } 15745 15746 // Check that the result type is what we expect. 15747 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15748 // Reject even if the type is dependent; an operator delete function is 15749 // required to have a non-dependent result type. 15750 return SemaRef.Diag( 15751 FnDecl->getLocation(), 15752 ResultType->isDependentType() 15753 ? diag::err_operator_new_delete_dependent_result_type 15754 : diag::err_operator_new_delete_invalid_result_type) 15755 << FnDecl->getDeclName() << ExpectedResultType; 15756 } 15757 15758 // A function template must have at least 2 parameters. 15759 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15760 return SemaRef.Diag(FnDecl->getLocation(), 15761 diag::err_operator_new_delete_template_too_few_parameters) 15762 << FnDecl->getDeclName(); 15763 15764 // The function decl must have at least 1 parameter. 15765 if (FnDecl->getNumParams() == 0) 15766 return SemaRef.Diag(FnDecl->getLocation(), 15767 diag::err_operator_new_delete_too_few_parameters) 15768 << FnDecl->getDeclName(); 15769 15770 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15771 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15772 // The operator is valid on any address space for OpenCL. 15773 // Drop address space from actual and expected first parameter types. 15774 if (const auto *PtrTy = 15775 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15776 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15777 15778 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15779 ExpectedFirstParamType = 15780 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15781 } 15782 15783 // Check that the first parameter type is what we expect. 15784 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15785 ExpectedFirstParamType) { 15786 // The first parameter type is not allowed to be dependent. As a tentative 15787 // DR resolution, we allow a dependent parameter type if it is the right 15788 // type anyway, to allow destroying operator delete in class templates. 15789 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15790 ? DependentParamTypeDiag 15791 : InvalidParamTypeDiag) 15792 << FnDecl->getDeclName() << ExpectedFirstParamType; 15793 } 15794 15795 return false; 15796 } 15797 15798 static bool 15799 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15800 // C++ [basic.stc.dynamic.allocation]p1: 15801 // A program is ill-formed if an allocation function is declared in a 15802 // namespace scope other than global scope or declared static in global 15803 // scope. 15804 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15805 return true; 15806 15807 CanQualType SizeTy = 15808 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15809 15810 // C++ [basic.stc.dynamic.allocation]p1: 15811 // The return type shall be void*. The first parameter shall have type 15812 // std::size_t. 15813 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15814 SizeTy, 15815 diag::err_operator_new_dependent_param_type, 15816 diag::err_operator_new_param_type)) 15817 return true; 15818 15819 // C++ [basic.stc.dynamic.allocation]p1: 15820 // The first parameter shall not have an associated default argument. 15821 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15822 return SemaRef.Diag(FnDecl->getLocation(), 15823 diag::err_operator_new_default_arg) 15824 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15825 15826 return false; 15827 } 15828 15829 static bool 15830 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15831 // C++ [basic.stc.dynamic.deallocation]p1: 15832 // A program is ill-formed if deallocation functions are declared in a 15833 // namespace scope other than global scope or declared static in global 15834 // scope. 15835 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15836 return true; 15837 15838 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15839 15840 // C++ P0722: 15841 // Within a class C, the first parameter of a destroying operator delete 15842 // shall be of type C *. The first parameter of any other deallocation 15843 // function shall be of type void *. 15844 CanQualType ExpectedFirstParamType = 15845 MD && MD->isDestroyingOperatorDelete() 15846 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15847 SemaRef.Context.getRecordType(MD->getParent()))) 15848 : SemaRef.Context.VoidPtrTy; 15849 15850 // C++ [basic.stc.dynamic.deallocation]p2: 15851 // Each deallocation function shall return void 15852 if (CheckOperatorNewDeleteTypes( 15853 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15854 diag::err_operator_delete_dependent_param_type, 15855 diag::err_operator_delete_param_type)) 15856 return true; 15857 15858 // C++ P0722: 15859 // A destroying operator delete shall be a usual deallocation function. 15860 if (MD && !MD->getParent()->isDependentContext() && 15861 MD->isDestroyingOperatorDelete() && 15862 !SemaRef.isUsualDeallocationFunction(MD)) { 15863 SemaRef.Diag(MD->getLocation(), 15864 diag::err_destroying_operator_delete_not_usual); 15865 return true; 15866 } 15867 15868 return false; 15869 } 15870 15871 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15872 /// of this overloaded operator is well-formed. If so, returns false; 15873 /// otherwise, emits appropriate diagnostics and returns true. 15874 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15875 assert(FnDecl && FnDecl->isOverloadedOperator() && 15876 "Expected an overloaded operator declaration"); 15877 15878 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15879 15880 // C++ [over.oper]p5: 15881 // The allocation and deallocation functions, operator new, 15882 // operator new[], operator delete and operator delete[], are 15883 // described completely in 3.7.3. The attributes and restrictions 15884 // found in the rest of this subclause do not apply to them unless 15885 // explicitly stated in 3.7.3. 15886 if (Op == OO_Delete || Op == OO_Array_Delete) 15887 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15888 15889 if (Op == OO_New || Op == OO_Array_New) 15890 return CheckOperatorNewDeclaration(*this, FnDecl); 15891 15892 // C++ [over.oper]p6: 15893 // An operator function shall either be a non-static member 15894 // function or be a non-member function and have at least one 15895 // parameter whose type is a class, a reference to a class, an 15896 // enumeration, or a reference to an enumeration. 15897 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15898 if (MethodDecl->isStatic()) 15899 return Diag(FnDecl->getLocation(), 15900 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15901 } else { 15902 bool ClassOrEnumParam = false; 15903 for (auto Param : FnDecl->parameters()) { 15904 QualType ParamType = Param->getType().getNonReferenceType(); 15905 if (ParamType->isDependentType() || ParamType->isRecordType() || 15906 ParamType->isEnumeralType()) { 15907 ClassOrEnumParam = true; 15908 break; 15909 } 15910 } 15911 15912 if (!ClassOrEnumParam) 15913 return Diag(FnDecl->getLocation(), 15914 diag::err_operator_overload_needs_class_or_enum) 15915 << FnDecl->getDeclName(); 15916 } 15917 15918 // C++ [over.oper]p8: 15919 // An operator function cannot have default arguments (8.3.6), 15920 // except where explicitly stated below. 15921 // 15922 // Only the function-call operator (C++ [over.call]p1) and the subscript 15923 // operator (CWG2507) allow default arguments. 15924 if (Op != OO_Call) { 15925 ParmVarDecl *FirstDefaultedParam = nullptr; 15926 for (auto Param : FnDecl->parameters()) { 15927 if (Param->hasDefaultArg()) { 15928 FirstDefaultedParam = Param; 15929 break; 15930 } 15931 } 15932 if (FirstDefaultedParam) { 15933 if (Op == OO_Subscript) { 15934 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b 15935 ? diag::ext_subscript_overload 15936 : diag::error_subscript_overload) 15937 << FnDecl->getDeclName() << 1 15938 << FirstDefaultedParam->getDefaultArgRange(); 15939 } else { 15940 return Diag(FirstDefaultedParam->getLocation(), 15941 diag::err_operator_overload_default_arg) 15942 << FnDecl->getDeclName() 15943 << FirstDefaultedParam->getDefaultArgRange(); 15944 } 15945 } 15946 } 15947 15948 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15949 { false, false, false } 15950 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15951 , { Unary, Binary, MemberOnly } 15952 #include "clang/Basic/OperatorKinds.def" 15953 }; 15954 15955 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15956 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15957 bool MustBeMemberOperator = OperatorUses[Op][2]; 15958 15959 // C++ [over.oper]p8: 15960 // [...] Operator functions cannot have more or fewer parameters 15961 // than the number required for the corresponding operator, as 15962 // described in the rest of this subclause. 15963 unsigned NumParams = FnDecl->getNumParams() 15964 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15965 if (Op != OO_Call && Op != OO_Subscript && 15966 ((NumParams == 1 && !CanBeUnaryOperator) || 15967 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) || 15968 (NumParams > 2))) { 15969 // We have the wrong number of parameters. 15970 unsigned ErrorKind; 15971 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15972 ErrorKind = 2; // 2 -> unary or binary. 15973 } else if (CanBeUnaryOperator) { 15974 ErrorKind = 0; // 0 -> unary 15975 } else { 15976 assert(CanBeBinaryOperator && 15977 "All non-call overloaded operators are unary or binary!"); 15978 ErrorKind = 1; // 1 -> binary 15979 } 15980 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15981 << FnDecl->getDeclName() << NumParams << ErrorKind; 15982 } 15983 15984 if (Op == OO_Subscript && NumParams != 2) { 15985 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b 15986 ? diag::ext_subscript_overload 15987 : diag::error_subscript_overload) 15988 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2); 15989 } 15990 15991 // Overloaded operators other than operator() and operator[] cannot be 15992 // variadic. 15993 if (Op != OO_Call && 15994 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15995 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15996 << FnDecl->getDeclName(); 15997 } 15998 15999 // Some operators must be non-static member functions. 16000 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 16001 return Diag(FnDecl->getLocation(), 16002 diag::err_operator_overload_must_be_member) 16003 << FnDecl->getDeclName(); 16004 } 16005 16006 // C++ [over.inc]p1: 16007 // The user-defined function called operator++ implements the 16008 // prefix and postfix ++ operator. If this function is a member 16009 // function with no parameters, or a non-member function with one 16010 // parameter of class or enumeration type, it defines the prefix 16011 // increment operator ++ for objects of that type. If the function 16012 // is a member function with one parameter (which shall be of type 16013 // int) or a non-member function with two parameters (the second 16014 // of which shall be of type int), it defines the postfix 16015 // increment operator ++ for objects of that type. 16016 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 16017 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 16018 QualType ParamType = LastParam->getType(); 16019 16020 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 16021 !ParamType->isDependentType()) 16022 return Diag(LastParam->getLocation(), 16023 diag::err_operator_overload_post_incdec_must_be_int) 16024 << LastParam->getType() << (Op == OO_MinusMinus); 16025 } 16026 16027 return false; 16028 } 16029 16030 static bool 16031 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 16032 FunctionTemplateDecl *TpDecl) { 16033 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 16034 16035 // Must have one or two template parameters. 16036 if (TemplateParams->size() == 1) { 16037 NonTypeTemplateParmDecl *PmDecl = 16038 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 16039 16040 // The template parameter must be a char parameter pack. 16041 if (PmDecl && PmDecl->isTemplateParameterPack() && 16042 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 16043 return false; 16044 16045 // C++20 [over.literal]p5: 16046 // A string literal operator template is a literal operator template 16047 // whose template-parameter-list comprises a single non-type 16048 // template-parameter of class type. 16049 // 16050 // As a DR resolution, we also allow placeholders for deduced class 16051 // template specializations. 16052 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 16053 !PmDecl->isTemplateParameterPack() && 16054 (PmDecl->getType()->isRecordType() || 16055 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 16056 return false; 16057 } else if (TemplateParams->size() == 2) { 16058 TemplateTypeParmDecl *PmType = 16059 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 16060 NonTypeTemplateParmDecl *PmArgs = 16061 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 16062 16063 // The second template parameter must be a parameter pack with the 16064 // first template parameter as its type. 16065 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 16066 PmArgs->isTemplateParameterPack()) { 16067 const TemplateTypeParmType *TArgs = 16068 PmArgs->getType()->getAs<TemplateTypeParmType>(); 16069 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 16070 TArgs->getIndex() == PmType->getIndex()) { 16071 if (!SemaRef.inTemplateInstantiation()) 16072 SemaRef.Diag(TpDecl->getLocation(), 16073 diag::ext_string_literal_operator_template); 16074 return false; 16075 } 16076 } 16077 } 16078 16079 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 16080 diag::err_literal_operator_template) 16081 << TpDecl->getTemplateParameters()->getSourceRange(); 16082 return true; 16083 } 16084 16085 /// CheckLiteralOperatorDeclaration - Check whether the declaration 16086 /// of this literal operator function is well-formed. If so, returns 16087 /// false; otherwise, emits appropriate diagnostics and returns true. 16088 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 16089 if (isa<CXXMethodDecl>(FnDecl)) { 16090 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 16091 << FnDecl->getDeclName(); 16092 return true; 16093 } 16094 16095 if (FnDecl->isExternC()) { 16096 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 16097 if (const LinkageSpecDecl *LSD = 16098 FnDecl->getDeclContext()->getExternCContext()) 16099 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 16100 return true; 16101 } 16102 16103 // This might be the definition of a literal operator template. 16104 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 16105 16106 // This might be a specialization of a literal operator template. 16107 if (!TpDecl) 16108 TpDecl = FnDecl->getPrimaryTemplate(); 16109 16110 // template <char...> type operator "" name() and 16111 // template <class T, T...> type operator "" name() are the only valid 16112 // template signatures, and the only valid signatures with no parameters. 16113 // 16114 // C++20 also allows template <SomeClass T> type operator "" name(). 16115 if (TpDecl) { 16116 if (FnDecl->param_size() != 0) { 16117 Diag(FnDecl->getLocation(), 16118 diag::err_literal_operator_template_with_params); 16119 return true; 16120 } 16121 16122 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 16123 return true; 16124 16125 } else if (FnDecl->param_size() == 1) { 16126 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 16127 16128 QualType ParamType = Param->getType().getUnqualifiedType(); 16129 16130 // Only unsigned long long int, long double, any character type, and const 16131 // char * are allowed as the only parameters. 16132 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 16133 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 16134 Context.hasSameType(ParamType, Context.CharTy) || 16135 Context.hasSameType(ParamType, Context.WideCharTy) || 16136 Context.hasSameType(ParamType, Context.Char8Ty) || 16137 Context.hasSameType(ParamType, Context.Char16Ty) || 16138 Context.hasSameType(ParamType, Context.Char32Ty)) { 16139 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 16140 QualType InnerType = Ptr->getPointeeType(); 16141 16142 // Pointer parameter must be a const char *. 16143 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16144 Context.CharTy) && 16145 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16146 Diag(Param->getSourceRange().getBegin(), 16147 diag::err_literal_operator_param) 16148 << ParamType << "'const char *'" << Param->getSourceRange(); 16149 return true; 16150 } 16151 16152 } else if (ParamType->isRealFloatingType()) { 16153 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16154 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16155 return true; 16156 16157 } else if (ParamType->isIntegerType()) { 16158 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16159 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16160 return true; 16161 16162 } else { 16163 Diag(Param->getSourceRange().getBegin(), 16164 diag::err_literal_operator_invalid_param) 16165 << ParamType << Param->getSourceRange(); 16166 return true; 16167 } 16168 16169 } else if (FnDecl->param_size() == 2) { 16170 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16171 16172 // First, verify that the first parameter is correct. 16173 16174 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16175 16176 // Two parameter function must have a pointer to const as a 16177 // first parameter; let's strip those qualifiers. 16178 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16179 16180 if (!PT) { 16181 Diag((*Param)->getSourceRange().getBegin(), 16182 diag::err_literal_operator_param) 16183 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16184 return true; 16185 } 16186 16187 QualType PointeeType = PT->getPointeeType(); 16188 // First parameter must be const 16189 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16190 Diag((*Param)->getSourceRange().getBegin(), 16191 diag::err_literal_operator_param) 16192 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16193 return true; 16194 } 16195 16196 QualType InnerType = PointeeType.getUnqualifiedType(); 16197 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16198 // const char32_t* are allowed as the first parameter to a two-parameter 16199 // function 16200 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16201 Context.hasSameType(InnerType, Context.WideCharTy) || 16202 Context.hasSameType(InnerType, Context.Char8Ty) || 16203 Context.hasSameType(InnerType, Context.Char16Ty) || 16204 Context.hasSameType(InnerType, Context.Char32Ty))) { 16205 Diag((*Param)->getSourceRange().getBegin(), 16206 diag::err_literal_operator_param) 16207 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16208 return true; 16209 } 16210 16211 // Move on to the second and final parameter. 16212 ++Param; 16213 16214 // The second parameter must be a std::size_t. 16215 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16216 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16217 Diag((*Param)->getSourceRange().getBegin(), 16218 diag::err_literal_operator_param) 16219 << SecondParamType << Context.getSizeType() 16220 << (*Param)->getSourceRange(); 16221 return true; 16222 } 16223 } else { 16224 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16225 return true; 16226 } 16227 16228 // Parameters are good. 16229 16230 // A parameter-declaration-clause containing a default argument is not 16231 // equivalent to any of the permitted forms. 16232 for (auto Param : FnDecl->parameters()) { 16233 if (Param->hasDefaultArg()) { 16234 Diag(Param->getDefaultArgRange().getBegin(), 16235 diag::err_literal_operator_default_argument) 16236 << Param->getDefaultArgRange(); 16237 break; 16238 } 16239 } 16240 16241 StringRef LiteralName 16242 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16243 if (LiteralName[0] != '_' && 16244 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16245 // C++11 [usrlit.suffix]p1: 16246 // Literal suffix identifiers that do not start with an underscore 16247 // are reserved for future standardization. 16248 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16249 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16250 } 16251 16252 return false; 16253 } 16254 16255 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16256 /// linkage specification, including the language and (if present) 16257 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16258 /// language string literal. LBraceLoc, if valid, provides the location of 16259 /// the '{' brace. Otherwise, this linkage specification does not 16260 /// have any braces. 16261 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16262 Expr *LangStr, 16263 SourceLocation LBraceLoc) { 16264 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16265 if (!Lit->isAscii()) { 16266 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16267 << LangStr->getSourceRange(); 16268 return nullptr; 16269 } 16270 16271 StringRef Lang = Lit->getString(); 16272 LinkageSpecDecl::LanguageIDs Language; 16273 if (Lang == "C") 16274 Language = LinkageSpecDecl::lang_c; 16275 else if (Lang == "C++") 16276 Language = LinkageSpecDecl::lang_cxx; 16277 else { 16278 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16279 << LangStr->getSourceRange(); 16280 return nullptr; 16281 } 16282 16283 // FIXME: Add all the various semantics of linkage specifications 16284 16285 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16286 LangStr->getExprLoc(), Language, 16287 LBraceLoc.isValid()); 16288 16289 /// C++ [module.unit]p7.2.3 16290 /// - Otherwise, if the declaration 16291 /// - ... 16292 /// - ... 16293 /// - appears within a linkage-specification, 16294 /// it is attached to the global module. 16295 /// 16296 /// If the declaration is already in global module fragment, we don't 16297 /// need to attach it again. 16298 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) { 16299 Module *GlobalModule = 16300 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true); 16301 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16302 D->setLocalOwningModule(GlobalModule); 16303 } 16304 16305 CurContext->addDecl(D); 16306 PushDeclContext(S, D); 16307 return D; 16308 } 16309 16310 /// ActOnFinishLinkageSpecification - Complete the definition of 16311 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16312 /// valid, it's the position of the closing '}' brace in a linkage 16313 /// specification that uses braces. 16314 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16315 Decl *LinkageSpec, 16316 SourceLocation RBraceLoc) { 16317 if (RBraceLoc.isValid()) { 16318 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16319 LSDecl->setRBraceLoc(RBraceLoc); 16320 } 16321 16322 // If the current module doesn't has Parent, it implies that the 16323 // LinkageSpec isn't in the module created by itself. So we don't 16324 // need to pop it. 16325 if (getLangOpts().CPlusPlusModules && getCurrentModule() && 16326 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent) 16327 PopGlobalModuleFragment(); 16328 16329 PopDeclContext(); 16330 return LinkageSpec; 16331 } 16332 16333 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16334 const ParsedAttributesView &AttrList, 16335 SourceLocation SemiLoc) { 16336 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16337 // Attribute declarations appertain to empty declaration so we handle 16338 // them here. 16339 ProcessDeclAttributeList(S, ED, AttrList); 16340 16341 CurContext->addDecl(ED); 16342 return ED; 16343 } 16344 16345 /// Perform semantic analysis for the variable declaration that 16346 /// occurs within a C++ catch clause, returning the newly-created 16347 /// variable. 16348 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16349 TypeSourceInfo *TInfo, 16350 SourceLocation StartLoc, 16351 SourceLocation Loc, 16352 IdentifierInfo *Name) { 16353 bool Invalid = false; 16354 QualType ExDeclType = TInfo->getType(); 16355 16356 // Arrays and functions decay. 16357 if (ExDeclType->isArrayType()) 16358 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16359 else if (ExDeclType->isFunctionType()) 16360 ExDeclType = Context.getPointerType(ExDeclType); 16361 16362 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16363 // The exception-declaration shall not denote a pointer or reference to an 16364 // incomplete type, other than [cv] void*. 16365 // N2844 forbids rvalue references. 16366 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16367 Diag(Loc, diag::err_catch_rvalue_ref); 16368 Invalid = true; 16369 } 16370 16371 if (ExDeclType->isVariablyModifiedType()) { 16372 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16373 Invalid = true; 16374 } 16375 16376 QualType BaseType = ExDeclType; 16377 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16378 unsigned DK = diag::err_catch_incomplete; 16379 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16380 BaseType = Ptr->getPointeeType(); 16381 Mode = 1; 16382 DK = diag::err_catch_incomplete_ptr; 16383 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16384 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16385 BaseType = Ref->getPointeeType(); 16386 Mode = 2; 16387 DK = diag::err_catch_incomplete_ref; 16388 } 16389 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16390 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16391 Invalid = true; 16392 16393 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16394 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16395 Invalid = true; 16396 } 16397 16398 if (!Invalid && !ExDeclType->isDependentType() && 16399 RequireNonAbstractType(Loc, ExDeclType, 16400 diag::err_abstract_type_in_decl, 16401 AbstractVariableType)) 16402 Invalid = true; 16403 16404 // Only the non-fragile NeXT runtime currently supports C++ catches 16405 // of ObjC types, and no runtime supports catching ObjC types by value. 16406 if (!Invalid && getLangOpts().ObjC) { 16407 QualType T = ExDeclType; 16408 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16409 T = RT->getPointeeType(); 16410 16411 if (T->isObjCObjectType()) { 16412 Diag(Loc, diag::err_objc_object_catch); 16413 Invalid = true; 16414 } else if (T->isObjCObjectPointerType()) { 16415 // FIXME: should this be a test for macosx-fragile specifically? 16416 if (getLangOpts().ObjCRuntime.isFragile()) 16417 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16418 } 16419 } 16420 16421 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16422 ExDeclType, TInfo, SC_None); 16423 ExDecl->setExceptionVariable(true); 16424 16425 // In ARC, infer 'retaining' for variables of retainable type. 16426 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16427 Invalid = true; 16428 16429 if (!Invalid && !ExDeclType->isDependentType()) { 16430 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16431 // Insulate this from anything else we might currently be parsing. 16432 EnterExpressionEvaluationContext scope( 16433 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16434 16435 // C++ [except.handle]p16: 16436 // The object declared in an exception-declaration or, if the 16437 // exception-declaration does not specify a name, a temporary (12.2) is 16438 // copy-initialized (8.5) from the exception object. [...] 16439 // The object is destroyed when the handler exits, after the destruction 16440 // of any automatic objects initialized within the handler. 16441 // 16442 // We just pretend to initialize the object with itself, then make sure 16443 // it can be destroyed later. 16444 QualType initType = Context.getExceptionObjectType(ExDeclType); 16445 16446 InitializedEntity entity = 16447 InitializedEntity::InitializeVariable(ExDecl); 16448 InitializationKind initKind = 16449 InitializationKind::CreateCopy(Loc, SourceLocation()); 16450 16451 Expr *opaqueValue = 16452 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16453 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16454 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16455 if (result.isInvalid()) 16456 Invalid = true; 16457 else { 16458 // If the constructor used was non-trivial, set this as the 16459 // "initializer". 16460 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16461 if (!construct->getConstructor()->isTrivial()) { 16462 Expr *init = MaybeCreateExprWithCleanups(construct); 16463 ExDecl->setInit(init); 16464 } 16465 16466 // And make sure it's destructable. 16467 FinalizeVarWithDestructor(ExDecl, recordType); 16468 } 16469 } 16470 } 16471 16472 if (Invalid) 16473 ExDecl->setInvalidDecl(); 16474 16475 return ExDecl; 16476 } 16477 16478 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16479 /// handler. 16480 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16481 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16482 bool Invalid = D.isInvalidType(); 16483 16484 // Check for unexpanded parameter packs. 16485 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16486 UPPC_ExceptionType)) { 16487 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16488 D.getIdentifierLoc()); 16489 Invalid = true; 16490 } 16491 16492 IdentifierInfo *II = D.getIdentifier(); 16493 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16494 LookupOrdinaryName, 16495 ForVisibleRedeclaration)) { 16496 // The scope should be freshly made just for us. There is just no way 16497 // it contains any previous declaration, except for function parameters in 16498 // a function-try-block's catch statement. 16499 assert(!S->isDeclScope(PrevDecl)); 16500 if (isDeclInScope(PrevDecl, CurContext, S)) { 16501 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16502 << D.getIdentifier(); 16503 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16504 Invalid = true; 16505 } else if (PrevDecl->isTemplateParameter()) 16506 // Maybe we will complain about the shadowed template parameter. 16507 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16508 } 16509 16510 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16511 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16512 << D.getCXXScopeSpec().getRange(); 16513 Invalid = true; 16514 } 16515 16516 VarDecl *ExDecl = BuildExceptionDeclaration( 16517 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16518 if (Invalid) 16519 ExDecl->setInvalidDecl(); 16520 16521 // Add the exception declaration into this scope. 16522 if (II) 16523 PushOnScopeChains(ExDecl, S); 16524 else 16525 CurContext->addDecl(ExDecl); 16526 16527 ProcessDeclAttributes(S, ExDecl, D); 16528 return ExDecl; 16529 } 16530 16531 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16532 Expr *AssertExpr, 16533 Expr *AssertMessageExpr, 16534 SourceLocation RParenLoc) { 16535 StringLiteral *AssertMessage = 16536 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16537 16538 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16539 return nullptr; 16540 16541 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16542 AssertMessage, RParenLoc, false); 16543 } 16544 16545 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16546 Expr *AssertExpr, 16547 StringLiteral *AssertMessage, 16548 SourceLocation RParenLoc, 16549 bool Failed) { 16550 assert(AssertExpr != nullptr && "Expected non-null condition"); 16551 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16552 !Failed) { 16553 // In a static_assert-declaration, the constant-expression shall be a 16554 // constant expression that can be contextually converted to bool. 16555 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16556 if (Converted.isInvalid()) 16557 Failed = true; 16558 16559 ExprResult FullAssertExpr = 16560 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16561 /*DiscardedValue*/ false, 16562 /*IsConstexpr*/ true); 16563 if (FullAssertExpr.isInvalid()) 16564 Failed = true; 16565 else 16566 AssertExpr = FullAssertExpr.get(); 16567 16568 llvm::APSInt Cond; 16569 if (!Failed && VerifyIntegerConstantExpression( 16570 AssertExpr, &Cond, 16571 diag::err_static_assert_expression_is_not_constant) 16572 .isInvalid()) 16573 Failed = true; 16574 16575 if (!Failed && !Cond) { 16576 SmallString<256> MsgBuffer; 16577 llvm::raw_svector_ostream Msg(MsgBuffer); 16578 if (AssertMessage) 16579 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16580 16581 Expr *InnerCond = nullptr; 16582 std::string InnerCondDescription; 16583 std::tie(InnerCond, InnerCondDescription) = 16584 findFailedBooleanCondition(Converted.get()); 16585 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16586 // Drill down into concept specialization expressions to see why they 16587 // weren't satisfied. 16588 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16589 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16590 ConstraintSatisfaction Satisfaction; 16591 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16592 DiagnoseUnsatisfiedConstraint(Satisfaction); 16593 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16594 && !isa<IntegerLiteral>(InnerCond)) { 16595 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16596 << InnerCondDescription << !AssertMessage 16597 << Msg.str() << InnerCond->getSourceRange(); 16598 } else { 16599 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16600 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16601 } 16602 Failed = true; 16603 } 16604 } else { 16605 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16606 /*DiscardedValue*/false, 16607 /*IsConstexpr*/true); 16608 if (FullAssertExpr.isInvalid()) 16609 Failed = true; 16610 else 16611 AssertExpr = FullAssertExpr.get(); 16612 } 16613 16614 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16615 AssertExpr, AssertMessage, RParenLoc, 16616 Failed); 16617 16618 CurContext->addDecl(Decl); 16619 return Decl; 16620 } 16621 16622 /// Perform semantic analysis of the given friend type declaration. 16623 /// 16624 /// \returns A friend declaration that. 16625 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16626 SourceLocation FriendLoc, 16627 TypeSourceInfo *TSInfo) { 16628 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16629 16630 QualType T = TSInfo->getType(); 16631 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16632 16633 // C++03 [class.friend]p2: 16634 // An elaborated-type-specifier shall be used in a friend declaration 16635 // for a class.* 16636 // 16637 // * The class-key of the elaborated-type-specifier is required. 16638 if (!CodeSynthesisContexts.empty()) { 16639 // Do not complain about the form of friend template types during any kind 16640 // of code synthesis. For template instantiation, we will have complained 16641 // when the template was defined. 16642 } else { 16643 if (!T->isElaboratedTypeSpecifier()) { 16644 // If we evaluated the type to a record type, suggest putting 16645 // a tag in front. 16646 if (const RecordType *RT = T->getAs<RecordType>()) { 16647 RecordDecl *RD = RT->getDecl(); 16648 16649 SmallString<16> InsertionText(" "); 16650 InsertionText += RD->getKindName(); 16651 16652 Diag(TypeRange.getBegin(), 16653 getLangOpts().CPlusPlus11 ? 16654 diag::warn_cxx98_compat_unelaborated_friend_type : 16655 diag::ext_unelaborated_friend_type) 16656 << (unsigned) RD->getTagKind() 16657 << T 16658 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16659 InsertionText); 16660 } else { 16661 Diag(FriendLoc, 16662 getLangOpts().CPlusPlus11 ? 16663 diag::warn_cxx98_compat_nonclass_type_friend : 16664 diag::ext_nonclass_type_friend) 16665 << T 16666 << TypeRange; 16667 } 16668 } else if (T->getAs<EnumType>()) { 16669 Diag(FriendLoc, 16670 getLangOpts().CPlusPlus11 ? 16671 diag::warn_cxx98_compat_enum_friend : 16672 diag::ext_enum_friend) 16673 << T 16674 << TypeRange; 16675 } 16676 16677 // C++11 [class.friend]p3: 16678 // A friend declaration that does not declare a function shall have one 16679 // of the following forms: 16680 // friend elaborated-type-specifier ; 16681 // friend simple-type-specifier ; 16682 // friend typename-specifier ; 16683 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16684 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16685 } 16686 16687 // If the type specifier in a friend declaration designates a (possibly 16688 // cv-qualified) class type, that class is declared as a friend; otherwise, 16689 // the friend declaration is ignored. 16690 return FriendDecl::Create(Context, CurContext, 16691 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16692 FriendLoc); 16693 } 16694 16695 /// Handle a friend tag declaration where the scope specifier was 16696 /// templated. 16697 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16698 unsigned TagSpec, SourceLocation TagLoc, 16699 CXXScopeSpec &SS, IdentifierInfo *Name, 16700 SourceLocation NameLoc, 16701 const ParsedAttributesView &Attr, 16702 MultiTemplateParamsArg TempParamLists) { 16703 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16704 16705 bool IsMemberSpecialization = false; 16706 bool Invalid = false; 16707 16708 if (TemplateParameterList *TemplateParams = 16709 MatchTemplateParametersToScopeSpecifier( 16710 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16711 IsMemberSpecialization, Invalid)) { 16712 if (TemplateParams->size() > 0) { 16713 // This is a declaration of a class template. 16714 if (Invalid) 16715 return nullptr; 16716 16717 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16718 NameLoc, Attr, TemplateParams, AS_public, 16719 /*ModulePrivateLoc=*/SourceLocation(), 16720 FriendLoc, TempParamLists.size() - 1, 16721 TempParamLists.data()).get(); 16722 } else { 16723 // The "template<>" header is extraneous. 16724 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16725 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16726 IsMemberSpecialization = true; 16727 } 16728 } 16729 16730 if (Invalid) return nullptr; 16731 16732 bool isAllExplicitSpecializations = true; 16733 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16734 if (TempParamLists[I]->size()) { 16735 isAllExplicitSpecializations = false; 16736 break; 16737 } 16738 } 16739 16740 // FIXME: don't ignore attributes. 16741 16742 // If it's explicit specializations all the way down, just forget 16743 // about the template header and build an appropriate non-templated 16744 // friend. TODO: for source fidelity, remember the headers. 16745 if (isAllExplicitSpecializations) { 16746 if (SS.isEmpty()) { 16747 bool Owned = false; 16748 bool IsDependent = false; 16749 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16750 Attr, AS_public, 16751 /*ModulePrivateLoc=*/SourceLocation(), 16752 MultiTemplateParamsArg(), Owned, IsDependent, 16753 /*ScopedEnumKWLoc=*/SourceLocation(), 16754 /*ScopedEnumUsesClassTag=*/false, 16755 /*UnderlyingType=*/TypeResult(), 16756 /*IsTypeSpecifier=*/false, 16757 /*IsTemplateParamOrArg=*/false); 16758 } 16759 16760 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16761 ElaboratedTypeKeyword Keyword 16762 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16763 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16764 *Name, NameLoc); 16765 if (T.isNull()) 16766 return nullptr; 16767 16768 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16769 if (isa<DependentNameType>(T)) { 16770 DependentNameTypeLoc TL = 16771 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16772 TL.setElaboratedKeywordLoc(TagLoc); 16773 TL.setQualifierLoc(QualifierLoc); 16774 TL.setNameLoc(NameLoc); 16775 } else { 16776 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16777 TL.setElaboratedKeywordLoc(TagLoc); 16778 TL.setQualifierLoc(QualifierLoc); 16779 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16780 } 16781 16782 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16783 TSI, FriendLoc, TempParamLists); 16784 Friend->setAccess(AS_public); 16785 CurContext->addDecl(Friend); 16786 return Friend; 16787 } 16788 16789 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16790 16791 16792 16793 // Handle the case of a templated-scope friend class. e.g. 16794 // template <class T> class A<T>::B; 16795 // FIXME: we don't support these right now. 16796 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16797 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16798 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16799 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16800 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16801 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16802 TL.setElaboratedKeywordLoc(TagLoc); 16803 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16804 TL.setNameLoc(NameLoc); 16805 16806 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16807 TSI, FriendLoc, TempParamLists); 16808 Friend->setAccess(AS_public); 16809 Friend->setUnsupportedFriend(true); 16810 CurContext->addDecl(Friend); 16811 return Friend; 16812 } 16813 16814 /// Handle a friend type declaration. This works in tandem with 16815 /// ActOnTag. 16816 /// 16817 /// Notes on friend class templates: 16818 /// 16819 /// We generally treat friend class declarations as if they were 16820 /// declaring a class. So, for example, the elaborated type specifier 16821 /// in a friend declaration is required to obey the restrictions of a 16822 /// class-head (i.e. no typedefs in the scope chain), template 16823 /// parameters are required to match up with simple template-ids, &c. 16824 /// However, unlike when declaring a template specialization, it's 16825 /// okay to refer to a template specialization without an empty 16826 /// template parameter declaration, e.g. 16827 /// friend class A<T>::B<unsigned>; 16828 /// We permit this as a special case; if there are any template 16829 /// parameters present at all, require proper matching, i.e. 16830 /// template <> template \<class T> friend class A<int>::B; 16831 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16832 MultiTemplateParamsArg TempParams) { 16833 SourceLocation Loc = DS.getBeginLoc(); 16834 16835 assert(DS.isFriendSpecified()); 16836 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16837 16838 // C++ [class.friend]p3: 16839 // A friend declaration that does not declare a function shall have one of 16840 // the following forms: 16841 // friend elaborated-type-specifier ; 16842 // friend simple-type-specifier ; 16843 // friend typename-specifier ; 16844 // 16845 // Any declaration with a type qualifier does not have that form. (It's 16846 // legal to specify a qualified type as a friend, you just can't write the 16847 // keywords.) 16848 if (DS.getTypeQualifiers()) { 16849 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16850 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16851 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16852 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16853 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16854 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16855 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16856 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16857 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16858 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16859 } 16860 16861 // Try to convert the decl specifier to a type. This works for 16862 // friend templates because ActOnTag never produces a ClassTemplateDecl 16863 // for a TUK_Friend. 16864 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16865 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16866 QualType T = TSI->getType(); 16867 if (TheDeclarator.isInvalidType()) 16868 return nullptr; 16869 16870 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16871 return nullptr; 16872 16873 // This is definitely an error in C++98. It's probably meant to 16874 // be forbidden in C++0x, too, but the specification is just 16875 // poorly written. 16876 // 16877 // The problem is with declarations like the following: 16878 // template <T> friend A<T>::foo; 16879 // where deciding whether a class C is a friend or not now hinges 16880 // on whether there exists an instantiation of A that causes 16881 // 'foo' to equal C. There are restrictions on class-heads 16882 // (which we declare (by fiat) elaborated friend declarations to 16883 // be) that makes this tractable. 16884 // 16885 // FIXME: handle "template <> friend class A<T>;", which 16886 // is possibly well-formed? Who even knows? 16887 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16888 Diag(Loc, diag::err_tagless_friend_type_template) 16889 << DS.getSourceRange(); 16890 return nullptr; 16891 } 16892 16893 // C++98 [class.friend]p1: A friend of a class is a function 16894 // or class that is not a member of the class . . . 16895 // This is fixed in DR77, which just barely didn't make the C++03 16896 // deadline. It's also a very silly restriction that seriously 16897 // affects inner classes and which nobody else seems to implement; 16898 // thus we never diagnose it, not even in -pedantic. 16899 // 16900 // But note that we could warn about it: it's always useless to 16901 // friend one of your own members (it's not, however, worthless to 16902 // friend a member of an arbitrary specialization of your template). 16903 16904 Decl *D; 16905 if (!TempParams.empty()) 16906 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16907 TempParams, 16908 TSI, 16909 DS.getFriendSpecLoc()); 16910 else 16911 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16912 16913 if (!D) 16914 return nullptr; 16915 16916 D->setAccess(AS_public); 16917 CurContext->addDecl(D); 16918 16919 return D; 16920 } 16921 16922 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16923 MultiTemplateParamsArg TemplateParams) { 16924 const DeclSpec &DS = D.getDeclSpec(); 16925 16926 assert(DS.isFriendSpecified()); 16927 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16928 16929 SourceLocation Loc = D.getIdentifierLoc(); 16930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16931 16932 // C++ [class.friend]p1 16933 // A friend of a class is a function or class.... 16934 // Note that this sees through typedefs, which is intended. 16935 // It *doesn't* see through dependent types, which is correct 16936 // according to [temp.arg.type]p3: 16937 // If a declaration acquires a function type through a 16938 // type dependent on a template-parameter and this causes 16939 // a declaration that does not use the syntactic form of a 16940 // function declarator to have a function type, the program 16941 // is ill-formed. 16942 if (!TInfo->getType()->isFunctionType()) { 16943 Diag(Loc, diag::err_unexpected_friend); 16944 16945 // It might be worthwhile to try to recover by creating an 16946 // appropriate declaration. 16947 return nullptr; 16948 } 16949 16950 // C++ [namespace.memdef]p3 16951 // - If a friend declaration in a non-local class first declares a 16952 // class or function, the friend class or function is a member 16953 // of the innermost enclosing namespace. 16954 // - The name of the friend is not found by simple name lookup 16955 // until a matching declaration is provided in that namespace 16956 // scope (either before or after the class declaration granting 16957 // friendship). 16958 // - If a friend function is called, its name may be found by the 16959 // name lookup that considers functions from namespaces and 16960 // classes associated with the types of the function arguments. 16961 // - When looking for a prior declaration of a class or a function 16962 // declared as a friend, scopes outside the innermost enclosing 16963 // namespace scope are not considered. 16964 16965 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16966 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16967 assert(NameInfo.getName()); 16968 16969 // Check for unexpanded parameter packs. 16970 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16971 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16972 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16973 return nullptr; 16974 16975 // The context we found the declaration in, or in which we should 16976 // create the declaration. 16977 DeclContext *DC; 16978 Scope *DCScope = S; 16979 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16980 ForExternalRedeclaration); 16981 16982 // There are five cases here. 16983 // - There's no scope specifier and we're in a local class. Only look 16984 // for functions declared in the immediately-enclosing block scope. 16985 // We recover from invalid scope qualifiers as if they just weren't there. 16986 FunctionDecl *FunctionContainingLocalClass = nullptr; 16987 if ((SS.isInvalid() || !SS.isSet()) && 16988 (FunctionContainingLocalClass = 16989 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16990 // C++11 [class.friend]p11: 16991 // If a friend declaration appears in a local class and the name 16992 // specified is an unqualified name, a prior declaration is 16993 // looked up without considering scopes that are outside the 16994 // innermost enclosing non-class scope. For a friend function 16995 // declaration, if there is no prior declaration, the program is 16996 // ill-formed. 16997 16998 // Find the innermost enclosing non-class scope. This is the block 16999 // scope containing the local class definition (or for a nested class, 17000 // the outer local class). 17001 DCScope = S->getFnParent(); 17002 17003 // Look up the function name in the scope. 17004 Previous.clear(LookupLocalFriendName); 17005 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 17006 17007 if (!Previous.empty()) { 17008 // All possible previous declarations must have the same context: 17009 // either they were declared at block scope or they are members of 17010 // one of the enclosing local classes. 17011 DC = Previous.getRepresentativeDecl()->getDeclContext(); 17012 } else { 17013 // This is ill-formed, but provide the context that we would have 17014 // declared the function in, if we were permitted to, for error recovery. 17015 DC = FunctionContainingLocalClass; 17016 } 17017 adjustContextForLocalExternDecl(DC); 17018 17019 // C++ [class.friend]p6: 17020 // A function can be defined in a friend declaration of a class if and 17021 // only if the class is a non-local class (9.8), the function name is 17022 // unqualified, and the function has namespace scope. 17023 if (D.isFunctionDefinition()) { 17024 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 17025 } 17026 17027 // - There's no scope specifier, in which case we just go to the 17028 // appropriate scope and look for a function or function template 17029 // there as appropriate. 17030 } else if (SS.isInvalid() || !SS.isSet()) { 17031 // C++11 [namespace.memdef]p3: 17032 // If the name in a friend declaration is neither qualified nor 17033 // a template-id and the declaration is a function or an 17034 // elaborated-type-specifier, the lookup to determine whether 17035 // the entity has been previously declared shall not consider 17036 // any scopes outside the innermost enclosing namespace. 17037 bool isTemplateId = 17038 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 17039 17040 // Find the appropriate context according to the above. 17041 DC = CurContext; 17042 17043 // Skip class contexts. If someone can cite chapter and verse 17044 // for this behavior, that would be nice --- it's what GCC and 17045 // EDG do, and it seems like a reasonable intent, but the spec 17046 // really only says that checks for unqualified existing 17047 // declarations should stop at the nearest enclosing namespace, 17048 // not that they should only consider the nearest enclosing 17049 // namespace. 17050 while (DC->isRecord()) 17051 DC = DC->getParent(); 17052 17053 DeclContext *LookupDC = DC->getNonTransparentContext(); 17054 while (true) { 17055 LookupQualifiedName(Previous, LookupDC); 17056 17057 if (!Previous.empty()) { 17058 DC = LookupDC; 17059 break; 17060 } 17061 17062 if (isTemplateId) { 17063 if (isa<TranslationUnitDecl>(LookupDC)) break; 17064 } else { 17065 if (LookupDC->isFileContext()) break; 17066 } 17067 LookupDC = LookupDC->getParent(); 17068 } 17069 17070 DCScope = getScopeForDeclContext(S, DC); 17071 17072 // - There's a non-dependent scope specifier, in which case we 17073 // compute it and do a previous lookup there for a function 17074 // or function template. 17075 } else if (!SS.getScopeRep()->isDependent()) { 17076 DC = computeDeclContext(SS); 17077 if (!DC) return nullptr; 17078 17079 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 17080 17081 LookupQualifiedName(Previous, DC); 17082 17083 // C++ [class.friend]p1: A friend of a class is a function or 17084 // class that is not a member of the class . . . 17085 if (DC->Equals(CurContext)) 17086 Diag(DS.getFriendSpecLoc(), 17087 getLangOpts().CPlusPlus11 ? 17088 diag::warn_cxx98_compat_friend_is_member : 17089 diag::err_friend_is_member); 17090 17091 if (D.isFunctionDefinition()) { 17092 // C++ [class.friend]p6: 17093 // A function can be defined in a friend declaration of a class if and 17094 // only if the class is a non-local class (9.8), the function name is 17095 // unqualified, and the function has namespace scope. 17096 // 17097 // FIXME: We should only do this if the scope specifier names the 17098 // innermost enclosing namespace; otherwise the fixit changes the 17099 // meaning of the code. 17100 SemaDiagnosticBuilder DB 17101 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 17102 17103 DB << SS.getScopeRep(); 17104 if (DC->isFileContext()) 17105 DB << FixItHint::CreateRemoval(SS.getRange()); 17106 SS.clear(); 17107 } 17108 17109 // - There's a scope specifier that does not match any template 17110 // parameter lists, in which case we use some arbitrary context, 17111 // create a method or method template, and wait for instantiation. 17112 // - There's a scope specifier that does match some template 17113 // parameter lists, which we don't handle right now. 17114 } else { 17115 if (D.isFunctionDefinition()) { 17116 // C++ [class.friend]p6: 17117 // A function can be defined in a friend declaration of a class if and 17118 // only if the class is a non-local class (9.8), the function name is 17119 // unqualified, and the function has namespace scope. 17120 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 17121 << SS.getScopeRep(); 17122 } 17123 17124 DC = CurContext; 17125 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 17126 } 17127 17128 if (!DC->isRecord()) { 17129 int DiagArg = -1; 17130 switch (D.getName().getKind()) { 17131 case UnqualifiedIdKind::IK_ConstructorTemplateId: 17132 case UnqualifiedIdKind::IK_ConstructorName: 17133 DiagArg = 0; 17134 break; 17135 case UnqualifiedIdKind::IK_DestructorName: 17136 DiagArg = 1; 17137 break; 17138 case UnqualifiedIdKind::IK_ConversionFunctionId: 17139 DiagArg = 2; 17140 break; 17141 case UnqualifiedIdKind::IK_DeductionGuideName: 17142 DiagArg = 3; 17143 break; 17144 case UnqualifiedIdKind::IK_Identifier: 17145 case UnqualifiedIdKind::IK_ImplicitSelfParam: 17146 case UnqualifiedIdKind::IK_LiteralOperatorId: 17147 case UnqualifiedIdKind::IK_OperatorFunctionId: 17148 case UnqualifiedIdKind::IK_TemplateId: 17149 break; 17150 } 17151 // This implies that it has to be an operator or function. 17152 if (DiagArg >= 0) { 17153 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 17154 return nullptr; 17155 } 17156 } 17157 17158 // FIXME: This is an egregious hack to cope with cases where the scope stack 17159 // does not contain the declaration context, i.e., in an out-of-line 17160 // definition of a class. 17161 Scope FakeDCScope(S, Scope::DeclScope, Diags); 17162 if (!DCScope) { 17163 FakeDCScope.setEntity(DC); 17164 DCScope = &FakeDCScope; 17165 } 17166 17167 bool AddToScope = true; 17168 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17169 TemplateParams, AddToScope); 17170 if (!ND) return nullptr; 17171 17172 assert(ND->getLexicalDeclContext() == CurContext); 17173 17174 // If we performed typo correction, we might have added a scope specifier 17175 // and changed the decl context. 17176 DC = ND->getDeclContext(); 17177 17178 // Add the function declaration to the appropriate lookup tables, 17179 // adjusting the redeclarations list as necessary. We don't 17180 // want to do this yet if the friending class is dependent. 17181 // 17182 // Also update the scope-based lookup if the target context's 17183 // lookup context is in lexical scope. 17184 if (!CurContext->isDependentContext()) { 17185 DC = DC->getRedeclContext(); 17186 DC->makeDeclVisibleInContext(ND); 17187 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17188 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17189 } 17190 17191 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17192 D.getIdentifierLoc(), ND, 17193 DS.getFriendSpecLoc()); 17194 FrD->setAccess(AS_public); 17195 CurContext->addDecl(FrD); 17196 17197 if (ND->isInvalidDecl()) { 17198 FrD->setInvalidDecl(); 17199 } else { 17200 if (DC->isRecord()) CheckFriendAccess(ND); 17201 17202 FunctionDecl *FD; 17203 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17204 FD = FTD->getTemplatedDecl(); 17205 else 17206 FD = cast<FunctionDecl>(ND); 17207 17208 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17209 // default argument expression, that declaration shall be a definition 17210 // and shall be the only declaration of the function or function 17211 // template in the translation unit. 17212 if (functionDeclHasDefaultArgument(FD)) { 17213 // We can't look at FD->getPreviousDecl() because it may not have been set 17214 // if we're in a dependent context. If the function is known to be a 17215 // redeclaration, we will have narrowed Previous down to the right decl. 17216 if (D.isRedeclaration()) { 17217 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17218 Diag(Previous.getRepresentativeDecl()->getLocation(), 17219 diag::note_previous_declaration); 17220 } else if (!D.isFunctionDefinition()) 17221 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17222 } 17223 17224 // Mark templated-scope function declarations as unsupported. 17225 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17226 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17227 << SS.getScopeRep() << SS.getRange() 17228 << cast<CXXRecordDecl>(CurContext); 17229 FrD->setUnsupportedFriend(true); 17230 } 17231 } 17232 17233 warnOnReservedIdentifier(ND); 17234 17235 return ND; 17236 } 17237 17238 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17239 AdjustDeclIfTemplate(Dcl); 17240 17241 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17242 if (!Fn) { 17243 Diag(DelLoc, diag::err_deleted_non_function); 17244 return; 17245 } 17246 17247 // Deleted function does not have a body. 17248 Fn->setWillHaveBody(false); 17249 17250 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17251 // Don't consider the implicit declaration we generate for explicit 17252 // specializations. FIXME: Do not generate these implicit declarations. 17253 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17254 Prev->getPreviousDecl()) && 17255 !Prev->isDefined()) { 17256 Diag(DelLoc, diag::err_deleted_decl_not_first); 17257 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17258 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17259 : diag::note_previous_declaration); 17260 // We can't recover from this; the declaration might have already 17261 // been used. 17262 Fn->setInvalidDecl(); 17263 return; 17264 } 17265 17266 // To maintain the invariant that functions are only deleted on their first 17267 // declaration, mark the implicitly-instantiated declaration of the 17268 // explicitly-specialized function as deleted instead of marking the 17269 // instantiated redeclaration. 17270 Fn = Fn->getCanonicalDecl(); 17271 } 17272 17273 // dllimport/dllexport cannot be deleted. 17274 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17275 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17276 Fn->setInvalidDecl(); 17277 } 17278 17279 // C++11 [basic.start.main]p3: 17280 // A program that defines main as deleted [...] is ill-formed. 17281 if (Fn->isMain()) 17282 Diag(DelLoc, diag::err_deleted_main); 17283 17284 // C++11 [dcl.fct.def.delete]p4: 17285 // A deleted function is implicitly inline. 17286 Fn->setImplicitlyInline(); 17287 Fn->setDeletedAsWritten(); 17288 } 17289 17290 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17291 if (!Dcl || Dcl->isInvalidDecl()) 17292 return; 17293 17294 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17295 if (!FD) { 17296 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17297 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17298 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17299 return; 17300 } 17301 } 17302 17303 Diag(DefaultLoc, diag::err_default_special_members) 17304 << getLangOpts().CPlusPlus20; 17305 return; 17306 } 17307 17308 // Reject if this can't possibly be a defaultable function. 17309 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17310 if (!DefKind && 17311 // A dependent function that doesn't locally look defaultable can 17312 // still instantiate to a defaultable function if it's a constructor 17313 // or assignment operator. 17314 (!FD->isDependentContext() || 17315 (!isa<CXXConstructorDecl>(FD) && 17316 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17317 Diag(DefaultLoc, diag::err_default_special_members) 17318 << getLangOpts().CPlusPlus20; 17319 return; 17320 } 17321 17322 // Issue compatibility warning. We already warned if the operator is 17323 // 'operator<=>' when parsing the '<=>' token. 17324 if (DefKind.isComparison() && 17325 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17326 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17327 ? diag::warn_cxx17_compat_defaulted_comparison 17328 : diag::ext_defaulted_comparison); 17329 } 17330 17331 FD->setDefaulted(); 17332 FD->setExplicitlyDefaulted(); 17333 17334 // Defer checking functions that are defaulted in a dependent context. 17335 if (FD->isDependentContext()) 17336 return; 17337 17338 // Unset that we will have a body for this function. We might not, 17339 // if it turns out to be trivial, and we don't need this marking now 17340 // that we've marked it as defaulted. 17341 FD->setWillHaveBody(false); 17342 17343 if (DefKind.isComparison()) { 17344 // If this comparison's defaulting occurs within the definition of its 17345 // lexical class context, we have to do the checking when complete. 17346 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext())) 17347 if (!RD->isCompleteDefinition()) 17348 return; 17349 } 17350 17351 // If this member fn was defaulted on its first declaration, we will have 17352 // already performed the checking in CheckCompletedCXXClass. Such a 17353 // declaration doesn't trigger an implicit definition. 17354 if (isa<CXXMethodDecl>(FD)) { 17355 const FunctionDecl *Primary = FD; 17356 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17357 // Ask the template instantiation pattern that actually had the 17358 // '= default' on it. 17359 Primary = Pattern; 17360 if (Primary->getCanonicalDecl()->isDefaulted()) 17361 return; 17362 } 17363 17364 if (DefKind.isComparison()) { 17365 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison())) 17366 FD->setInvalidDecl(); 17367 else 17368 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison()); 17369 } else { 17370 auto *MD = cast<CXXMethodDecl>(FD); 17371 17372 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17373 MD->setInvalidDecl(); 17374 else 17375 DefineDefaultedFunction(*this, MD, DefaultLoc); 17376 } 17377 } 17378 17379 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17380 for (Stmt *SubStmt : S->children()) { 17381 if (!SubStmt) 17382 continue; 17383 if (isa<ReturnStmt>(SubStmt)) 17384 Self.Diag(SubStmt->getBeginLoc(), 17385 diag::err_return_in_constructor_handler); 17386 if (!isa<Expr>(SubStmt)) 17387 SearchForReturnInStmt(Self, SubStmt); 17388 } 17389 } 17390 17391 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17392 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17393 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17394 SearchForReturnInStmt(*this, Handler); 17395 } 17396 } 17397 17398 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, 17399 FnBodyKind BodyKind) { 17400 switch (BodyKind) { 17401 case FnBodyKind::Delete: 17402 SetDeclDeleted(D, Loc); 17403 break; 17404 case FnBodyKind::Default: 17405 SetDeclDefaulted(D, Loc); 17406 break; 17407 case FnBodyKind::Other: 17408 llvm_unreachable( 17409 "Parsed function body should be '= delete;' or '= default;'"); 17410 } 17411 } 17412 17413 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17414 const CXXMethodDecl *Old) { 17415 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17416 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17417 17418 if (OldFT->hasExtParameterInfos()) { 17419 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17420 // A parameter of the overriding method should be annotated with noescape 17421 // if the corresponding parameter of the overridden method is annotated. 17422 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17423 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17424 Diag(New->getParamDecl(I)->getLocation(), 17425 diag::warn_overriding_method_missing_noescape); 17426 Diag(Old->getParamDecl(I)->getLocation(), 17427 diag::note_overridden_marked_noescape); 17428 } 17429 } 17430 17431 // Virtual overrides must have the same code_seg. 17432 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17433 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17434 if ((NewCSA || OldCSA) && 17435 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17436 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17437 Diag(Old->getLocation(), diag::note_previous_declaration); 17438 return true; 17439 } 17440 17441 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17442 17443 // If the calling conventions match, everything is fine 17444 if (NewCC == OldCC) 17445 return false; 17446 17447 // If the calling conventions mismatch because the new function is static, 17448 // suppress the calling convention mismatch error; the error about static 17449 // function override (err_static_overrides_virtual from 17450 // Sema::CheckFunctionDeclaration) is more clear. 17451 if (New->getStorageClass() == SC_Static) 17452 return false; 17453 17454 Diag(New->getLocation(), 17455 diag::err_conflicting_overriding_cc_attributes) 17456 << New->getDeclName() << New->getType() << Old->getType(); 17457 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17458 return true; 17459 } 17460 17461 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17462 const CXXMethodDecl *Old) { 17463 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17464 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17465 17466 if (Context.hasSameType(NewTy, OldTy) || 17467 NewTy->isDependentType() || OldTy->isDependentType()) 17468 return false; 17469 17470 // Check if the return types are covariant 17471 QualType NewClassTy, OldClassTy; 17472 17473 /// Both types must be pointers or references to classes. 17474 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17475 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17476 NewClassTy = NewPT->getPointeeType(); 17477 OldClassTy = OldPT->getPointeeType(); 17478 } 17479 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17480 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17481 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17482 NewClassTy = NewRT->getPointeeType(); 17483 OldClassTy = OldRT->getPointeeType(); 17484 } 17485 } 17486 } 17487 17488 // The return types aren't either both pointers or references to a class type. 17489 if (NewClassTy.isNull()) { 17490 Diag(New->getLocation(), 17491 diag::err_different_return_type_for_overriding_virtual_function) 17492 << New->getDeclName() << NewTy << OldTy 17493 << New->getReturnTypeSourceRange(); 17494 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17495 << Old->getReturnTypeSourceRange(); 17496 17497 return true; 17498 } 17499 17500 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17501 // C++14 [class.virtual]p8: 17502 // If the class type in the covariant return type of D::f differs from 17503 // that of B::f, the class type in the return type of D::f shall be 17504 // complete at the point of declaration of D::f or shall be the class 17505 // type D. 17506 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17507 if (!RT->isBeingDefined() && 17508 RequireCompleteType(New->getLocation(), NewClassTy, 17509 diag::err_covariant_return_incomplete, 17510 New->getDeclName())) 17511 return true; 17512 } 17513 17514 // Check if the new class derives from the old class. 17515 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17516 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17517 << New->getDeclName() << NewTy << OldTy 17518 << New->getReturnTypeSourceRange(); 17519 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17520 << Old->getReturnTypeSourceRange(); 17521 return true; 17522 } 17523 17524 // Check if we the conversion from derived to base is valid. 17525 if (CheckDerivedToBaseConversion( 17526 NewClassTy, OldClassTy, 17527 diag::err_covariant_return_inaccessible_base, 17528 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17529 New->getLocation(), New->getReturnTypeSourceRange(), 17530 New->getDeclName(), nullptr)) { 17531 // FIXME: this note won't trigger for delayed access control 17532 // diagnostics, and it's impossible to get an undelayed error 17533 // here from access control during the original parse because 17534 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17535 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17536 << Old->getReturnTypeSourceRange(); 17537 return true; 17538 } 17539 } 17540 17541 // The qualifiers of the return types must be the same. 17542 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17543 Diag(New->getLocation(), 17544 diag::err_covariant_return_type_different_qualifications) 17545 << New->getDeclName() << NewTy << OldTy 17546 << New->getReturnTypeSourceRange(); 17547 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17548 << Old->getReturnTypeSourceRange(); 17549 return true; 17550 } 17551 17552 17553 // The new class type must have the same or less qualifiers as the old type. 17554 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17555 Diag(New->getLocation(), 17556 diag::err_covariant_return_type_class_type_more_qualified) 17557 << New->getDeclName() << NewTy << OldTy 17558 << New->getReturnTypeSourceRange(); 17559 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17560 << Old->getReturnTypeSourceRange(); 17561 return true; 17562 } 17563 17564 return false; 17565 } 17566 17567 /// Mark the given method pure. 17568 /// 17569 /// \param Method the method to be marked pure. 17570 /// 17571 /// \param InitRange the source range that covers the "0" initializer. 17572 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17573 SourceLocation EndLoc = InitRange.getEnd(); 17574 if (EndLoc.isValid()) 17575 Method->setRangeEnd(EndLoc); 17576 17577 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17578 Method->setPure(); 17579 return false; 17580 } 17581 17582 if (!Method->isInvalidDecl()) 17583 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17584 << Method->getDeclName() << InitRange; 17585 return true; 17586 } 17587 17588 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17589 if (D->getFriendObjectKind()) 17590 Diag(D->getLocation(), diag::err_pure_friend); 17591 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17592 CheckPureMethod(M, ZeroLoc); 17593 else 17594 Diag(D->getLocation(), diag::err_illegal_initializer); 17595 } 17596 17597 /// Determine whether the given declaration is a global variable or 17598 /// static data member. 17599 static bool isNonlocalVariable(const Decl *D) { 17600 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17601 return Var->hasGlobalStorage(); 17602 17603 return false; 17604 } 17605 17606 /// Invoked when we are about to parse an initializer for the declaration 17607 /// 'Dcl'. 17608 /// 17609 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17610 /// static data member of class X, names should be looked up in the scope of 17611 /// class X. If the declaration had a scope specifier, a scope will have 17612 /// been created and passed in for this purpose. Otherwise, S will be null. 17613 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17614 // If there is no declaration, there was an error parsing it. 17615 if (!D || D->isInvalidDecl()) 17616 return; 17617 17618 // We will always have a nested name specifier here, but this declaration 17619 // might not be out of line if the specifier names the current namespace: 17620 // extern int n; 17621 // int ::n = 0; 17622 if (S && D->isOutOfLine()) 17623 EnterDeclaratorContext(S, D->getDeclContext()); 17624 17625 // If we are parsing the initializer for a static data member, push a 17626 // new expression evaluation context that is associated with this static 17627 // data member. 17628 if (isNonlocalVariable(D)) 17629 PushExpressionEvaluationContext( 17630 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17631 } 17632 17633 /// Invoked after we are finished parsing an initializer for the declaration D. 17634 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17635 // If there is no declaration, there was an error parsing it. 17636 if (!D || D->isInvalidDecl()) 17637 return; 17638 17639 if (isNonlocalVariable(D)) 17640 PopExpressionEvaluationContext(); 17641 17642 if (S && D->isOutOfLine()) 17643 ExitDeclaratorContext(S); 17644 } 17645 17646 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17647 /// C++ if/switch/while/for statement. 17648 /// e.g: "if (int x = f()) {...}" 17649 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17650 // C++ 6.4p2: 17651 // The declarator shall not specify a function or an array. 17652 // The type-specifier-seq shall not contain typedef and shall not declare a 17653 // new class or enumeration. 17654 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17655 "Parser allowed 'typedef' as storage class of condition decl."); 17656 17657 Decl *Dcl = ActOnDeclarator(S, D); 17658 if (!Dcl) 17659 return true; 17660 17661 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17662 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17663 << D.getSourceRange(); 17664 return true; 17665 } 17666 17667 return Dcl; 17668 } 17669 17670 void Sema::LoadExternalVTableUses() { 17671 if (!ExternalSource) 17672 return; 17673 17674 SmallVector<ExternalVTableUse, 4> VTables; 17675 ExternalSource->ReadUsedVTables(VTables); 17676 SmallVector<VTableUse, 4> NewUses; 17677 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17678 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17679 = VTablesUsed.find(VTables[I].Record); 17680 // Even if a definition wasn't required before, it may be required now. 17681 if (Pos != VTablesUsed.end()) { 17682 if (!Pos->second && VTables[I].DefinitionRequired) 17683 Pos->second = true; 17684 continue; 17685 } 17686 17687 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17688 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17689 } 17690 17691 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17692 } 17693 17694 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17695 bool DefinitionRequired) { 17696 // Ignore any vtable uses in unevaluated operands or for classes that do 17697 // not have a vtable. 17698 if (!Class->isDynamicClass() || Class->isDependentContext() || 17699 CurContext->isDependentContext() || isUnevaluatedContext()) 17700 return; 17701 // Do not mark as used if compiling for the device outside of the target 17702 // region. 17703 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17704 !isInOpenMPDeclareTargetContext() && 17705 !isInOpenMPTargetExecutionDirective()) { 17706 if (!DefinitionRequired) 17707 MarkVirtualMembersReferenced(Loc, Class); 17708 return; 17709 } 17710 17711 // Try to insert this class into the map. 17712 LoadExternalVTableUses(); 17713 Class = Class->getCanonicalDecl(); 17714 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17715 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17716 if (!Pos.second) { 17717 // If we already had an entry, check to see if we are promoting this vtable 17718 // to require a definition. If so, we need to reappend to the VTableUses 17719 // list, since we may have already processed the first entry. 17720 if (DefinitionRequired && !Pos.first->second) { 17721 Pos.first->second = true; 17722 } else { 17723 // Otherwise, we can early exit. 17724 return; 17725 } 17726 } else { 17727 // The Microsoft ABI requires that we perform the destructor body 17728 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17729 // the deleting destructor is emitted with the vtable, not with the 17730 // destructor definition as in the Itanium ABI. 17731 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17732 CXXDestructorDecl *DD = Class->getDestructor(); 17733 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17734 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17735 // If this is an out-of-line declaration, marking it referenced will 17736 // not do anything. Manually call CheckDestructor to look up operator 17737 // delete(). 17738 ContextRAII SavedContext(*this, DD); 17739 CheckDestructor(DD); 17740 } else { 17741 MarkFunctionReferenced(Loc, Class->getDestructor()); 17742 } 17743 } 17744 } 17745 } 17746 17747 // Local classes need to have their virtual members marked 17748 // immediately. For all other classes, we mark their virtual members 17749 // at the end of the translation unit. 17750 if (Class->isLocalClass()) 17751 MarkVirtualMembersReferenced(Loc, Class); 17752 else 17753 VTableUses.push_back(std::make_pair(Class, Loc)); 17754 } 17755 17756 bool Sema::DefineUsedVTables() { 17757 LoadExternalVTableUses(); 17758 if (VTableUses.empty()) 17759 return false; 17760 17761 // Note: The VTableUses vector could grow as a result of marking 17762 // the members of a class as "used", so we check the size each 17763 // time through the loop and prefer indices (which are stable) to 17764 // iterators (which are not). 17765 bool DefinedAnything = false; 17766 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17767 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17768 if (!Class) 17769 continue; 17770 TemplateSpecializationKind ClassTSK = 17771 Class->getTemplateSpecializationKind(); 17772 17773 SourceLocation Loc = VTableUses[I].second; 17774 17775 bool DefineVTable = true; 17776 17777 // If this class has a key function, but that key function is 17778 // defined in another translation unit, we don't need to emit the 17779 // vtable even though we're using it. 17780 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17781 if (KeyFunction && !KeyFunction->hasBody()) { 17782 // The key function is in another translation unit. 17783 DefineVTable = false; 17784 TemplateSpecializationKind TSK = 17785 KeyFunction->getTemplateSpecializationKind(); 17786 assert(TSK != TSK_ExplicitInstantiationDefinition && 17787 TSK != TSK_ImplicitInstantiation && 17788 "Instantiations don't have key functions"); 17789 (void)TSK; 17790 } else if (!KeyFunction) { 17791 // If we have a class with no key function that is the subject 17792 // of an explicit instantiation declaration, suppress the 17793 // vtable; it will live with the explicit instantiation 17794 // definition. 17795 bool IsExplicitInstantiationDeclaration = 17796 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17797 for (auto R : Class->redecls()) { 17798 TemplateSpecializationKind TSK 17799 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17800 if (TSK == TSK_ExplicitInstantiationDeclaration) 17801 IsExplicitInstantiationDeclaration = true; 17802 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17803 IsExplicitInstantiationDeclaration = false; 17804 break; 17805 } 17806 } 17807 17808 if (IsExplicitInstantiationDeclaration) 17809 DefineVTable = false; 17810 } 17811 17812 // The exception specifications for all virtual members may be needed even 17813 // if we are not providing an authoritative form of the vtable in this TU. 17814 // We may choose to emit it available_externally anyway. 17815 if (!DefineVTable) { 17816 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17817 continue; 17818 } 17819 17820 // Mark all of the virtual members of this class as referenced, so 17821 // that we can build a vtable. Then, tell the AST consumer that a 17822 // vtable for this class is required. 17823 DefinedAnything = true; 17824 MarkVirtualMembersReferenced(Loc, Class); 17825 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17826 if (VTablesUsed[Canonical]) 17827 Consumer.HandleVTable(Class); 17828 17829 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17830 // no key function or the key function is inlined. Don't warn in C++ ABIs 17831 // that lack key functions, since the user won't be able to make one. 17832 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17833 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 17834 ClassTSK != TSK_ExplicitInstantiationDefinition) { 17835 const FunctionDecl *KeyFunctionDef = nullptr; 17836 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17837 KeyFunctionDef->isInlined())) 17838 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 17839 } 17840 } 17841 VTableUses.clear(); 17842 17843 return DefinedAnything; 17844 } 17845 17846 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17847 const CXXRecordDecl *RD) { 17848 for (const auto *I : RD->methods()) 17849 if (I->isVirtual() && !I->isPure()) 17850 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17851 } 17852 17853 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17854 const CXXRecordDecl *RD, 17855 bool ConstexprOnly) { 17856 // Mark all functions which will appear in RD's vtable as used. 17857 CXXFinalOverriderMap FinalOverriders; 17858 RD->getFinalOverriders(FinalOverriders); 17859 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17860 E = FinalOverriders.end(); 17861 I != E; ++I) { 17862 for (OverridingMethods::const_iterator OI = I->second.begin(), 17863 OE = I->second.end(); 17864 OI != OE; ++OI) { 17865 assert(OI->second.size() > 0 && "no final overrider"); 17866 CXXMethodDecl *Overrider = OI->second.front().Method; 17867 17868 // C++ [basic.def.odr]p2: 17869 // [...] A virtual member function is used if it is not pure. [...] 17870 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17871 MarkFunctionReferenced(Loc, Overrider); 17872 } 17873 } 17874 17875 // Only classes that have virtual bases need a VTT. 17876 if (RD->getNumVBases() == 0) 17877 return; 17878 17879 for (const auto &I : RD->bases()) { 17880 const auto *Base = 17881 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17882 if (Base->getNumVBases() == 0) 17883 continue; 17884 MarkVirtualMembersReferenced(Loc, Base); 17885 } 17886 } 17887 17888 /// SetIvarInitializers - This routine builds initialization ASTs for the 17889 /// Objective-C implementation whose ivars need be initialized. 17890 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17891 if (!getLangOpts().CPlusPlus) 17892 return; 17893 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17894 SmallVector<ObjCIvarDecl*, 8> ivars; 17895 CollectIvarsToConstructOrDestruct(OID, ivars); 17896 if (ivars.empty()) 17897 return; 17898 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17899 for (unsigned i = 0; i < ivars.size(); i++) { 17900 FieldDecl *Field = ivars[i]; 17901 if (Field->isInvalidDecl()) 17902 continue; 17903 17904 CXXCtorInitializer *Member; 17905 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17906 InitializationKind InitKind = 17907 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17908 17909 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17910 ExprResult MemberInit = 17911 InitSeq.Perform(*this, InitEntity, InitKind, None); 17912 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17913 // Note, MemberInit could actually come back empty if no initialization 17914 // is required (e.g., because it would call a trivial default constructor) 17915 if (!MemberInit.get() || MemberInit.isInvalid()) 17916 continue; 17917 17918 Member = 17919 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17920 SourceLocation(), 17921 MemberInit.getAs<Expr>(), 17922 SourceLocation()); 17923 AllToInit.push_back(Member); 17924 17925 // Be sure that the destructor is accessible and is marked as referenced. 17926 if (const RecordType *RecordTy = 17927 Context.getBaseElementType(Field->getType()) 17928 ->getAs<RecordType>()) { 17929 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17930 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17931 MarkFunctionReferenced(Field->getLocation(), Destructor); 17932 CheckDestructorAccess(Field->getLocation(), Destructor, 17933 PDiag(diag::err_access_dtor_ivar) 17934 << Context.getBaseElementType(Field->getType())); 17935 } 17936 } 17937 } 17938 ObjCImplementation->setIvarInitializers(Context, 17939 AllToInit.data(), AllToInit.size()); 17940 } 17941 } 17942 17943 static 17944 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17945 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17946 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17947 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17948 Sema &S) { 17949 if (Ctor->isInvalidDecl()) 17950 return; 17951 17952 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17953 17954 // Target may not be determinable yet, for instance if this is a dependent 17955 // call in an uninstantiated template. 17956 if (Target) { 17957 const FunctionDecl *FNTarget = nullptr; 17958 (void)Target->hasBody(FNTarget); 17959 Target = const_cast<CXXConstructorDecl*>( 17960 cast_or_null<CXXConstructorDecl>(FNTarget)); 17961 } 17962 17963 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17964 // Avoid dereferencing a null pointer here. 17965 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17966 17967 if (!Current.insert(Canonical).second) 17968 return; 17969 17970 // We know that beyond here, we aren't chaining into a cycle. 17971 if (!Target || !Target->isDelegatingConstructor() || 17972 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17973 Valid.insert(Current.begin(), Current.end()); 17974 Current.clear(); 17975 // We've hit a cycle. 17976 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17977 Current.count(TCanonical)) { 17978 // If we haven't diagnosed this cycle yet, do so now. 17979 if (!Invalid.count(TCanonical)) { 17980 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17981 diag::warn_delegating_ctor_cycle) 17982 << Ctor; 17983 17984 // Don't add a note for a function delegating directly to itself. 17985 if (TCanonical != Canonical) 17986 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17987 17988 CXXConstructorDecl *C = Target; 17989 while (C->getCanonicalDecl() != Canonical) { 17990 const FunctionDecl *FNTarget = nullptr; 17991 (void)C->getTargetConstructor()->hasBody(FNTarget); 17992 assert(FNTarget && "Ctor cycle through bodiless function"); 17993 17994 C = const_cast<CXXConstructorDecl*>( 17995 cast<CXXConstructorDecl>(FNTarget)); 17996 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17997 } 17998 } 17999 18000 Invalid.insert(Current.begin(), Current.end()); 18001 Current.clear(); 18002 } else { 18003 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 18004 } 18005 } 18006 18007 18008 void Sema::CheckDelegatingCtorCycles() { 18009 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 18010 18011 for (DelegatingCtorDeclsType::iterator 18012 I = DelegatingCtorDecls.begin(ExternalSource), 18013 E = DelegatingCtorDecls.end(); 18014 I != E; ++I) 18015 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 18016 18017 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 18018 (*CI)->setInvalidDecl(); 18019 } 18020 18021 namespace { 18022 /// AST visitor that finds references to the 'this' expression. 18023 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 18024 Sema &S; 18025 18026 public: 18027 explicit FindCXXThisExpr(Sema &S) : S(S) { } 18028 18029 bool VisitCXXThisExpr(CXXThisExpr *E) { 18030 S.Diag(E->getLocation(), diag::err_this_static_member_func) 18031 << E->isImplicit(); 18032 return false; 18033 } 18034 }; 18035 } 18036 18037 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 18038 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18039 if (!TSInfo) 18040 return false; 18041 18042 TypeLoc TL = TSInfo->getTypeLoc(); 18043 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18044 if (!ProtoTL) 18045 return false; 18046 18047 // C++11 [expr.prim.general]p3: 18048 // [The expression this] shall not appear before the optional 18049 // cv-qualifier-seq and it shall not appear within the declaration of a 18050 // static member function (although its type and value category are defined 18051 // within a static member function as they are within a non-static member 18052 // function). [ Note: this is because declaration matching does not occur 18053 // until the complete declarator is known. - end note ] 18054 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18055 FindCXXThisExpr Finder(*this); 18056 18057 // If the return type came after the cv-qualifier-seq, check it now. 18058 if (Proto->hasTrailingReturn() && 18059 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 18060 return true; 18061 18062 // Check the exception specification. 18063 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 18064 return true; 18065 18066 // Check the trailing requires clause 18067 if (Expr *E = Method->getTrailingRequiresClause()) 18068 if (!Finder.TraverseStmt(E)) 18069 return true; 18070 18071 return checkThisInStaticMemberFunctionAttributes(Method); 18072 } 18073 18074 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 18075 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18076 if (!TSInfo) 18077 return false; 18078 18079 TypeLoc TL = TSInfo->getTypeLoc(); 18080 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18081 if (!ProtoTL) 18082 return false; 18083 18084 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18085 FindCXXThisExpr Finder(*this); 18086 18087 switch (Proto->getExceptionSpecType()) { 18088 case EST_Unparsed: 18089 case EST_Uninstantiated: 18090 case EST_Unevaluated: 18091 case EST_BasicNoexcept: 18092 case EST_NoThrow: 18093 case EST_DynamicNone: 18094 case EST_MSAny: 18095 case EST_None: 18096 break; 18097 18098 case EST_DependentNoexcept: 18099 case EST_NoexceptFalse: 18100 case EST_NoexceptTrue: 18101 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 18102 return true; 18103 LLVM_FALLTHROUGH; 18104 18105 case EST_Dynamic: 18106 for (const auto &E : Proto->exceptions()) { 18107 if (!Finder.TraverseType(E)) 18108 return true; 18109 } 18110 break; 18111 } 18112 18113 return false; 18114 } 18115 18116 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 18117 FindCXXThisExpr Finder(*this); 18118 18119 // Check attributes. 18120 for (const auto *A : Method->attrs()) { 18121 // FIXME: This should be emitted by tblgen. 18122 Expr *Arg = nullptr; 18123 ArrayRef<Expr *> Args; 18124 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 18125 Arg = G->getArg(); 18126 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 18127 Arg = G->getArg(); 18128 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 18129 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 18130 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 18131 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 18132 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 18133 Arg = ETLF->getSuccessValue(); 18134 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 18135 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 18136 Arg = STLF->getSuccessValue(); 18137 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 18138 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 18139 Arg = LR->getArg(); 18140 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 18141 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 18142 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 18143 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18144 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 18145 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18146 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 18147 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 18148 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 18149 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 18150 18151 if (Arg && !Finder.TraverseStmt(Arg)) 18152 return true; 18153 18154 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 18155 if (!Finder.TraverseStmt(Args[I])) 18156 return true; 18157 } 18158 } 18159 18160 return false; 18161 } 18162 18163 void Sema::checkExceptionSpecification( 18164 bool IsTopLevel, ExceptionSpecificationType EST, 18165 ArrayRef<ParsedType> DynamicExceptions, 18166 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 18167 SmallVectorImpl<QualType> &Exceptions, 18168 FunctionProtoType::ExceptionSpecInfo &ESI) { 18169 Exceptions.clear(); 18170 ESI.Type = EST; 18171 if (EST == EST_Dynamic) { 18172 Exceptions.reserve(DynamicExceptions.size()); 18173 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 18174 // FIXME: Preserve type source info. 18175 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 18176 18177 if (IsTopLevel) { 18178 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 18179 collectUnexpandedParameterPacks(ET, Unexpanded); 18180 if (!Unexpanded.empty()) { 18181 DiagnoseUnexpandedParameterPacks( 18182 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18183 Unexpanded); 18184 continue; 18185 } 18186 } 18187 18188 // Check that the type is valid for an exception spec, and 18189 // drop it if not. 18190 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18191 Exceptions.push_back(ET); 18192 } 18193 ESI.Exceptions = Exceptions; 18194 return; 18195 } 18196 18197 if (isComputedNoexcept(EST)) { 18198 assert((NoexceptExpr->isTypeDependent() || 18199 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18200 Context.BoolTy) && 18201 "Parser should have made sure that the expression is boolean"); 18202 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18203 ESI.Type = EST_BasicNoexcept; 18204 return; 18205 } 18206 18207 ESI.NoexceptExpr = NoexceptExpr; 18208 return; 18209 } 18210 } 18211 18212 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18213 ExceptionSpecificationType EST, 18214 SourceRange SpecificationRange, 18215 ArrayRef<ParsedType> DynamicExceptions, 18216 ArrayRef<SourceRange> DynamicExceptionRanges, 18217 Expr *NoexceptExpr) { 18218 if (!MethodD) 18219 return; 18220 18221 // Dig out the method we're referring to. 18222 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18223 MethodD = FunTmpl->getTemplatedDecl(); 18224 18225 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18226 if (!Method) 18227 return; 18228 18229 // Check the exception specification. 18230 llvm::SmallVector<QualType, 4> Exceptions; 18231 FunctionProtoType::ExceptionSpecInfo ESI; 18232 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18233 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18234 ESI); 18235 18236 // Update the exception specification on the function type. 18237 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18238 18239 if (Method->isStatic()) 18240 checkThisInStaticMemberFunctionExceptionSpec(Method); 18241 18242 if (Method->isVirtual()) { 18243 // Check overrides, which we previously had to delay. 18244 for (const CXXMethodDecl *O : Method->overridden_methods()) 18245 CheckOverridingFunctionExceptionSpec(Method, O); 18246 } 18247 } 18248 18249 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18250 /// 18251 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18252 SourceLocation DeclStart, Declarator &D, 18253 Expr *BitWidth, 18254 InClassInitStyle InitStyle, 18255 AccessSpecifier AS, 18256 const ParsedAttr &MSPropertyAttr) { 18257 IdentifierInfo *II = D.getIdentifier(); 18258 if (!II) { 18259 Diag(DeclStart, diag::err_anonymous_property); 18260 return nullptr; 18261 } 18262 SourceLocation Loc = D.getIdentifierLoc(); 18263 18264 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18265 QualType T = TInfo->getType(); 18266 if (getLangOpts().CPlusPlus) { 18267 CheckExtraCXXDefaultArguments(D); 18268 18269 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18270 UPPC_DataMemberType)) { 18271 D.setInvalidType(); 18272 T = Context.IntTy; 18273 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18274 } 18275 } 18276 18277 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18278 18279 if (D.getDeclSpec().isInlineSpecified()) 18280 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18281 << getLangOpts().CPlusPlus17; 18282 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18283 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18284 diag::err_invalid_thread) 18285 << DeclSpec::getSpecifierName(TSCS); 18286 18287 // Check to see if this name was declared as a member previously 18288 NamedDecl *PrevDecl = nullptr; 18289 LookupResult Previous(*this, II, Loc, LookupMemberName, 18290 ForVisibleRedeclaration); 18291 LookupName(Previous, S); 18292 switch (Previous.getResultKind()) { 18293 case LookupResult::Found: 18294 case LookupResult::FoundUnresolvedValue: 18295 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18296 break; 18297 18298 case LookupResult::FoundOverloaded: 18299 PrevDecl = Previous.getRepresentativeDecl(); 18300 break; 18301 18302 case LookupResult::NotFound: 18303 case LookupResult::NotFoundInCurrentInstantiation: 18304 case LookupResult::Ambiguous: 18305 break; 18306 } 18307 18308 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18309 // Maybe we will complain about the shadowed template parameter. 18310 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18311 // Just pretend that we didn't see the previous declaration. 18312 PrevDecl = nullptr; 18313 } 18314 18315 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18316 PrevDecl = nullptr; 18317 18318 SourceLocation TSSL = D.getBeginLoc(); 18319 MSPropertyDecl *NewPD = 18320 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18321 MSPropertyAttr.getPropertyDataGetter(), 18322 MSPropertyAttr.getPropertyDataSetter()); 18323 ProcessDeclAttributes(TUScope, NewPD, D); 18324 NewPD->setAccess(AS); 18325 18326 if (NewPD->isInvalidDecl()) 18327 Record->setInvalidDecl(); 18328 18329 if (D.getDeclSpec().isModulePrivateSpecified()) 18330 NewPD->setModulePrivate(); 18331 18332 if (NewPD->isInvalidDecl() && PrevDecl) { 18333 // Don't introduce NewFD into scope; there's already something 18334 // with the same name in the same scope. 18335 } else if (II) { 18336 PushOnScopeChains(NewPD, S); 18337 } else 18338 Record->addDecl(NewPD); 18339 18340 return NewPD; 18341 } 18342 18343 void Sema::ActOnStartFunctionDeclarationDeclarator( 18344 Declarator &Declarator, unsigned TemplateParameterDepth) { 18345 auto &Info = InventedParameterInfos.emplace_back(); 18346 TemplateParameterList *ExplicitParams = nullptr; 18347 ArrayRef<TemplateParameterList *> ExplicitLists = 18348 Declarator.getTemplateParameterLists(); 18349 if (!ExplicitLists.empty()) { 18350 bool IsMemberSpecialization, IsInvalid; 18351 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18352 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18353 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18354 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18355 /*SuppressDiagnostic=*/true); 18356 } 18357 if (ExplicitParams) { 18358 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18359 llvm::append_range(Info.TemplateParams, *ExplicitParams); 18360 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18361 } else { 18362 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18363 Info.NumExplicitTemplateParams = 0; 18364 } 18365 } 18366 18367 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18368 auto &FSI = InventedParameterInfos.back(); 18369 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18370 if (FSI.NumExplicitTemplateParams != 0) { 18371 TemplateParameterList *ExplicitParams = 18372 Declarator.getTemplateParameterLists().back(); 18373 Declarator.setInventedTemplateParameterList( 18374 TemplateParameterList::Create( 18375 Context, ExplicitParams->getTemplateLoc(), 18376 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18377 ExplicitParams->getRAngleLoc(), 18378 ExplicitParams->getRequiresClause())); 18379 } else { 18380 Declarator.setInventedTemplateParameterList( 18381 TemplateParameterList::Create( 18382 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18383 SourceLocation(), /*RequiresClause=*/nullptr)); 18384 } 18385 } 18386 InventedParameterInfos.pop_back(); 18387 } 18388